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
RelativeMargin
import torch import torch.nn as nn class RelativeMargin(nn.Module): def __init__(self): super(RelativeMargin, self).__init__() def forward(self, x1, x2, y1, y2, t, reduce=True): if reduce: loss = torch.mean(torch.clamp(torch.abs(y1 - y2) - t * (x1 - x2 ), 0.0)) else: loss = torch.sum(torch.clamp(torch.abs(y1 - y2) - t * (x1 - x2), 0.0)) return 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])] 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_per_fused_abs_clamp_mean_mul_sub_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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) tmp4 = tl.load(in_ptr2 + r0, None) tmp5 = tl.load(in_ptr3 + r0, None) tmp6 = tl.load(in_ptr4 + r0, None) tmp2 = tmp0 - tmp1 tmp3 = tl_math.abs(tmp2) tmp7 = tmp5 - tmp6 tmp8 = tmp4 * tmp7 tmp9 = tmp3 - tmp8 tmp10 = 0.0 tmp11 = triton_helpers.maximum(tmp9, tmp10) tmp12 = tl.broadcast_to(tmp11, [RBLOCK]) tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0)) tmp15 = 256.0 tmp16 = tmp14 / tmp15 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp16, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_1, arg4_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)) 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_mean_mul_sub_0[grid(1)](buf1, arg0_1, arg1_1, arg4_1, arg2_1, arg3_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 del arg4_1 return buf1, class RelativeMarginNew(nn.Module): def __init__(self): super(RelativeMarginNew, self).__init__() def forward(self, input_0, input_1, input_2, input_3, input_4): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 arg3_1 = input_3 arg4_1 = input_4 output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1]) return output[0]
UKPLab/ijcai2019-relis
RelativeMargin
false
18,025
[ "MIT" ]
5
8a40762dcfa90c075a4f6591cbdceb468026ef17
https://github.com/UKPLab/ijcai2019-relis/tree/8a40762dcfa90c075a4f6591cbdceb468026ef17
TVLoss
import torch from torch import nn class TVLoss(nn.Module): """ Total variation loss. """ def __init__(self): super(TVLoss, self).__init__() def forward(self, yhat, y): _bsize, _chan, height, width = y.size() dyh = torch.abs(y[:, :, 1:, :] - y[:, :, :-1, :]) dyhath = torch.abs(yhat[:, :, 1:, :] - yhat[:, :, :-1, :]) dyw = torch.abs(y[:, :, :, 1:] - y[:, :, :, :-1]) dyhatw = torch.abs(yhat[:, :, :, 1:] - yhat[:, :, :, :-1]) error = torch.norm(dyh - dyhath, 1) / height + torch.norm(dyw - dyhatw, 1) / width return error 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.triton_helpers import 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_abs_add_div_linalg_vector_norm_sub_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): rnumel = 192 RBLOCK: tl.constexpr = 256 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, :] rmask = rindex < rnumel r0 = rindex % 12 r1 = rindex // 12 r2 = rindex % 3 r3 = rindex // 3 tmp0 = tl.load(in_ptr0 + (4 + r0 + 16 * r1), rmask, other=0.0) tmp1 = tl.load(in_ptr0 + (r0 + 16 * r1), rmask, other=0.0) tmp4 = tl.load(in_ptr1 + (4 + r0 + 16 * r1), rmask, other=0.0) tmp5 = tl.load(in_ptr1 + (r0 + 16 * r1), rmask, other=0.0) tmp14 = tl.load(in_ptr0 + (1 + r2 + 4 * r3), rmask, other=0.0) tmp15 = tl.load(in_ptr0 + (r2 + 4 * r3), rmask, other=0.0) tmp18 = tl.load(in_ptr1 + (1 + r2 + 4 * r3), rmask, other=0.0) tmp19 = tl.load(in_ptr1 + (r2 + 4 * r3), rmask, other=0.0) tmp2 = tmp0 - tmp1 tmp3 = tl_math.abs(tmp2) tmp6 = tmp4 - tmp5 tmp7 = tl_math.abs(tmp6) tmp8 = tmp3 - tmp7 tmp9 = tl_math.abs(tmp8) tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK]) tmp12 = tl.where(rmask, tmp10, 0) tmp13 = tl.sum(tmp12, 1)[:, None] tmp16 = tmp14 - tmp15 tmp17 = tl_math.abs(tmp16) tmp20 = tmp18 - tmp19 tmp21 = tl_math.abs(tmp20) tmp22 = tmp17 - tmp21 tmp23 = tl_math.abs(tmp22) tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK]) tmp26 = tl.where(rmask, tmp24, 0) tmp27 = tl.sum(tmp26, 1)[:, None] tmp28 = 0.25 tmp29 = tmp13 * tmp28 tmp30 = tmp27 * tmp28 tmp31 = tmp29 + tmp30 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp31, 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) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_abs_add_div_linalg_vector_norm_sub_0[grid(1)](buf2, arg0_1, arg1_1, 1, 192, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf2, class TVLossNew(nn.Module): """ Total variation loss. """ def __init__(self): super(TVLossNew, self).__init__() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
TiagoCortinhal/SR_GAN
TVLoss
false
18,026
[ "MIT" ]
4
9ccceaa25e87e404d20825dbb552fa6a2ef3af47
https://github.com/TiagoCortinhal/SR_GAN/tree/9ccceaa25e87e404d20825dbb552fa6a2ef3af47
SoftDetectionModule
import torch import torch.nn.functional as F import torch.nn as nn class SoftDetectionModule(nn.Module): def __init__(self, soft_local_max_size=3): super(SoftDetectionModule, self).__init__() self.soft_local_max_size = soft_local_max_size self.pad = self.soft_local_max_size // 2 def forward(self, batch): b = batch.size(0) batch = F.relu(batch) max_per_sample = torch.max(batch.view(b, -1), dim=1)[0] exp = torch.exp(batch / max_per_sample.view(b, 1, 1, 1)) sum_exp = self.soft_local_max_size ** 2 * F.avg_pool2d(F.pad(exp, [ self.pad] * 4, mode='constant', value=1.0), self. soft_local_max_size, stride=1) local_max_score = exp / sum_exp depth_wise_max = torch.max(batch, dim=1)[0] depth_wise_max_score = batch / depth_wise_max.unsqueeze(1) all_scores = local_max_score * depth_wise_max_score score = torch.max(all_scores, dim=1)[0] score = score / (torch.sum(score.view(b, -1), dim=1).view(b, 1, 1) + 1e-05) return score 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 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_max_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl. constexpr): xnumel = 4 RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0) tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.where(xmask, tmp3, float('-inf')) tmp6 = triton_helpers.max2(tmp5, 1)[:, None] tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_constant_pad_nd_div_exp_relu_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 576 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 6 % 6 x0 = xindex % 6 x4 = xindex // 36 x3 = xindex // 144 x6 = xindex tmp0 = -1 + x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = -1 + x0 tmp6 = tmp5 >= tmp1 tmp7 = tmp5 < tmp3 tmp8 = tmp2 & tmp4 tmp9 = tmp8 & tmp6 tmp10 = tmp9 & tmp7 tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x4), tmp10 & xmask, other=0.0) tmp12 = tl.full([1], 0, tl.int32) tmp13 = triton_helpers.maximum(tmp12, tmp11) tmp14 = tl.load(in_ptr1 + x3, tmp10 & xmask, eviction_policy= 'evict_last', other=0.0) tmp15 = tmp13 / tmp14 tmp16 = tl_math.exp(tmp15) tmp17 = tl.full(tmp16.shape, 1.0, tmp16.dtype) tmp18 = tl.where(tmp10, tmp16, tmp17) tl.store(out_ptr0 + x6, tmp18, xmask) @triton.jit def triton_poi_fused_avg_pool2d_constant_pad_nd_div_exp_relu_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 x0 = xindex % 4 x1 = xindex // 4 % 4 x2 = xindex // 16 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 6 * x1 + 36 * x2), xmask) tmp1 = tl.load(in_ptr0 + (1 + x0 + 6 * x1 + 36 * x2), xmask) tmp3 = tl.load(in_ptr0 + (2 + x0 + 6 * x1 + 36 * x2), xmask) tmp5 = tl.load(in_ptr0 + (6 + x0 + 6 * x1 + 36 * x2), xmask) tmp7 = tl.load(in_ptr0 + (7 + x0 + 6 * x1 + 36 * x2), xmask) tmp9 = tl.load(in_ptr0 + (8 + x0 + 6 * x1 + 36 * x2), xmask) tmp11 = tl.load(in_ptr0 + (12 + x0 + 6 * x1 + 36 * x2), xmask) tmp13 = tl.load(in_ptr0 + (13 + x0 + 6 * x1 + 36 * x2), xmask) tmp15 = tl.load(in_ptr0 + (14 + x0 + 6 * x1 + 36 * x2), xmask) tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp8 = tmp7 + tmp6 tmp10 = tmp9 + tmp8 tmp12 = tmp11 + tmp10 tmp14 = tmp13 + tmp12 tmp16 = tmp15 + tmp14 tmp17 = 0.1111111111111111 tmp18 = tmp16 * tmp17 tl.store(out_ptr0 + x3, tmp18, xmask) @triton.jit def triton_per_fused_add_div_exp_max_mul_relu_sum_3(in_ptr0, in_ptr1, in_ptr2, out_ptr2, 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_ptr0 + (r1 + 64 * x0), xmask, other=0.0) tmp3 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr2 + (r1 + 64 * x0), xmask, other=0.0) tmp10 = tl.load(in_ptr0 + (16 + r1 + 64 * x0), xmask, other=0.0) tmp13 = tl.load(in_ptr0 + (32 + r1 + 64 * x0), xmask, other=0.0) tmp16 = tl.load(in_ptr0 + (48 + r1 + 64 * x0), xmask, other=0.0) tmp23 = tl.load(in_ptr2 + (16 + r1 + 64 * x0), xmask, other=0.0) tmp31 = tl.load(in_ptr2 + (32 + r1 + 64 * x0), xmask, other=0.0) tmp39 = tl.load(in_ptr2 + (48 + r1 + 64 * x0), xmask, other=0.0) tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 / tmp3 tmp5 = tl_math.exp(tmp4) tmp7 = 9.0 tmp8 = tmp6 * tmp7 tmp9 = tmp5 / tmp8 tmp11 = triton_helpers.maximum(tmp1, tmp10) tmp12 = triton_helpers.maximum(tmp2, tmp11) tmp14 = triton_helpers.maximum(tmp1, tmp13) tmp15 = triton_helpers.maximum(tmp12, tmp14) tmp17 = triton_helpers.maximum(tmp1, tmp16) tmp18 = triton_helpers.maximum(tmp15, tmp17) tmp19 = tmp2 / tmp18 tmp20 = tmp9 * tmp19 tmp21 = tmp11 / tmp3 tmp22 = tl_math.exp(tmp21) tmp24 = tmp23 * tmp7 tmp25 = tmp22 / tmp24 tmp26 = tmp11 / tmp18 tmp27 = tmp25 * tmp26 tmp28 = triton_helpers.maximum(tmp20, tmp27) tmp29 = tmp14 / tmp3 tmp30 = tl_math.exp(tmp29) tmp32 = tmp31 * tmp7 tmp33 = tmp30 / tmp32 tmp34 = tmp14 / tmp18 tmp35 = tmp33 * tmp34 tmp36 = triton_helpers.maximum(tmp28, tmp35) tmp37 = tmp17 / tmp3 tmp38 = tl_math.exp(tmp37) tmp40 = tmp39 * tmp7 tmp41 = tmp38 / tmp40 tmp42 = tmp17 / tmp18 tmp43 = tmp41 * tmp42 tmp44 = triton_helpers.maximum(tmp36, tmp43) tmp45 = tl.broadcast_to(tmp44, [XBLOCK, RBLOCK]) tmp47 = tl.where(xmask, tmp45, 0) tmp48 = tl.sum(tmp47, 1)[:, None] tmp49 = 1e-05 tmp50 = tmp48 + tmp49 tmp51 = tmp44 / tmp50 tl.store(out_ptr2 + (r1 + 16 * x0), tmp51, 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,), (1,), torch.float32) get_raw_stream(0) triton_per_fused_max_0[grid(4)](arg0_1, buf0, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) buf2 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32) triton_poi_fused_constant_pad_nd_div_exp_relu_1[grid(576)](arg0_1, buf0, buf2, 576, XBLOCK=128, num_warps=4, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_avg_pool2d_constant_pad_nd_div_exp_relu_2[grid(256)]( buf2, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf2 buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_per_fused_add_div_exp_max_mul_relu_sum_3[grid(4)](arg0_1, buf0, buf3, buf6, 4, 16, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del buf0 del buf3 return buf6, class SoftDetectionModuleNew(nn.Module): def __init__(self, soft_local_max_size=3): super(SoftDetectionModuleNew, self).__init__() self.soft_local_max_size = soft_local_max_size self.pad = self.soft_local_max_size // 2 def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
UditSinghParihar/d2-net
SoftDetectionModule
false
18,027
[ "BSD-3-Clause-Clear" ]
6
b3592beebe6759cf4cc1acdfd23d603ef059ef30
https://github.com/UditSinghParihar/d2-net/tree/b3592beebe6759cf4cc1acdfd23d603ef059ef30
FRN
import torch import torch.nn as nn class FRN(nn.Module): def __init__(self, num_features, eps=1e-05): super(FRN, self).__init__() self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.gamma = nn.Parameter(torch.ones(1, num_features, 1, 1)) self.beta = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.eps = eps def forward(self, x): x = x * torch.rsqrt(torch.mean(x ** 2, dim=[2, 3], keepdim=True) + self.eps) return torch.max(self.gamma * x + self.beta, self.tau) 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 import triton_helpers 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_per_fused_add_maximum_mean_mul_pow_rsqrt_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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) r1 = rindex x0 = xindex x2 = xindex % 4 tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp11 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last') tmp14 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last') tmp16 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last') tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.where(xmask, tmp2, 0) tmp5 = tl.sum(tmp4, 1)[:, None] tmp6 = 16.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp12 = tmp0 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tmp17 = triton_helpers.maximum(tmp15, tmp16) tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp10, xmask) tl.store(out_ptr0 + (r1 + 16 * x0), tmp17, 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, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_4, (1, 4, 1, 1), (4, 1, 1, 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 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_maximum_mean_mul_pow_rsqrt_0[grid(16)](buf1, primals_1, primals_2, primals_3, primals_4, buf2, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) return buf2, primals_1, primals_2, primals_3, primals_4, buf1 class FRNNew(nn.Module): def __init__(self, num_features, eps=1e-05): super(FRNNew, self).__init__() self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.gamma = nn.Parameter(torch.ones(1, num_features, 1, 1)) self.beta = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.eps = eps def forward(self, input_0): primals_2 = self.tau primals_3 = self.gamma primals_4 = self.beta primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
UdonDa/StarGAN-v2-pytorch-nonofficial
FRN
false
18,028
[ "MIT" ]
9
219df6b7fd4bd533686e2093ee914a337914ca9b
https://github.com/UdonDa/StarGAN-v2-pytorch-nonofficial/tree/219df6b7fd4bd533686e2093ee914a337914ca9b
Discriminator
import torch import torch.nn as nn import torch.nn.functional as F class Discriminator(nn.Module): def __init__(self, in_dim, hidden_dim=100): super(Discriminator, self).__init__() self.fc1 = nn.Linear(in_dim, 256) nn.init.xavier_normal(self.fc1.weight) nn.init.constant(self.fc1.bias, 0.0) self.fc2 = nn.Linear(256, 512) nn.init.xavier_normal(self.fc2.weight) nn.init.constant(self.fc2.bias, 0.0) self.fc3 = nn.Linear(512, 1) nn.init.xavier_normal(self.fc3.weight) nn.init.constant(self.fc3.bias, 0.0) def forward(self, x, TASK=2): h1 = F.relu(self.fc1(x)) h2 = F.relu(self.fc2(h1)) if TASK == 1 or TASK == 2: score = F.sigmoid(self.fc3(h2)) else: score = self.fc3(h2) return score def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_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_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 % 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) 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_relu_threshold_backward_1(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 % 512 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_sigmoid_2(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, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (256, 4), (4, 1)) assert_size_stride(primals_2, (256,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (512, 256), (256, 1)) assert_size_stride(primals_5, (512,), (1,)) assert_size_stride(primals_6, (1, 512), (512, 1)) assert_size_stride(primals_7, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 256), (256, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 256), (4096, 1024, 256, 1), 0 ) del buf0 buf7 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(16384)](buf1, primals_2, buf7, 16384, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 512), (512, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 256), (256, 1), 0), reinterpret_tensor(primals_4, (256, 512), (1, 256), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 512), (8192, 2048, 512, 1), 0 ) del buf2 buf6 = empty_strided_cuda((4, 4, 4, 512), (8192, 2048, 512, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(32768)](buf3, primals_5, buf6, 32768, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (64, 512), (512, 1), 0), reinterpret_tensor(primals_6, (512, 1), (1, 512), 0), out=buf4) buf5 = reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf4 triton_poi_fused_sigmoid_2[grid(64)](buf5, primals_7, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_7 return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 256), (256, 1), 0 ), reinterpret_tensor(buf3, (64, 512), (512, 1), 0 ), buf5, primals_6, buf6, primals_4, buf7 class DiscriminatorNew(nn.Module): def __init__(self, in_dim, hidden_dim=100): super(DiscriminatorNew, self).__init__() self.fc1 = nn.Linear(in_dim, 256) nn.init.xavier_normal(self.fc1.weight) nn.init.constant(self.fc1.bias, 0.0) self.fc2 = nn.Linear(256, 512) nn.init.xavier_normal(self.fc2.weight) nn.init.constant(self.fc2.bias, 0.0) self.fc3 = nn.Linear(512, 1) nn.init.xavier_normal(self.fc3.weight) nn.init.constant(self.fc3.bias, 0.0) 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]
Vahe1994/ThreeDLAPGAN
Discriminator
false
18,029
[ "MIT" ]
6
7e8f20be9216bc741bbe22ed2a13c261f78db521
https://github.com/Vahe1994/ThreeDLAPGAN/tree/7e8f20be9216bc741bbe22ed2a13c261f78db521
FocalLoss
import torch from torchvision.transforms import functional as F from torch import nn import torch.nn.functional as F class FocalLoss(nn.Module): def __init__(self, gamma: 'int'=2) ->None: super().__init__() self.gamma = gamma def forward(self, output: 'torch.Tensor', target: 'torch.Tensor' ) ->torch.Tensor: max_val = (-output).clamp(min=0) loss = output - output * target + max_val + ((-max_val).exp() + (- output - max_val).exp()).log() invprobs = F.logsigmoid(-output * (target * 2 - 1)) loss = (invprobs * self.gamma).exp() * loss 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, 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_add_clamp_exp_log_log_sigmoid_forward_mean_mul_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) tmp2 = tl.load(in_ptr1 + r0, None) tmp1 = -tmp0 tmp3 = 2.0 tmp4 = tmp2 * tmp3 tmp5 = 1.0 tmp6 = tmp4 - tmp5 tmp7 = tmp1 * tmp6 tmp8 = 0.0 tmp9 = triton_helpers.minimum(tmp8, tmp7) tmp10 = tl_math.abs(tmp7) tmp11 = -tmp10 tmp12 = tl_math.exp(tmp11) tmp13 = libdevice.log1p(tmp12) tmp14 = tmp9 - tmp13 tmp15 = tmp14 * tmp3 tmp16 = tl_math.exp(tmp15) tmp17 = tmp0 * tmp2 tmp18 = tmp0 - tmp17 tmp19 = triton_helpers.maximum(tmp1, tmp8) tmp20 = tmp18 + tmp19 tmp21 = -tmp19 tmp22 = tl_math.exp(tmp21) tmp23 = tmp1 - tmp19 tmp24 = tl_math.exp(tmp23) tmp25 = tmp22 + tmp24 tmp26 = tl_math.log(tmp25) tmp27 = tmp20 + tmp26 tmp28 = tmp16 * tmp27 tmp29 = tl.broadcast_to(tmp28, [RBLOCK]) tmp31 = triton_helpers.promote_to_tensor(tl.sum(tmp29, 0)) tmp32 = 256.0 tmp33 = tmp31 / 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) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_clamp_exp_log_log_sigmoid_forward_mean_mul_neg_sub_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 FocalLossNew(nn.Module): def __init__(self, gamma: 'int'=2) ->None: 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]
TylerYep/ml-toolkit
FocalLoss
false
18,030
[ "MIT" ]
7
095bdce961133acc720f90b6d1bbb0a7becbfc9f
https://github.com/TylerYep/ml-toolkit/tree/095bdce961133acc720f90b6d1bbb0a7becbfc9f
Block_local
import math import torch import numpy as np from torch import nn from torch.nn.modules.utils import _pair from functools import partial import torch.utils.data import torch.nn.parallel from torch import optim as optim def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x. device) random_tensor.floor_() output = x.div(keep_prob) * random_tensor return output class DCNv2(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, deformable_groups=1): super(DCNv2, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _pair(kernel_size) self.stride = _pair(stride) self.padding = _pair(padding) self.dilation = _pair(dilation) self.deformable_groups = deformable_groups self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels, *self.kernel_size)) self.bias = nn.Parameter(torch.Tensor(out_channels)) self.reset_parameters() def reset_parameters(self): n = self.in_channels for k in self.kernel_size: n *= k stdv = 1.0 / math.sqrt(n) self.weight.data.uniform_(-stdv, stdv) self.bias.data.zero_() def forward(self, input, offset, mask): assert 2 * self.deformable_groups * self.kernel_size[0 ] * self.kernel_size[1] == offset.shape[1] assert self.deformable_groups * self.kernel_size[0] * self.kernel_size[ 1] == mask.shape[1] return dcn_v2_conv(input, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation, self.deformable_groups) class DCN(DCNv2): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, deformable_groups=1): super(DCN, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, deformable_groups) channels_ = self.deformable_groups * 3 * self.kernel_size[0 ] * self.kernel_size[1] self.conv_offset_mask = nn.Conv2d(self.in_channels, channels_, kernel_size=self.kernel_size, stride=self.stride, padding=self. padding, bias=True) self.init_offset() def init_offset(self): self.conv_offset_mask.weight.data.zero_() self.conv_offset_mask.bias.data.zero_() def forward(self, input): out = self.conv_offset_mask(input) o1, o2, mask = torch.chunk(out, 3, dim=1) offset = torch.cat((o1, o2), dim=1) mask = torch.sigmoid(mask) return dcn_v2_conv(input, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation, self.deformable_groups) class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class LocalAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, local_ks=3, length=196): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) mask = torch.ones(length, length) for i in range(length): for j in range(i - local_ks // 2, i + local_ks // 2 + 1, 1): j = min(max(0, j), length - 1) mask[i, j] = 0 mask = mask.unsqueeze(0).unsqueeze(1) self.mask = nn.Parameter(mask, requires_grad=False) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) * self.scale attn = attn.masked_fill_(self.mask.bool(), -np.inf) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class LocalBranch(nn.Module): def __init__(self, dim, local_type='conv', local_ks=3, length=196, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.local_type = local_type if local_type == 'conv': self.linear = nn.Linear(dim, dim) self.local = nn.Conv1d(dim, dim, kernel_size=local_ks, padding= local_ks // 2, padding_mode='zeros', groups=1) elif local_type == 'dcn': self.linear = nn.Linear(dim, dim) self.local = DCN(dim, dim, kernel_size=(local_ks, 1), stride=1, padding=(local_ks // 2, 0), deformable_groups=2) elif local_type == 'attn': self.local = LocalAttention(dim, num_heads=num_heads, qkv_bias= qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop =proj_drop, local_ks=local_ks, length=length) else: self.local = nn.Identity() def forward(self, x): if self.local_type in ['conv']: x = self.linear(x) x = x.permute(0, 2, 1) x = self.local(x) x = x.permute(0, 2, 1) return x elif self.local_type == 'dcn': x = self.linear(x) x = x.permute(0, 2, 1).unsqueeze(3).contiguous() x = self.local(x) x = x.squeeze(3).permute(0, 2, 1) return x elif self.local_type == 'attn': x = self.local(x) return x else: x = self.local(x) return x class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) class Block_local(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn .GELU, norm_layer=partial(nn.LayerNorm, eps=1e-06), local_type= 'conv', local_ks=3, length=196, local_ratio=0.5, ffn_type='base'): super().__init__() local_dim = int(dim * local_ratio) self.global_dim = dim - local_dim div = 2 self.num_heads = num_heads // div self.norm1 = norm_layer(self.global_dim) self.norm1_local = norm_layer(local_dim) self.attn = Attention(self.global_dim, num_heads=self.num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.local = LocalBranch(local_dim, local_type=local_type, local_ks =local_ks, length=length, num_heads=self.num_heads, qkv_bias= qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path ) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) if ffn_type == 'base': MLP = Mlp else: raise Exception('invalid ffn_type: {}'.format(ffn_type)) self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x): x_attn = self.drop_path(self.attn(self.norm1(x[:, :, :self. global_dim]))) x_local = self.drop_path(self.local(self.norm1_local(x[:, :, self. global_dim:]))) x = x + torch.cat([x_attn, x_local], dim=2) x = x + self.drop_path(self.mlp(self.norm2(x))) return x def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'dim': 4, 'num_heads': 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 math import numpy as np from torch import nn from torch.nn.modules.utils import _pair from functools import partial import torch.utils.data import torch.nn.parallel from torch import optim as optim 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, 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') tmp2 = tmp0 + tmp1 tmp3 = 2.0 tmp4 = tmp2 / tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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 % 2 x1 = xindex // 2 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1), xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp16 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp18 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp3 - tmp1 tmp5 = tmp4 * tmp4 tmp7 = tmp6 - tmp1 tmp8 = tmp7 * tmp7 tmp9 = tmp5 + tmp8 tmp10 = 2.0 tmp11 = tmp9 / tmp10 tmp12 = 1e-06 tmp13 = tmp11 + tmp12 tmp14 = libdevice.rsqrt(tmp13) tmp15 = tmp2 * tmp14 tmp17 = tmp15 * tmp16 tmp19 = tmp17 + tmp18 tl.store(out_ptr0 + x2, tmp19, xmask) @triton.jit def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 8 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 % 2 y1 = yindex // 2 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 6 * x2 + 24 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 8 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 % 2 y1 = yindex // 2 y3 = yindex tmp0 = tl.load(in_ptr0 + (2 + y0 + 6 * x2 + 24 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 128 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 = tmp14 * tmp1 tmp16 = tl_math.exp(tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused__softmax_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 128 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_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 8 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 % 2 y1 = yindex // 2 y3 = yindex tmp0 = tl.load(in_ptr0 + (4 + y0 + 6 * x2 + 24 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_clone_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 2 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 + 8 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 2 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_native_layer_norm_8(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 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 2.0 tmp4 = tmp2 / tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused_native_layer_norm_9(in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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 % 2 x1 = xindex // 2 x2 = xindex tmp0 = tl.load(in_ptr0 + (2 + x0 + 4 * x1), xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = 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') tmp16 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp18 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp3 - tmp1 tmp5 = tmp4 * tmp4 tmp7 = tmp6 - tmp1 tmp8 = tmp7 * tmp7 tmp9 = tmp5 + tmp8 tmp10 = 2.0 tmp11 = tmp9 / tmp10 tmp12 = 1e-06 tmp13 = tmp11 + tmp12 tmp14 = libdevice.rsqrt(tmp13) tmp15 = tmp2 * tmp14 tmp17 = tmp15 * tmp16 tmp19 = tmp17 + tmp18 tl.store(out_ptr0 + x2, tmp19, xmask) @triton.jit def triton_poi_fused_convolution_10(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 8 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 % 2 y1 = yindex // 2 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 2 * x2 + 8 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_cat_11(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 % 4 x3 = xindex // 4 x1 = xindex // 4 % 4 x2 = xindex // 16 x4 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 2, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (2 * x3 + 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(tmp7.shape, 0.0, tmp7.dtype) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tmp0 >= tmp3 tl.full([1], 4, tl.int64) tmp13 = tl.load(in_ptr2 + (x1 + 4 * (-2 + x0) + 8 * x2), tmp10 & xmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.load(in_ptr3 + (-2 + 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) tl.store(out_ptr0 + x4, tmp18, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_12(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_13(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-06 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_gelu_14(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.5 tmp2 = tmp0 * tmp1 tmp3 = 0.7071067811865476 tmp4 = tmp0 * tmp3 tmp5 = libdevice.erf(tmp4) tmp6 = 1.0 tmp7 = tmp5 + tmp6 tmp8 = tmp2 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) @triton.jit def triton_poi_fused_add_15(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, 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_ptr1 + x2, xmask) tmp3 = tl.load(in_out_ptr0 + x2, xmask) tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tl.store(in_out_ptr0 + x2, 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, primals_18 ) = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (2,), (1,)) assert_size_stride(primals_3, (2,), (1,)) assert_size_stride(primals_4, (6, 2), (2, 1)) assert_size_stride(primals_5, (2, 2), (2, 1)) assert_size_stride(primals_6, (2,), (1,)) assert_size_stride(primals_7, (2,), (1,)) assert_size_stride(primals_8, (2,), (1,)) assert_size_stride(primals_9, (2, 2), (2, 1)) assert_size_stride(primals_10, (2,), (1,)) assert_size_stride(primals_11, (2, 2, 3), (6, 3, 1)) assert_size_stride(primals_12, (2,), (1,)) assert_size_stride(primals_13, (4,), (1,)) assert_size_stride(primals_14, (4,), (1,)) assert_size_stride(primals_15, (16, 4), (4, 1)) assert_size_stride(primals_16, (16,), (1,)) assert_size_stride(primals_17, (4, 16), (16, 1)) assert_size_stride(primals_18, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = 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, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(32)](primals_1, buf0, primals_2, primals_3, buf1, 32, XBLOCK=32, num_warps=1, num_stages=1) del primals_2 del primals_3 buf2 = empty_strided_cuda((16, 6), (6, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (16, 2), (2, 1), 0), reinterpret_tensor(primals_4, (2, 6), (1, 2), 0), out=buf2) buf3 = empty_strided_cuda((4, 2, 4, 1), (8, 4, 1, 1), torch.float32) triton_poi_fused_clone_2[grid(8, 4)](buf2, buf3, 8, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((4, 2, 1, 4), (8, 4, 4, 1), torch.float32) triton_poi_fused_clone_3[grid(8, 4)](buf2, buf4, 8, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((8, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (8, 4, 1), (4, 1, 0), 0 ), reinterpret_tensor(buf4, (8, 1, 4), (4, 0, 1), 0), out=buf5) buf6 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32) triton_poi_fused__softmax_4[grid(128)](buf5, buf6, 128, XBLOCK=128, num_warps=4, num_stages=1) buf7 = reinterpret_tensor(buf5, (4, 2, 4, 4), (32, 16, 4, 1), 0) del buf5 triton_poi_fused__softmax_5[grid(128)](buf6, buf7, 128, XBLOCK=128, num_warps=4, num_stages=1) del buf6 buf8 = empty_strided_cuda((4, 2, 4, 1), (8, 4, 1, 1), torch.float32) triton_poi_fused_clone_6[grid(8, 4)](buf2, buf8, 8, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del buf2 buf9 = empty_strided_cuda((8, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf7, (8, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf8, (8, 4, 1), (4, 1, 0), 0), out=buf9) buf10 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32) triton_poi_fused_clone_7[grid(16, 2)](buf9, buf10, 16, 2, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) buf11 = reinterpret_tensor(buf9, (16, 2), (2, 1), 0) del buf9 extern_kernels.mm(reinterpret_tensor(buf10, (16, 2), (2, 1), 0), reinterpret_tensor(primals_5, (2, 2), (1, 2), 0), out=buf11) buf12 = buf0 del buf0 triton_poi_fused_native_layer_norm_8[grid(16)](primals_1, buf12, 16, XBLOCK=16, num_warps=1, num_stages=1) buf13 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32) triton_poi_fused_native_layer_norm_9[grid(32)](primals_1, buf12, primals_7, primals_8, buf13, 32, XBLOCK=32, num_warps=1, num_stages=1) del primals_7 del primals_8 buf14 = empty_strided_cuda((16, 2), (2, 1), torch.float32) extern_kernels.addmm(primals_10, reinterpret_tensor(buf13, (16, 2), (2, 1), 0), reinterpret_tensor(primals_9, (2, 2), (1, 2), 0), alpha=1, beta=1, out=buf14) del primals_10 buf15 = empty_strided_cuda((4, 2, 4), (8, 4, 1), torch.float32) triton_poi_fused_convolution_10[grid(8, 4)](buf14, buf15, 8, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) buf16 = extern_kernels.convolution(buf15, primals_11, stride=(1,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf16, (4, 2, 4), (8, 4, 1)) del buf15 buf17 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_cat_11[grid(64)](buf11, primals_6, buf16, primals_12, buf17, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf11 del buf16 del primals_12 del primals_6 buf18 = buf12 del buf12 buf19 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) triton_poi_fused_add_native_layer_norm_12[grid(16)](primals_1, buf17, buf18, buf19, 16, XBLOCK=16, num_warps=1, num_stages=1) buf20 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_13[grid(64)](primals_1, buf17, buf18, buf19, primals_13, primals_14, buf20, 64, XBLOCK= 64, num_warps=1, num_stages=1) del buf18 del buf19 del primals_14 buf21 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.addmm(primals_16, reinterpret_tensor(buf20, (16, 4), (4, 1), 0), reinterpret_tensor(primals_15, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf21) del primals_16 buf22 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32) triton_poi_fused_gelu_14[grid(256)](buf21, buf22, 256, XBLOCK=256, num_warps=4, num_stages=1) buf23 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf22, (16, 16), (16, 1), 0), reinterpret_tensor(primals_17, (16, 4), (1, 16), 0), out=buf23) buf24 = reinterpret_tensor(buf23, (4, 4, 4), (16, 4, 1), 0) del buf23 triton_poi_fused_add_15[grid(64)](buf24, primals_1, buf17, primals_18, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_18 return buf24, primals_1, primals_11, primals_13, reinterpret_tensor(buf1, (16, 2), (2, 1), 0), buf7, reinterpret_tensor(buf10, (16, 2), (2, 1), 0 ), reinterpret_tensor(buf13, (16, 2), (2, 1), 0), reinterpret_tensor( buf14, (4, 2, 4), (8, 1, 2), 0), buf17, reinterpret_tensor(buf20, ( 16, 4), (4, 1), 0), buf21, reinterpret_tensor(buf22, (16, 16), (16, 1), 0 ), primals_17, primals_15, primals_9, primals_5, reinterpret_tensor( buf8, (8, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf3, (8, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf4, (8, 4, 1), (4, 1, 4), 0 ), primals_4 def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x. device) random_tensor.floor_() output = x.div(keep_prob) * random_tensor return output class DCNv2(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, deformable_groups=1): super(DCNv2, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _pair(kernel_size) self.stride = _pair(stride) self.padding = _pair(padding) self.dilation = _pair(dilation) self.deformable_groups = deformable_groups self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels, *self.kernel_size)) self.bias = nn.Parameter(torch.Tensor(out_channels)) self.reset_parameters() def reset_parameters(self): n = self.in_channels for k in self.kernel_size: n *= k stdv = 1.0 / math.sqrt(n) self.weight.data.uniform_(-stdv, stdv) self.bias.data.zero_() def forward(self, input, offset, mask): assert 2 * self.deformable_groups * self.kernel_size[0 ] * self.kernel_size[1] == offset.shape[1] assert self.deformable_groups * self.kernel_size[0] * self.kernel_size[ 1] == mask.shape[1] return dcn_v2_conv(input, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation, self.deformable_groups) class DCN(DCNv2): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, deformable_groups=1): super(DCN, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, deformable_groups) channels_ = self.deformable_groups * 3 * self.kernel_size[0 ] * self.kernel_size[1] self.conv_offset_mask = nn.Conv2d(self.in_channels, channels_, kernel_size=self.kernel_size, stride=self.stride, padding=self. padding, bias=True) self.init_offset() def init_offset(self): self.conv_offset_mask.weight.data.zero_() self.conv_offset_mask.bias.data.zero_() def forward(self, input): out = self.conv_offset_mask(input) o1, o2, mask = torch.chunk(out, 3, dim=1) offset = torch.cat((o1, o2), dim=1) mask = torch.sigmoid(mask) return dcn_v2_conv(input, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation, self.deformable_groups) class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class LocalAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, local_ks=3, length=196): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) mask = torch.ones(length, length) for i in range(length): for j in range(i - local_ks // 2, i + local_ks // 2 + 1, 1): j = min(max(0, j), length - 1) mask[i, j] = 0 mask = mask.unsqueeze(0).unsqueeze(1) self.mask = nn.Parameter(mask, requires_grad=False) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q, k, v = qkv[0], qkv[1], qkv[2] attn = q @ k.transpose(-2, -1) * self.scale attn = attn.masked_fill_(self.mask.bool(), -np.inf) attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, N, C) x = self.proj(x) x = self.proj_drop(x) return x class LocalBranch(nn.Module): def __init__(self, dim, local_type='conv', local_ks=3, length=196, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.local_type = local_type if local_type == 'conv': self.linear = nn.Linear(dim, dim) self.local = nn.Conv1d(dim, dim, kernel_size=local_ks, padding= local_ks // 2, padding_mode='zeros', groups=1) elif local_type == 'dcn': self.linear = nn.Linear(dim, dim) self.local = DCN(dim, dim, kernel_size=(local_ks, 1), stride=1, padding=(local_ks // 2, 0), deformable_groups=2) elif local_type == 'attn': self.local = LocalAttention(dim, num_heads=num_heads, qkv_bias= qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop =proj_drop, local_ks=local_ks, length=length) else: self.local = nn.Identity() def forward(self, x): if self.local_type in ['conv']: x = self.linear(x) x = x.permute(0, 2, 1) x = self.local(x) x = x.permute(0, 2, 1) return x elif self.local_type == 'dcn': x = self.linear(x) x = x.permute(0, 2, 1).unsqueeze(3).contiguous() x = self.local(x) x = x.squeeze(3).permute(0, 2, 1) return x elif self.local_type == 'attn': x = self.local(x) return x else: x = self.local(x) return x class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) class Block_localNew(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn .GELU, norm_layer=partial(nn.LayerNorm, eps=1e-06), local_type= 'conv', local_ks=3, length=196, local_ratio=0.5, ffn_type='base'): super().__init__() local_dim = int(dim * local_ratio) self.global_dim = dim - local_dim div = 2 self.num_heads = num_heads // div self.norm1 = norm_layer(self.global_dim) self.norm1_local = norm_layer(local_dim) self.attn = Attention(self.global_dim, num_heads=self.num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.local = LocalBranch(local_dim, local_type=local_type, local_ks =local_ks, length=length, num_heads=self.num_heads, qkv_bias= qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path ) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) if ffn_type == 'base': MLP = Mlp else: raise Exception('invalid ffn_type: {}'.format(ffn_type)) self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, input_0): primals_2 = self.norm1.weight primals_3 = self.norm1.bias primals_6 = self.norm1_local.weight primals_7 = self.norm1_local.bias primals_4 = self.attn.qkv.weight primals_5 = self.attn.proj.weight primals_8 = self.attn.proj.bias primals_9 = self.local.linear.weight primals_10 = self.local.linear.bias primals_11 = self.local.local.weight primals_12 = self.local.local.bias primals_13 = self.norm2.weight primals_14 = self.norm2.bias primals_15 = self.mlp.fc1.weight primals_16 = self.mlp.fc1.bias primals_17 = self.mlp.fc2.weight primals_18 = self.mlp.fc2.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]) return output[0]
TencentYoutuResearch/BaseArchitecture-EAT
Block_local
false
18,031
[ "BSD-3-Clause" ]
9
b916738ef9b1314f5fdad780a0839cb4e010a208
https://github.com/TencentYoutuResearch/BaseArchitecture-EAT/tree/b916738ef9b1314f5fdad780a0839cb4e010a208
BatchMLP
import torch from torch import nn class NPBlockRelu2d(nn.Module): """Block for Neural Processes.""" def __init__(self, in_channels, out_channels, dropout=0, batchnorm= False, bias=False): super().__init__() self.linear = nn.Linear(in_channels, out_channels, bias=bias) self.act = nn.ReLU() self.dropout = nn.Dropout2d(dropout) self.norm = nn.BatchNorm2d(out_channels) if batchnorm else False def forward(self, x): x = self.act(self.linear(x)) x = x.permute(0, 2, 1)[:, :, :, None] if self.norm: x = self.norm(x) x = self.dropout(x) return x[:, :, :, 0].permute(0, 2, 1) class BatchMLP(nn.Module): """Apply MLP to the final axis of a 3D tensor (reusing already defined MLPs). Args: input: input tensor of shape [B,n,d_in]. output_sizes: An iterable containing the output sizes of the MLP as defined in `basic.Linear`. Returns: tensor of shape [B,n,d_out] where d_out=output_size """ def __init__(self, input_size, output_size, num_layers=2, dropout=0, batchnorm=False): super().__init__() self.input_size = input_size self.output_size = output_size self.num_layers = num_layers self.initial = NPBlockRelu2d(input_size, output_size, dropout= dropout, batchnorm=batchnorm) self.encoder = nn.Sequential(*[NPBlockRelu2d(output_size, output_size, dropout=dropout, batchnorm=batchnorm) for _ in range(num_layers - 2)]) self.final = nn.Linear(output_size, output_size) def forward(self, x): x = self.initial(x) x = self.encoder(x) return self.final(x) def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'input_size': 4, 'output_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 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, 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 tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = 0.0 tmp4 = tmp2 <= tmp3 tl.store(in_out_ptr0 + x0, tmp2, xmask) tl.store(out_ptr0 + x0, tmp4, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (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_2, (16, 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), (16, 4, 1), 0) del buf0 buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(64)](buf1, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_4, reinterpret_tensor(buf1, (16, 4), ( 4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del primals_4 return reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (16, 4), (4, 1), 0), primals_3, buf3 class NPBlockRelu2d(nn.Module): """Block for Neural Processes.""" def __init__(self, in_channels, out_channels, dropout=0, batchnorm= False, bias=False): super().__init__() self.linear = nn.Linear(in_channels, out_channels, bias=bias) self.act = nn.ReLU() self.dropout = nn.Dropout2d(dropout) self.norm = nn.BatchNorm2d(out_channels) if batchnorm else False def forward(self, x): x = self.act(self.linear(x)) x = x.permute(0, 2, 1)[:, :, :, None] if self.norm: x = self.norm(x) x = self.dropout(x) return x[:, :, :, 0].permute(0, 2, 1) class BatchMLPNew(nn.Module): """Apply MLP to the final axis of a 3D tensor (reusing already defined MLPs). Args: input: input tensor of shape [B,n,d_in]. output_sizes: An iterable containing the output sizes of the MLP as defined in `basic.Linear`. Returns: tensor of shape [B,n,d_out] where d_out=output_size """ def __init__(self, input_size, output_size, num_layers=2, dropout=0, batchnorm=False): super().__init__() self.input_size = input_size self.output_size = output_size self.num_layers = num_layers self.initial = NPBlockRelu2d(input_size, output_size, dropout= dropout, batchnorm=batchnorm) self.encoder = nn.Sequential(*[NPBlockRelu2d(output_size, output_size, dropout=dropout, batchnorm=batchnorm) for _ in range(num_layers - 2)]) self.final = nn.Linear(output_size, output_size) def forward(self, input_0): primals_1 = self.initial.linear.weight primals_3 = self.final.weight primals_4 = self.final.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
VersElectronics/Neural-Processes
BatchMLP
false
18,032
[ "MIT" ]
5
6eb7552a0d1c489189d6dd0f83704dcdbeaed24b
https://github.com/VersElectronics/Neural-Processes/tree/6eb7552a0d1c489189d6dd0f83704dcdbeaed24b
DropConnect
import torch class DropConnect(torch.nn.Module): def __init__(self, p): super(DropConnect, self).__init__() self.p = p def forward(self, inputs): batch_size = inputs.shape[0] inputs.shape[2] inputs.shape[3] channel_size = inputs.shape[1] keep_prob = 1 - self.p random_tensor = keep_prob random_tensor += torch.rand([batch_size, channel_size, 1, 1], dtype =inputs.dtype, device=inputs.device) binary_tensor = torch.floor(random_tensor) output = inputs / keep_prob * binary_tensor return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'p': 4}]
import torch from torch import device 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 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_floor_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 x2 = xindex x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp1 = -0.3333333333333333 tmp2 = tmp0 * tmp1 tmp4 = -3.0 tmp5 = tmp3 + tmp4 tmp6 = libdevice.floor(tmp5) tmp7 = tmp2 * tmp6 tl.store(out_ptr0 + x2, tmp7, 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 = torch.ops.aten.rand.default([4, 4, 1, 1], dtype=torch. float32, device=device(type='cuda', index=0), pin_memory=False) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_floor_mul_0[grid(256)](arg0_1, buf1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 del buf1 return buf2, class DropConnectNew(torch.nn.Module): def __init__(self, p): super(DropConnectNew, self).__init__() self.p = p def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
VascoLopes/GEA
DropConnect
false
18,033
[ "MIT" ]
4
ab80dbb9851dfc215102e5222e8d5f70e855dd15
https://github.com/VascoLopes/GEA/tree/ab80dbb9851dfc215102e5222e8d5f70e855dd15
Block_cls
import torch from torch import nn from functools import partial import torch.utils.data import torch.nn.parallel from torch import optim as optim def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x. device) random_tensor.floor_() output = x.div(keep_prob) * random_tensor return output class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class CrossAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) self.q = nn.Linear(dim, dim * 1, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x, xq): B, N, C = x.shape _, Nq, _ = xq.shape kv = self.kv(x).reshape(B, N, 2, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q_ = self.q(xq).reshape(B, Nq, 1, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q, k, v = q_[0], kv[0], kv[1] attn = q @ k.transpose(-2, -1) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, Nq, C) x = self.proj(x) x = self.proj_drop(x) return x class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) class Block_cls(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn .GELU, norm_layer=partial(nn.LayerNorm, eps=1e-06), local_type= 'conv', local_ks=3, local_ratio=0.5, ffn_type='base'): super().__init__() self.norm1 = norm_layer(dim) self.attn = CrossAttention(dim, num_heads=num_heads, qkv_bias= qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path ) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) if ffn_type == 'base': MLP = Mlp else: raise Exception('invalid ffn_type: {}'.format(ffn_type)) self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, x, xq): xq = xq + self.drop_path(self.attn(x, self.norm1(xq))) xq = xq + self.drop_path(self.mlp(self.norm2(xq))) return xq def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'dim': 4, 'num_heads': 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 from torch import nn from functools import partial import torch.utils.data import torch.nn.parallel from torch import optim as optim 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 = 1e-06 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, 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) @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) @triton.jit def triton_poi_fused_clone_3(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 + 8 * x2 + 32 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused__softmax_4(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 = tmp14 * tmp1 tmp16 = tl_math.exp(tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused__softmax_5(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_clone_6(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 + (4 + y0 + 8 * x2 + 32 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_native_layer_norm_7(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 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') tmp2 = tl.load(in_ptr2 + 0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK]) tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr2 + 1) tmp9 = tl.broadcast_to(tmp8, [XBLOCK]) tmp13 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp14 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp15 = tl.load(in_ptr2 + 2) tmp16 = tl.broadcast_to(tmp15, [XBLOCK]) tmp20 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp21 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp22 = tl.load(in_ptr2 + 3) tmp23 = tl.broadcast_to(tmp22, [XBLOCK]) tmp4 = tmp1 + tmp3 tmp5 = tmp0 + tmp4 tmp10 = tmp7 + tmp9 tmp11 = tmp6 + tmp10 tmp12 = tmp5 + tmp11 tmp17 = tmp14 + tmp16 tmp18 = tmp13 + tmp17 tmp19 = tmp12 + tmp18 tmp24 = tmp21 + tmp23 tmp25 = tmp20 + tmp24 tmp26 = tmp19 + tmp25 tmp27 = 4.0 tmp28 = tmp26 / tmp27 tmp29 = tmp5 - tmp28 tmp30 = tmp29 * tmp29 tmp31 = tmp11 - tmp28 tmp32 = tmp31 * tmp31 tmp33 = tmp30 + tmp32 tmp34 = tmp18 - tmp28 tmp35 = tmp34 * tmp34 tmp36 = tmp33 + tmp35 tmp37 = tmp25 - tmp28 tmp38 = tmp37 * tmp37 tmp39 = tmp36 + tmp38 tmp40 = tmp39 / tmp27 tl.store(out_ptr0 + x0, tmp28, xmask) tl.store(out_ptr1 + x0, tmp40, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_8(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, 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 x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x2, xmask) tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp14 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tmp6 = tmp4 - tmp5 tmp8 = 1e-06 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp6 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_poi_fused_gelu_9(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.5 tmp2 = tmp0 * tmp1 tmp3 = 0.7071067811865476 tmp4 = tmp0 * tmp3 tmp5 = libdevice.erf(tmp4) tmp6 = 1.0 tmp7 = tmp5 + tmp6 tmp8 = tmp2 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) @triton.jit def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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_ptr1 + x2, xmask) tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_out_ptr0 + x2, xmask) tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tmp7 = tmp5 + tmp6 tmp8 = tmp4 + tmp7 tl.store(in_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,), (1,)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_5, (8, 4), (4, 1)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4, 4), (4, 1)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (16, 4), (4, 1)) assert_size_stride(primals_12, (16,), (1,)) assert_size_stride(primals_13, (4, 16), (16, 1)) assert_size_stride(primals_14, (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_3, buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((16, 8), (8, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (16, 4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 8), (1, 4), 0), out=buf2) del primals_5 buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(64)](primals_3, buf0, buf1, primals_1, primals_2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_2 buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4) buf5 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 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, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf4 triton_poi_fused_clone_3[grid(16, 4)](buf2, buf6, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf7 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf5, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf6, (16, 1, 4), (4, 0, 1), 0), out=buf7) buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_4[grid(256)](buf7, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1) buf9 = reinterpret_tensor(buf7, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf7 triton_poi_fused__softmax_5[grid(256)](buf8, buf9, 256, XBLOCK=128, num_warps=4, num_stages=1) buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) triton_poi_fused_clone_6[grid(16, 4)](buf2, buf10, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) del buf2 buf11 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf9, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf10, (16, 4, 1), (4, 1, 0), 0), out=buf11) buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_clone_2[grid(16, 4)](buf11, buf12, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf13 = reinterpret_tensor(buf11, (16, 4), (4, 1), 0) del buf11 extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf13) buf14 = buf1 del buf1 buf15 = buf0 del buf0 triton_poi_fused_add_native_layer_norm_7[grid(16)](primals_3, buf13, primals_8, buf14, buf15, 16, XBLOCK=16, num_warps=1, num_stages=1) buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_8[grid(64)](primals_3, buf13, primals_8, buf14, buf15, primals_9, primals_10, buf16, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf14 del buf15 del primals_10 buf17 = reinterpret_tensor(buf8, (16, 16), (16, 1), 0) del buf8 extern_kernels.addmm(primals_12, reinterpret_tensor(buf16, (16, 4), (4, 1), 0), reinterpret_tensor(primals_11, (4, 16), (1, 4), 0), alpha=1, beta=1, out=buf17) del primals_12 buf18 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32) triton_poi_fused_gelu_9[grid(256)](buf17, buf18, 256, XBLOCK=256, num_warps=4, num_stages=1) buf19 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf18, (16, 16), (16, 1), 0), reinterpret_tensor(primals_13, (16, 4), (1, 16), 0), out=buf19) buf20 = reinterpret_tensor(buf19, (4, 4, 4), (16, 4, 1), 0) del buf19 triton_poi_fused_add_10[grid(64)](buf20, primals_3, buf13, primals_8, primals_14, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_14 return buf20, primals_3, primals_8, primals_9, reinterpret_tensor(primals_4 , (16, 4), (4, 1), 0), reinterpret_tensor(buf3, (16, 4), (4, 1), 0 ), buf9, reinterpret_tensor(buf12, (16, 4), (4, 1), 0 ), buf13, reinterpret_tensor(buf16, (16, 4), (4, 1), 0 ), buf17, reinterpret_tensor(buf18, (16, 16), (16, 1), 0 ), primals_13, primals_11, primals_7, reinterpret_tensor(buf10, (16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf5, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 4), 0), primals_6 def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0.0 or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x. device) random_tensor.floor_() output = x.div(keep_prob) * random_tensor return output class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.fc2 = nn.Linear(hidden_features, out_features) self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop(x) x = self.fc2(x) x = self.drop(x) return x class CrossAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = qk_scale or head_dim ** -0.5 self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias) self.q = nn.Linear(dim, dim * 1, bias=qkv_bias) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x, xq): B, N, C = x.shape _, Nq, _ = xq.shape kv = self.kv(x).reshape(B, N, 2, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q_ = self.q(xq).reshape(B, Nq, 1, self.num_heads, C // self.num_heads ).permute(2, 0, 3, 1, 4) q, k, v = q_[0], kv[0], kv[1] attn = q @ k.transpose(-2, -1) * self.scale attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (attn @ v).transpose(1, 2).reshape(B, Nq, C) x = self.proj(x) x = self.proj_drop(x) return x class DropPath(nn.Module): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). """ def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training) class Block_clsNew(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn .GELU, norm_layer=partial(nn.LayerNorm, eps=1e-06), local_type= 'conv', local_ks=3, local_ratio=0.5, ffn_type='base'): super().__init__() self.norm1 = norm_layer(dim) self.attn = CrossAttention(dim, num_heads=num_heads, qkv_bias= qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop) self.drop_path = DropPath(drop_path ) if drop_path > 0.0 else nn.Identity() self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) if ffn_type == 'base': MLP = Mlp else: raise Exception('invalid ffn_type: {}'.format(ffn_type)) self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) def forward(self, input_0, input_1): primals_1 = self.norm1.weight primals_2 = self.norm1.bias primals_5 = self.attn.kv.weight primals_6 = self.attn.q.weight primals_7 = self.attn.proj.weight primals_8 = self.attn.proj.bias primals_9 = self.norm2.weight primals_10 = self.norm2.bias primals_11 = self.mlp.fc1.weight primals_12 = self.mlp.fc1.bias primals_13 = self.mlp.fc2.weight primals_14 = self.mlp.fc2.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, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14]) return output[0]
TencentYoutuResearch/BaseArchitecture-EAT
Block_cls
false
18,034
[ "BSD-3-Clause" ]
9
b916738ef9b1314f5fdad780a0839cb4e010a208
https://github.com/TencentYoutuResearch/BaseArchitecture-EAT/tree/b916738ef9b1314f5fdad780a0839cb4e010a208
Classifier
import torch import torch.nn as nn import torch.utils.data class Classifier(nn.Module): def __init__(self, feature_dim, classes): super(Classifier, self).__init__() self.classifier = nn.Linear(int(feature_dim * 2), classes) def forward(self, di_z, ds_z): z = torch.cat((di_z, ds_z), dim=1) y = self.classifier(z) return y def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'feature_dim': 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 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_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) def call(args): primals_1, primals_2, primals_3, primals_4 = 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,)) 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) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_4, buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8), 0), alpha=1, beta=1, out=buf1) del primals_3 del primals_4 return buf1, buf0 class ClassifierNew(nn.Module): def __init__(self, feature_dim, classes): super(ClassifierNew, self).__init__() self.classifier = nn.Linear(int(feature_dim * 2), classes) def forward(self, input_0, input_1): primals_3 = self.classifier.weight primals_4 = self.classifier.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
VinAIResearch/mDSDI
Classifier
false
18,035
[ "Apache-2.0" ]
9
8ec49085d8389ab490ec633c3ae4bf66be085366
https://github.com/VinAIResearch/mDSDI/tree/8ec49085d8389ab490ec633c3ae4bf66be085366
AdaFRN
import torch import torch.nn as nn class AdaFRN(nn.Module): def __init__(self, style_dim, num_features, eps=1e-05): super(AdaFRN, self).__init__() self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.fc = nn.Linear(style_dim, num_features * 2) self.eps = eps def forward(self, x, s): x = x * torch.rsqrt(torch.mean(x ** 2, dim=[2, 3], keepdim=True) + self.eps) h = self.fc(s) h = h.view(h.size(0), h.size(1), 1, 1) gamma, _beta = torch.chunk(h, chunks=2, dim=1) out = (1 + gamma) * x return torch.max(out, self.tau) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'style_dim': 4, 'num_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 import triton_helpers 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_per_fused_add_maximum_mean_mul_pow_rsqrt_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, 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) x0 = xindex % 4 x1 = xindex // 4 x2 = xindex r3 = rindex tmp0 = tl.load(in_ptr0 + (x0 + 8 * x1), xmask, eviction_policy='evict_last' ) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr2 + (r3 + 16 * x2), xmask, other=0.0) tmp18 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 + tmp3 tmp6 = tmp5 * tmp5 tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK]) tmp9 = tl.where(xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tmp11 = 16.0 tmp12 = tmp10 / tmp11 tmp13 = 1e-05 tmp14 = tmp12 + tmp13 tmp15 = libdevice.rsqrt(tmp14) tmp16 = tmp5 * tmp15 tmp17 = tmp4 * tmp16 tmp19 = triton_helpers.maximum(tmp17, tmp18) tl.store(out_ptr0 + x2, tmp4, xmask) tl.debug_barrier() tl.store(in_out_ptr0 + x2, tmp15, xmask) tl.store(out_ptr1 + (r3 + 16 * x2), tmp19, 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), (4, 1)) assert_size_stride(primals_3, (8,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (1, 4, 1, 1), (4, 1, 1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf2 = empty_strided_cuda((4, 8), (8, 1), torch.float32) extern_kernels.mm(primals_4, reinterpret_tensor(primals_2, (4, 8), (1, 4), 0), out=buf2) del primals_2 buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) 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 buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_maximum_mean_mul_pow_rsqrt_0[grid(16)](buf1, buf2, primals_3, primals_1, primals_5, buf3, buf4, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) del buf2 del primals_3 return buf4, primals_1, primals_4, primals_5, buf1, buf3 class AdaFRNNew(nn.Module): def __init__(self, style_dim, num_features, eps=1e-05): super(AdaFRNNew, self).__init__() self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.fc = nn.Linear(style_dim, num_features * 2) self.eps = eps def forward(self, input_0, input_1): primals_5 = self.tau primals_2 = self.fc.weight primals_3 = self.fc.bias primals_1 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
UdonDa/StarGAN-v2-pytorch-nonofficial
AdaFRN
false
18,036
[ "MIT" ]
9
219df6b7fd4bd533686e2093ee914a337914ca9b
https://github.com/UdonDa/StarGAN-v2-pytorch-nonofficial/tree/219df6b7fd4bd533686e2093ee914a337914ca9b
LayerNormalization
import torch from torch import nn class LayerNormalization(nn.Module): def __init__(self, d_hid, eps=0.001): super(LayerNormalization, self).__init__() self.gamma = nn.Parameter(torch.ones(d_hid), requires_grad=True) self.beta = nn.Parameter(torch.zeros(d_hid), requires_grad=True) self.eps = eps def forward(self, z): mean = z.mean(dim=-1, keepdim=True) std = z.std(dim=-1, keepdim=True) ln_out = (z - mean.expand_as(z)) / (std.expand_as(z) + self.eps) ln_out = self.gamma.expand_as(ln_out) * ln_out + self.beta.expand_as( ln_out) return ln_out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'d_hid': 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_poi_fused_add_div_mul_sub_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 % 4 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask) tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp8 = tmp6 + tmp7 tmp9 = 4.0 tmp10 = tmp8 / tmp9 tmp11 = tmp1 - tmp10 tmp12 = tmp2 - tmp10 tmp13 = tmp12 * tmp12 tmp14 = tmp3 - tmp10 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp10 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp7 - tmp10 tmp21 = tmp20 * tmp20 tmp22 = tmp19 + tmp21 tmp23 = 3.0 tmp24 = tmp22 / tmp23 tmp25 = libdevice.sqrt(tmp24) tmp26 = 0.001 tmp27 = tmp25 + tmp26 tmp28 = tmp11 / tmp27 tmp29 = tmp0 * tmp28 tmp31 = tmp29 + tmp30 tl.store(out_ptr0 + x2, tmp31, 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_div_mul_sub_0[grid(256)](primals_2, primals_1, primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 del primals_3 return buf0, primals_1 class LayerNormalizationNew(nn.Module): def __init__(self, d_hid, eps=0.001): super(LayerNormalizationNew, self).__init__() self.gamma = nn.Parameter(torch.ones(d_hid), requires_grad=True) self.beta = nn.Parameter(torch.zeros(d_hid), requires_grad=True) self.eps = eps def forward(self, input_0): primals_2 = self.gamma primals_3 = self.beta primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
VarnithChordia/Multlingual_Punctuation_restoration
LayerNormalization
false
18,037
[ "MIT" ]
8
17c026e8935b9fecae01d446a756926c7733fcd1
https://github.com/VarnithChordia/Multlingual_Punctuation_restoration/tree/17c026e8935b9fecae01d446a756926c7733fcd1
DiceLoss
import torch from torch import nn class DiceLoss(nn.Module): def __init__(self, eps: 'int'=1) ->None: super().__init__() self.eps = eps def forward(self, output: 'torch.Tensor', target: 'torch.Tensor' ) ->torch.Tensor: batch_size = output.shape[0] dice_target = target.reshape(batch_size, -1) dice_output = output.reshape(batch_size, -1) intersection = torch.sum(dice_output * dice_target, dim=1) union = torch.sum(dice_output, dim=1) + torch.sum(dice_target, dim=1) loss = (2 * intersection + self.eps) / (union + self.eps) return -torch.log(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.triton_helpers import 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_mul_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) tmp1 = tl.load(in_ptr1 + (r1 + 64 * x0), 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 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp9 = tl.where(xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tmp11 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp13 = tl.where(xmask, tmp11, 0) tmp14 = tl.sum(tmp13, 1)[:, None] tl.store(out_ptr0 + x0, tmp6, xmask) tl.store(out_ptr1 + x0, tmp10, xmask) tl.store(out_ptr2 + x0, tmp14, xmask) @triton.jit def triton_per_fused_add_div_log_mean_mul_neg_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 = 1.0 tmp4 = tmp2 + tmp3 tmp7 = tmp5 + tmp6 tmp8 = tmp7 + tmp3 tmp9 = tmp4 / tmp8 tmp10 = tl_math.log(tmp9) tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK]) tmp13 = tl.sum(tmp11, 1)[:, None] tmp14 = 4.0 tmp15 = tmp13 / tmp14 tmp16 = -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_mul_sum_0[grid(4)](arg0_1, arg1_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_log_mean_mul_neg_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 DiceLossNew(nn.Module): def __init__(self, eps: 'int'=1) ->None: super().__init__() self.eps = eps def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
TylerYep/ml-toolkit
DiceLoss
false
18,038
[ "MIT" ]
7
095bdce961133acc720f90b6d1bbb0a7becbfc9f
https://github.com/TylerYep/ml-toolkit/tree/095bdce961133acc720f90b6d1bbb0a7becbfc9f
GAP1d
import torch from torch import nn import torch.nn.functional class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), -1) class GAP1d(nn.Module): """Global Adaptive Pooling + Flatten """ def __init__(self, output_size=1): super(GAP1d, self).__init__() self.gap = nn.AdaptiveAvgPool1d(output_size) self.flatten = Flatten() def forward(self, x): return self.flatten(self.gap(x)) def get_inputs(): return [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 import torch.nn.functional 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_mean_0(in_ptr0, 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 = 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 tl.store(out_ptr0 + x0, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mean_0[grid(4)](arg0_1, buf0, 4, XBLOCK=4, num_warps=1, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 1), (1, 1), 0), class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), -1) class GAP1dNew(nn.Module): """Global Adaptive Pooling + Flatten """ def __init__(self, output_size=1): super(GAP1dNew, self).__init__() self.gap = nn.AdaptiveAvgPool1d(output_size) self.flatten = Flatten() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
VincentSch4rf/torchtime
GAP1d
false
18,039
[ "Apache-2.0" ]
4
bebd006cd67b31c342e0658285c9771c27411df0
https://github.com/VincentSch4rf/torchtime/tree/bebd006cd67b31c342e0658285c9771c27411df0
LRN
import torch import torch.nn as nn import torch.utils.data class LRN(nn.Module): def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=True ): super(LRN, self).__init__() self.ACROSS_CHANNELS = ACROSS_CHANNELS if ACROSS_CHANNELS: self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1), stride=1, padding=(int((local_size - 1.0) / 2), 0, 0)) else: self.average = nn.AvgPool2d(kernel_size=local_size, stride=1, padding=int((local_size - 1.0) / 2)) self.alpha = alpha self.beta = beta def forward(self, x): if self.ACROSS_CHANNELS: div = x.pow(2).unsqueeze(1) div = self.average(div).squeeze(1) div = div.mul(self.alpha).add(1.0).pow(self.beta) else: div = x.pow(2) div = self.average(div) div = div.mul(self.alpha).add(1.0).pow(self.beta) x = x.div(div) 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.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 @triton.jit def triton_poi_fused_add_div_mul_pow_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 * tmp0 tmp2 = 1.0 tmp3 = tmp1 * tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 + tmp2 tmp6 = 0.75 tmp7 = libdevice.pow(tmp5, tmp6) tmp8 = tmp0 / 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_mul_pow_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class LRNNew(nn.Module): def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=True ): super(LRNNew, self).__init__() self.ACROSS_CHANNELS = ACROSS_CHANNELS if ACROSS_CHANNELS: self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1), stride=1, padding=(int((local_size - 1.0) / 2), 0, 0)) else: self.average = nn.AvgPool2d(kernel_size=local_size, stride=1, padding=int((local_size - 1.0) / 2)) self.alpha = alpha self.beta = beta def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
VisionLearningGroup/CDS
LRN
false
18,040
[ "MIT" ]
7
5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
https://github.com/VisionLearningGroup/CDS/tree/5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
BinaryFocalLoss
import torch import torch.nn as nn def binary_focal_loss(pred, target, gamma=2.0, alpha=-1, reduction='mean'): p = torch.sigmoid(pred) loss_pos = -target * (1.0 - p) ** gamma * torch.log(p + 1e-09) loss_neg = -(1.0 - target) * p ** gamma * torch.log(1.0 - p + 1e-09) if alpha >= 0.0 and alpha <= 1.0: loss_pos = loss_pos * alpha loss_neg = loss_neg * (1.0 - alpha) loss = loss_pos + loss_neg if reduction == 'mean': return loss.mean() elif reduction == 'sum': return loss.sum() elif reduction == 'none': return loss else: raise RuntimeError class BinaryFocalLoss(nn.Module): def __init__(self, gamma=2.0, alpha=-1): super(BinaryFocalLoss, self).__init__() self.gamma, self.alpha = gamma, alpha def forward(self, pred, target, reduction='mean'): return binary_focal_loss(pred, target, self.gamma, self.alpha, reduction) 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_per_fused_add_log_mean_mul_neg_pow_rsub_sigmoid_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 = -tmp0 tmp3 = tl.sigmoid(tmp2) tmp4 = 1.0 tmp5 = tmp4 - tmp3 tmp6 = tmp5 * tmp5 tmp7 = tmp1 * tmp6 tmp8 = 1e-09 tmp9 = tmp3 + tmp8 tmp10 = tl_math.log(tmp9) tmp11 = tmp7 * tmp10 tmp12 = tmp4 - tmp0 tmp13 = -tmp12 tmp14 = tmp3 * tmp3 tmp15 = tmp13 * tmp14 tmp16 = tmp5 + tmp8 tmp17 = tl_math.log(tmp16) tmp18 = tmp15 * tmp17 tmp19 = tmp11 + tmp18 tmp20 = tl.broadcast_to(tmp19, [RBLOCK]) tmp22 = triton_helpers.promote_to_tensor(tl.sum(tmp20, 0)) tmp23 = 256.0 tmp24 = tmp22 / tmp23 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp24, 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_add_log_mean_mul_neg_pow_rsub_sigmoid_0[grid(1)](buf1, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, def binary_focal_loss(pred, target, gamma=2.0, alpha=-1, reduction='mean'): p = torch.sigmoid(pred) loss_pos = -target * (1.0 - p) ** gamma * torch.log(p + 1e-09) loss_neg = -(1.0 - target) * p ** gamma * torch.log(1.0 - p + 1e-09) if alpha >= 0.0 and alpha <= 1.0: loss_pos = loss_pos * alpha loss_neg = loss_neg * (1.0 - alpha) loss = loss_pos + loss_neg if reduction == 'mean': return loss.mean() elif reduction == 'sum': return loss.sum() elif reduction == 'none': return loss else: raise RuntimeError class BinaryFocalLossNew(nn.Module): def __init__(self, gamma=2.0, alpha=-1): super(BinaryFocalLossNew, self).__init__() self.gamma, self.alpha = gamma, alpha def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
VisualComputingInstitute/Person_MinkUNet
BinaryFocalLoss
false
18,041
[ "MIT" ]
4
fa39764245a022740c0a3d8c85026532fff93e74
https://github.com/VisualComputingInstitute/Person_MinkUNet/tree/fa39764245a022740c0a3d8c85026532fff93e74
LayerNorm
import torch from torch import nn class LayerNorm(nn.Module): """ Simple 1D LayerNorm. """ def __init__(self, features, center=True, scale=False, eps=1e-06): super().__init__() self.center = center self.scale = scale self.eps = eps if self.scale: self.scale_param = nn.Parameter(torch.ones(features)) else: self.scale_param = None if self.center: self.center_param = nn.Parameter(torch.zeros(features)) else: self.center_param = None def forward(self, x): mean = x.mean(-1, keepdim=True) std = x.std(-1, keepdim=True) output = (x - mean) / (std + self.eps) if self.scale: output = output * self.scale_param if self.center: output = output + self.center_param return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'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_poi_fused_add_div_mean_std_sub_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 x2 = xindex x1 = xindex // 4 x0 = 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') tmp28 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = 4.0 tmp9 = tmp7 / tmp8 tmp10 = tmp0 - tmp9 tmp11 = tmp1 - tmp9 tmp12 = tmp11 * tmp11 tmp13 = tmp2 - tmp9 tmp14 = tmp13 * tmp13 tmp15 = tmp12 + tmp14 tmp16 = tmp4 - tmp9 tmp17 = tmp16 * tmp16 tmp18 = tmp15 + tmp17 tmp19 = tmp6 - tmp9 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = 3.0 tmp23 = tmp21 / tmp22 tmp24 = libdevice.sqrt(tmp23) tmp25 = 1e-06 tmp26 = tmp24 + tmp25 tmp27 = tmp10 / tmp26 tmp29 = tmp27 + tmp28 tl.store(out_ptr0 + x2, tmp29, 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,), (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_mean_std_sub_0[grid(256)](primals_1, primals_2, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 del primals_2 return buf0, class LayerNormNew(nn.Module): """ Simple 1D LayerNorm. """ def __init__(self, features, center=True, scale=False, eps=1e-06): super().__init__() self.center = center self.scale = scale self.eps = eps if self.scale: self.scale_param = nn.Parameter(torch.ones(features)) else: self.scale_param = None if self.center: self.center_param = nn.Parameter(torch.zeros(features)) else: self.center_param = None def forward(self, input_0): primals_2 = self.center_param primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
UT-Austin-RPL/maple
LayerNorm
false
18,042
[ "MIT" ]
9
aef9fe9869945df5bbd1b02fd40813aac135cf5a
https://github.com/UT-Austin-RPL/maple/tree/aef9fe9869945df5bbd1b02fd40813aac135cf5a
SAM_Module
import torch import torch.nn as nn from torchvision.transforms import * class SAM_Module(nn.Module): """ Position attention module""" def __init__(self, channels): super(SAM_Module, self).__init__() self.relu = nn.ReLU(inplace=True) self.conv_after_concat = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1) self.sigmoid_spatial = nn.Sigmoid() def forward(self, x): """ inputs : x : input feature maps( B X C X H X W) returns : out : attention value + input feature attention: B X (HxW) X (HxW) """ module_input = x avg = torch.mean(x, 1, True) x = self.conv_after_concat(avg) x = self.sigmoid_spatial(x) x = module_input * x return 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 import torch.nn as nn from torchvision.transforms 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_mean_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 % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_convolution_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 tl.store(in_out_ptr0 + x0, tmp3, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_2(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, 1, 3, 3), (9, 9, 3, 1)) assert_size_stride(primals_3, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mean_0[grid(64)](primals_1, buf0, 64, XBLOCK=64, num_warps=1, 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, 1, 4, 4), (16, 16, 4, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_sigmoid_2[grid(256)](primals_1, buf2, buf3, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf3, primals_1, primals_2, buf0, buf2 class SAM_ModuleNew(nn.Module): """ Position attention module""" def __init__(self, channels): super(SAM_ModuleNew, self).__init__() self.relu = nn.ReLU(inplace=True) self.conv_after_concat = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1) self.sigmoid_spatial = nn.Sigmoid() def forward(self, input_0): primals_2 = self.conv_after_concat.weight primals_3 = self.conv_after_concat.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Vill-Lab/IGOAS
SAM_Module
false
18,043
[ "MIT" ]
8
42ca1d45e441f993c95b5e8f33c9f97ea3b916f3
https://github.com/Vill-Lab/IGOAS/tree/42ca1d45e441f993c95b5e8f33c9f97ea3b916f3
Normalize
import torch from torch import Tensor from typing import Tuple import torch.nn.functional as F import torch.nn.functional class Normalize(torch.nn.Module): """Normalize a tensor time series with mean and standard deviation. Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n`` channels, this transform will normalize each channel of the input ``torch.*Tensor`` i.e., ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` .. note:: This transform acts out of place, i.e., it does not mutate the input tensor. Args: mean (tuple): Sequence of means for each channel. std (tuple): Sequence of standard deviations for each channel. inplace(bool,optional): Bool to make this operation in-place. """ def __init__(self, mean: 'Tuple[float]', std: 'Tuple[float]', inplace: 'bool'=False): super(Normalize, self).__init__() self.mean = mean self.std = std self.inplace = inplace def forward(self, tensor: 'Tensor') ->Tensor: """ Args: tensor (Tensor): Tensor time series to be normalized. Returns: Tensor: Normalized Tensor series. """ return F.normalize(tensor, self.mean, self.std, self.inplace) def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self. mean, self.std) def get_inputs(): return [torch.rand([4, 4, 4, 4, 4])] def get_init_inputs(): return [[], {'mean': 4, 'std': 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 from typing import Tuple import torch.nn.functional 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_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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp4 = 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') tmp12 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp2 = tmp1 * tmp1 tmp3 = tmp2 * tmp2 tmp5 = tmp4 * tmp4 tmp6 = tmp5 * tmp5 tmp7 = tmp3 + tmp6 tmp9 = tmp8 * tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp7 + tmp10 tmp13 = tmp12 * tmp12 tmp14 = tmp13 * tmp13 tmp15 = tmp11 + tmp14 tmp16 = 0.25 tmp17 = libdevice.pow(tmp15, tmp16) tmp18 = 0.0 tmp19 = triton_helpers.maximum(tmp17, tmp18) tmp20 = tmp0 / tmp19 tl.store(out_ptr0 + x2, tmp20, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_0[grid(1024)](arg0_1, buf0, 1024, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class NormalizeNew(torch.nn.Module): """Normalize a tensor time series with mean and standard deviation. Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n`` channels, this transform will normalize each channel of the input ``torch.*Tensor`` i.e., ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` .. note:: This transform acts out of place, i.e., it does not mutate the input tensor. Args: mean (tuple): Sequence of means for each channel. std (tuple): Sequence of standard deviations for each channel. inplace(bool,optional): Bool to make this operation in-place. """ def __init__(self, mean: 'Tuple[float]', std: 'Tuple[float]', inplace: 'bool'=False): super(NormalizeNew, self).__init__() self.mean = mean self.std = std self.inplace = inplace def __repr__(self): return self.__class__.__name__ + '(mean={0}, std={1})'.format(self. mean, self.std) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
VincentSch4rf/torchtime
Normalize
false
18,044
[ "Apache-2.0" ]
4
bebd006cd67b31c342e0658285c9771c27411df0
https://github.com/VincentSch4rf/torchtime/tree/bebd006cd67b31c342e0658285c9771c27411df0
LinearAverage
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data class LinearAverage(nn.Module): def __init__(self, inputSize, outputSize, T=0.05, momentum=0.5): super(LinearAverage, self).__init__() self.nLem = outputSize self.momentum = momentum self.register_buffer('params', torch.tensor([T, momentum])) self.register_buffer('memory', torch.zeros(outputSize, inputSize)) self.flag = 0 self.T = T self.memory = self.memory self.memory_first = True def forward(self, x, y): out = torch.mm(x, self.memory.t()) / self.T return out def update_wegiht(self, features, index): weight_pos = self.memory.index_select(0, index.data.view(-1) ).resize_as_(features) weight_pos.mul_(self.momentum) weight_pos.add_(torch.mul(features.data, 1 - self.momentum)) w_norm = weight_pos.pow(2).sum(1, keepdim=True).pow(0.5) updated_weight = weight_pos.div(w_norm) self.memory.index_copy_(0, index, updated_weight) self.memory = F.normalize(self.memory) def set_weight(self, features, index): self.memory.index_select(0, index.data.view(-1)).resize_as_(features) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'inputSize': 4, 'outputSize': 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.nn.functional as F 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_div_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp1 = 20.0 tmp2 = tmp0 * tmp1 tl.store(in_out_ptr0 + x0, tmp2, xmask) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4), (4, 1)) assert_size_stride(arg1_1, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(arg1_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4), 0), out=buf0) del arg0_1 del arg1_1 buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_div_0[grid(16)](buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) return buf1, class LinearAverageNew(nn.Module): def __init__(self, inputSize, outputSize, T=0.05, momentum=0.5): super(LinearAverageNew, self).__init__() self.nLem = outputSize self.momentum = momentum self.register_buffer('params', torch.tensor([T, momentum])) self.register_buffer('memory', torch.zeros(outputSize, inputSize)) self.flag = 0 self.T = T self.memory = self.memory self.memory_first = True def update_wegiht(self, features, index): weight_pos = self.memory.index_select(0, index.data.view(-1) ).resize_as_(features) weight_pos.mul_(self.momentum) weight_pos.add_(torch.mul(features.data, 1 - self.momentum)) w_norm = weight_pos.pow(2).sum(1, keepdim=True).pow(0.5) updated_weight = weight_pos.div(w_norm) self.memory.index_copy_(0, index, updated_weight) self.memory = F.normalize(self.memory) def set_weight(self, features, index): self.memory.index_select(0, index.data.view(-1)).resize_as_(features) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
VisionLearningGroup/CDS
LinearAverage
false
18,045
[ "MIT" ]
7
5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
https://github.com/VisionLearningGroup/CDS/tree/5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
L2Norm
import torch import torch.nn as nn import torch.utils.data import torch.nn.init as init class L2Norm(nn.Module): def __init__(self, n_channels, scale): super(L2Norm, self).__init__() self.n_channels = n_channels self.gamma = scale or None self.eps = 1e-10 self.weight = nn.Parameter(torch.Tensor(self.n_channels)) self.reset_parameters() def reset_parameters(self): init.constant(self.weight, self.gamma) def forward(self, x): norm = x.pow(2).sum(1).sqrt() + self.eps x /= norm.expand_as(x) out = self.weight.unsqueeze(0).expand_as(x) * x return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'n_channels': 4, 'scale': 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.triton_helpers import libdevice import torch.nn as nn import torch.utils.data import torch.nn.init as init 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_mul_0(in_ptr0, in_ptr1, 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 x5 = xindex x0 = xindex % 16 x1 = xindex // 16 % 4 x3 = xindex % 4 tmp0 = tl.load(in_ptr0 + x5, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask, eviction_policy= 'evict_last') tmp16 = tl.load(in_ptr1 + x3, 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-10 tmp14 = tmp12 + tmp13 tmp15 = tmp0 / tmp14 tmp17 = tmp16 * tmp15 tl.store(out_ptr0 + x5, tmp15, xmask) tl.store(out_ptr1 + x5, tmp17, xmask) tl.store(out_ptr2 + x5, tmp15, 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,), (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 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_mul_0[grid(256)](primals_1, primals_2, buf0, buf1, primals_1, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 del primals_2 return buf1, buf0 class L2NormNew(nn.Module): def __init__(self, n_channels, scale): super(L2NormNew, self).__init__() self.n_channels = n_channels self.gamma = scale or None self.eps = 1e-10 self.weight = nn.Parameter(torch.Tensor(self.n_channels)) self.reset_parameters() def reset_parameters(self): init.constant(self.weight, self.gamma) def forward(self, input_0): primals_2 = self.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
VisionLearningGroup/CDS
L2Norm
false
18,046
[ "MIT" ]
7
5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
https://github.com/VisionLearningGroup/CDS/tree/5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
UNetUpsamplingBlock
import torch import torch.nn as nn import torch.nn.functional as F class UNetUpsamplingBlock(nn.Module): def __init__(self, in_channels, out_channels): super(UNetUpsamplingBlock, self).__init__() params = {'kernel_size': 3, 'stride': 1, 'padding': 1, 'bias': True} self.conv = nn.Conv2d(in_channels, out_channels, **params) self.relu = nn.ReLU(inplace=True) self.instance_norm = nn.InstanceNorm2d(out_channels, affine=True) def forward(self, x): x = F.interpolate(x, scale_factor=2, mode='nearest') x = self.conv(x) x = self.relu(x) x = self.instance_norm(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 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__native_batch_norm_legit_convolution_repeat_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr3, out_ptr4, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 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) x0 = xindex r3 = rindex x1 = xindex % 4 tmp0 = tl.load(in_ptr0 + x0 % 4, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_out_ptr0 + (r3 + 64 * x0), xmask, other=0.0) tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp30 = tl.load(in_ptr2 + x0 % 4, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tl.full([1, 1], 0, tl.int32) tmp5 = triton_helpers.maximum(tmp4, tmp3) tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tl.where(xmask, tmp6, 0) tmp9 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK]) tmp11 = tl.where(xmask, tmp9, 0) tmp12 = tl.sum(tmp11, 1)[:, None] tmp13 = tl.full([XBLOCK, 1], 64, tl.int32) tmp14 = tmp13.to(tl.float32) tmp15 = tmp12 / tmp14 tmp16 = tmp6 - tmp15 tmp17 = tmp16 * tmp16 tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK]) tmp20 = tl.where(xmask, tmp18, 0) tmp21 = tl.sum(tmp20, 1)[:, None] tmp22 = tmp5 - tmp15 tmp23 = 64.0 tmp24 = tmp21 / tmp23 tmp25 = 1e-05 tmp26 = tmp24 + tmp25 tmp27 = libdevice.rsqrt(tmp26) tmp28 = tmp22 * tmp27 tmp29 = tmp28 * tmp0 tmp31 = tmp29 + tmp30 tl.store(out_ptr0 + x0, tmp0, xmask) tl.store(in_out_ptr0 + (r3 + 64 * x0), tmp3, xmask) tl.store(out_ptr3 + (r3 + 64 * x0), tmp31, xmask) tl.store(out_ptr4 + x0, tmp27, xmask) tl.store(out_ptr1 + x0, tmp15, 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, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_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, 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=128, num_warps=4, num_stages=1) del primals_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, 4, 8, 8), (256, 64, 8, 1)) buf3 = empty_strided_cuda((16,), (1,), torch.float32) buf2 = buf1 del buf1 buf4 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) buf8 = empty_strided_cuda((1, 16, 8, 8), (1024, 64, 8, 1), torch. float32) buf7 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) triton_per_fused__native_batch_norm_legit_convolution_repeat_1[grid(16) ](buf2, primals_4, primals_3, primals_5, buf3, buf4, buf8, buf7, 16, 64, XBLOCK=8, num_warps=4, num_stages=1) del primals_3 del primals_4 del primals_5 return reinterpret_tensor(buf8, (4, 4, 8, 8), (256, 64, 8, 1), 0 ), primals_2, buf0, buf2, buf3, reinterpret_tensor(buf7, (16,), (1,), 0 ), reinterpret_tensor(buf4, (1, 16, 1, 1), (16, 1, 1, 1), 0) class UNetUpsamplingBlockNew(nn.Module): def __init__(self, in_channels, out_channels): super(UNetUpsamplingBlockNew, self).__init__() params = {'kernel_size': 3, 'stride': 1, 'padding': 1, 'bias': True} self.conv = nn.Conv2d(in_channels, out_channels, **params) self.relu = nn.ReLU(inplace=True) self.instance_norm = nn.InstanceNorm2d(out_channels, affine=True) def forward(self, input_0): primals_2 = self.conv.weight primals_3 = self.conv.bias primals_4 = self.instance_norm.weight primals_5 = self.instance_norm.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
TropComplique/bicycle-gan
UNetUpsamplingBlock
false
18,047
[ "MIT" ]
4
4bc8f4cdbe138e23c8a02c408cfb8e2ff7dfe6ab
https://github.com/TropComplique/bicycle-gan/tree/4bc8f4cdbe138e23c8a02c408cfb8e2ff7dfe6ab
_BahdanauAttention
import math import torch from torch import nn from torch.nn import functional class _BahdanauAttention(nn.Module): def __init__(self, method, hidden_size): super(_BahdanauAttention, self).__init__() self.method = method self.hidden_size = hidden_size self.attn = nn.Linear(self.hidden_size * 2, hidden_size) self.v = nn.Parameter(torch.rand(hidden_size)) stdv = 1.0 / math.sqrt(self.v.size(0)) self.v.data.normal_(mean=0, std=stdv) def forward(self, hidden, encoder_outputs, mask=None): """ :param hidden: previous hidden state of the decoder, in shape (layers*directions,B,H) :param encoder_outputs: encoder outputs from Encoder, in shape (T,B,H) :param mask: used for masking. NoneType or tensor in shape (B) indicating sequence length :return attention energies in shape (B,T) """ max_len = encoder_outputs.size(0) H = hidden.repeat(max_len, 1, 1).transpose(0, 1) encoder_outputs = encoder_outputs.transpose(0, 1) attn_energies = self.score(H, encoder_outputs) if mask is not None: attn_energies = attn_energies.masked_fill(mask, -1e+18) return functional.softmax(attn_energies).unsqueeze(1) def score(self, hidden, encoder_outputs): energy = functional.tanh(self.attn(torch.cat([hidden, encoder_outputs], 2))) energy = energy.transpose(2, 1) v = self.v.repeat(encoder_outputs.data.shape[0], 1).unsqueeze(1) energy = torch.bmm(v, energy) return energy.squeeze(1) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'method': 4, '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 libdevice, math as tl_math import math from torch import nn from torch.nn import functional 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 = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x2 = xindex // 32 x1 = xindex // 8 % 4 x3 = 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 * x2 + 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 * x2 + 16 * x1 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x3, tmp10, xmask) @triton.jit def triton_poi_fused_tanh_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 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) @triton.jit def triton_poi_fused_repeat_2(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 % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x2, tmp0, xmask) @triton.jit def triton_poi_fused__softmax_3(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_4(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) 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, 8), (8, 1)) assert_size_stride(primals_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, 8), (32, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(128)](primals_2, primals_1, buf0, 128, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 del primals_2 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (16, 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), (16, 4, 1), 0) del buf1 triton_poi_fused_tanh_1[grid(64)](buf2, primals_4, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_4 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_repeat_2[grid(16)](primals_5, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf4 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (4, 1, 4), (4, 0, 1), 0 ), reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), out=buf4) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__softmax_3[grid(16)](buf4, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1) buf6 = reinterpret_tensor(buf4, (4, 4), (4, 1), 0) del buf4 triton_poi_fused__softmax_4[grid(16)](buf5, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf5 return reinterpret_tensor(buf6, (4, 1, 4), (4, 4, 1), 0 ), reinterpret_tensor(buf0, (16, 8), (8, 1), 0 ), buf2, buf6, reinterpret_tensor(buf3, (4, 4, 1), (4, 1, 4), 0) class _BahdanauAttentionNew(nn.Module): def __init__(self, method, hidden_size): super(_BahdanauAttentionNew, self).__init__() self.method = method self.hidden_size = hidden_size self.attn = nn.Linear(self.hidden_size * 2, hidden_size) self.v = nn.Parameter(torch.rand(hidden_size)) stdv = 1.0 / math.sqrt(self.v.size(0)) self.v.data.normal_(mean=0, std=stdv) def score(self, hidden, encoder_outputs): energy = functional.tanh(self.attn(torch.cat([hidden, encoder_outputs], 2))) energy = energy.transpose(2, 1) v = self.v.repeat(encoder_outputs.data.shape[0], 1).unsqueeze(1) energy = torch.bmm(v, energy) return energy.squeeze(1) def forward(self, input_0, input_1): primals_4 = self.v primals_3 = self.attn.weight primals_5 = self.attn.bias primals_2 = input_0 primals_1 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
VarnithChordia/Multlingual_Punctuation_restoration
_BahdanauAttention
false
18,048
[ "MIT" ]
8
17c026e8935b9fecae01d446a756926c7733fcd1
https://github.com/VarnithChordia/Multlingual_Punctuation_restoration/tree/17c026e8935b9fecae01d446a756926c7733fcd1
loss_shape_exp
import torch import torch.nn as nn class loss_shape_exp(nn.Module): def __init__(self): super().__init__() def forward(self, x, y, beta=2): return torch.mean(torch.exp(beta * y) * torch.pow(x - y, 2)) 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_per_fused_exp_mean_mul_pow_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) tmp4 = tl.load(in_ptr1 + r0, None) tmp1 = 2.0 tmp2 = tmp0 * tmp1 tmp3 = tl_math.exp(tmp2) tmp5 = tmp4 - tmp0 tmp6 = tmp5 * tmp5 tmp7 = tmp3 * tmp6 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_exp_mean_mul_pow_sub_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 loss_shape_expNew(nn.Module): def __init__(self): super().__init__() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
Tsinghua-gongjing/StructureImpute
loss_shape_exp
false
18,049
[ "MIT" ]
9
59e33e913998a8841c2cb552828f0f0cc19ebc21
https://github.com/Tsinghua-gongjing/StructureImpute/tree/59e33e913998a8841c2cb552828f0f0cc19ebc21
ResBlk
import torch import torch.nn as nn import torch.nn.functional as F class FRN(nn.Module): def __init__(self, num_features, eps=1e-05): super(FRN, self).__init__() self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.gamma = nn.Parameter(torch.ones(1, num_features, 1, 1)) self.beta = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.eps = eps def forward(self, x): x = x * torch.rsqrt(torch.mean(x ** 2, dim=[2, 3], keepdim=True) + self.eps) return torch.max(self.gamma * x + self.beta, self.tau) class ResBlk(nn.Module): """Preactivation residual block with filter response norm.""" def __init__(self, dim_in, dim_out, style_dim=64, downsample=False): super(ResBlk, self).__init__() self.conv1 = nn.Conv2d(dim_in, dim_in, 3, 1, 1) self.downsample = downsample self.conv2 = nn.Conv2d(dim_in, dim_out, 3, 1, 1) self.norm1 = FRN(dim_in) self.norm2 = FRN(dim_in) if self.downsample: self.conv1x1 = nn.Conv2d(dim_in, dim_out, 4, 2, 1) def _shortcut(self, x): if self.downsample: x = self.conv1x1(x) return x def _residual(self, x): x = self.norm1(x) x = self.conv1(x) x = self.norm2(x) if self.downsample: x = F.avg_pool2d(x, 2) x = self.conv2(x) return x def forward(self, x): x = self._residual(x) + self._shortcut(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'dim_in': 4, 'dim_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 from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice 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_per_fused_add_maximum_mean_mul_pow_rsqrt_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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) r1 = rindex x0 = xindex x2 = xindex % 4 tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp11 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last') tmp14 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last') tmp16 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last') tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.where(xmask, tmp2, 0) tmp5 = tl.sum(tmp4, 1)[:, None] tmp6 = 16.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp12 = tmp0 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tmp17 = triton_helpers.maximum(tmp15, tmp16) tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp10, xmask) tl.store(out_ptr0 + (r1 + 16 * x0), tmp17, xmask) @triton.jit def triton_per_fused_add_convolution_maximum_mean_mul_pow_rsqrt_1(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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 x3 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + (r2 + 16 * x3), xmask, other=0.0) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp13 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp16 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp18 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tmp2 * tmp2 tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp6 = tl.where(xmask, tmp4, 0) tmp7 = tl.sum(tmp6, 1)[:, None] tmp8 = 16.0 tmp9 = tmp7 / tmp8 tmp10 = 1e-05 tmp11 = tmp9 + tmp10 tmp12 = libdevice.rsqrt(tmp11) tmp14 = tmp2 * tmp12 tmp15 = tmp13 * tmp14 tmp17 = tmp15 + tmp16 tmp19 = triton_helpers.maximum(tmp17, tmp18) tl.store(in_out_ptr0 + (r2 + 16 * x3), tmp2, xmask) tl.debug_barrier() tl.store(in_out_ptr1 + x3, tmp12, xmask) tl.store(out_ptr0 + (r2 + 16 * x3), tmp19, xmask) @triton.jit def triton_poi_fused_add_convolution_2(in_out_ptr0, in_ptr0, in_ptr1, 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') tmp3 = tl.load(in_ptr1 + x3, xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tl.store(in_out_ptr0 + x3, tmp4, 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, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_4, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_8, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_9, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_10, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_11, (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 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_maximum_mean_mul_pow_rsqrt_0[grid(16)](buf1, primals_1, primals_2, primals_3, primals_4, buf2, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) buf3 = extern_kernels.convolution(buf2, primals_5, stride=(1, 1), padding=(1, 1), 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 buf5 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32) buf6 = reinterpret_tensor(buf5, (4, 4, 1, 1), (4, 1, 1, 1), 0) del buf5 buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_per_fused_add_convolution_maximum_mean_mul_pow_rsqrt_1[grid(16) ](buf4, buf6, primals_6, primals_7, primals_8, primals_9, buf7, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) del primals_6 buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 4, 4, 4), (64, 16, 4, 1)) buf9 = buf8 del buf8 triton_poi_fused_add_convolution_2[grid(256)](buf9, primals_11, primals_1, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_11 return (buf9, primals_1, primals_2, primals_3, primals_4, primals_5, primals_7, primals_8, primals_9, primals_10, buf1, buf2, buf4, buf6, buf7) class FRN(nn.Module): def __init__(self, num_features, eps=1e-05): super(FRN, self).__init__() self.tau = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.gamma = nn.Parameter(torch.ones(1, num_features, 1, 1)) self.beta = nn.Parameter(torch.zeros(1, num_features, 1, 1)) self.eps = eps def forward(self, x): x = x * torch.rsqrt(torch.mean(x ** 2, dim=[2, 3], keepdim=True) + self.eps) return torch.max(self.gamma * x + self.beta, self.tau) class ResBlkNew(nn.Module): """Preactivation residual block with filter response norm.""" def __init__(self, dim_in, dim_out, style_dim=64, downsample=False): super(ResBlkNew, self).__init__() self.conv1 = nn.Conv2d(dim_in, dim_in, 3, 1, 1) self.downsample = downsample self.conv2 = nn.Conv2d(dim_in, dim_out, 3, 1, 1) self.norm1 = FRN(dim_in) self.norm2 = FRN(dim_in) if self.downsample: self.conv1x1 = nn.Conv2d(dim_in, dim_out, 4, 2, 1) def _shortcut(self, x): if self.downsample: x = self.conv1x1(x) return x def _residual(self, x): x = self.norm1(x) x = self.conv1(x) x = self.norm2(x) if self.downsample: x = F.avg_pool2d(x, 2) x = self.conv2(x) return x def forward(self, input_0): primals_5 = self.conv1.weight primals_6 = self.conv1.bias primals_10 = self.conv2.weight primals_11 = self.conv2.bias primals_2 = self.norm1.tau primals_3 = self.norm1.gamma primals_4 = self.norm1.beta primals_7 = self.norm2.tau primals_8 = self.norm2.gamma primals_9 = self.norm2.beta 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]) return output[0]
UdonDa/StarGAN-v2-pytorch-nonofficial
ResBlk
false
18,050
[ "MIT" ]
9
219df6b7fd4bd533686e2093ee914a337914ca9b
https://github.com/UdonDa/StarGAN-v2-pytorch-nonofficial/tree/219df6b7fd4bd533686e2093ee914a337914ca9b
TransformerEncoderLayer
import math import torch import warnings from torch import Tensor import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ import torch.nn.functional as F from typing import Optional from typing import Tuple from typing import List def _in_projection_packed(q: 'Tensor', k: 'Tensor', v: 'Tensor', w: 'Tensor', b: 'Optional[Tensor]'=None) ->List[Tensor]: E = q.size(-1) if k is v: if q is k: return F.linear(q, w, b).chunk(3, dim=-1) else: w_q, w_kv = w.split([E, E * 2]) if b is None: b_q = b_kv = None else: b_q, b_kv = b.split([E, E * 2]) return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk( 2, dim=-1) else: w_q, w_k, w_v = w.chunk(3) if b is None: b_q = b_k = b_v = None else: b_q, b_k, b_v = b.chunk(3) return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v) def scale_dot_attention(q: 'Tensor', k: 'Tensor', v: 'Tensor', dropout_p: 'float'=0.0, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Tensor]: _, _, E = q.shape q = q / math.sqrt(E) attn = torch.bmm(q, k.transpose(-2, -1)) if attn_mask is not None: attn = attn + attn_mask attn = F.softmax(attn, dim=-1) if dropout_p: attn = F.dropout(attn, p=dropout_p) out = torch.bmm(attn, v) return out, attn def multi_head_attention_forward(query: 'Tensor', key: 'Tensor', value: 'Tensor', num_heads: 'int', in_proj_weight: 'Tensor', in_proj_bias: 'Optional[Tensor]', dropout_p: 'float', out_proj_weight: 'Tensor', out_proj_bias: 'Optional[Tensor]', training: 'bool'=True, key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'=True, attn_mask: 'Optional[Tensor]'=None, use_separate_proj_weight=None, q_proj_weight: 'Optional[Tensor]'=None, k_proj_weight: 'Optional[Tensor]'=None, v_proj_weight: 'Optional[Tensor]'=None) ->Tuple[ Tensor, Optional[Tensor]]: tgt_len, bsz, embed_dim = query.shape src_len, _, _ = key.shape head_dim = embed_dim // num_heads q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias) if attn_mask is not None: if attn_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) attn_mask = attn_mask else: assert attn_mask.is_floating_point( ) or attn_mask.dtype == torch.bool, f'Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}' if attn_mask.dim() == 2: correct_2d_size = tgt_len, src_len if attn_mask.shape != correct_2d_size: raise RuntimeError( f'The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.' ) attn_mask = attn_mask.unsqueeze(0) elif attn_mask.dim() == 3: correct_3d_size = bsz * num_heads, tgt_len, src_len if attn_mask.shape != correct_3d_size: raise RuntimeError( f'The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.' ) else: raise RuntimeError( f"attn_mask's dimension {attn_mask.dim()} is not supported") if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) key_padding_mask = key_padding_mask q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) if key_padding_mask is not None: assert key_padding_mask.shape == (bsz, src_len ), f'expecting key_padding_mask shape of {bsz, src_len}, but got {key_padding_mask.shape}' key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len).expand( -1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len) if attn_mask is None: attn_mask = key_padding_mask elif attn_mask.dtype == torch.bool: attn_mask = attn_mask.logical_or(key_padding_mask) else: attn_mask = attn_mask.masked_fill(key_padding_mask, float('-inf')) if attn_mask is not None and attn_mask.dtype == torch.bool: new_attn_mask = torch.zeros_like(attn_mask, dtype=torch.float) new_attn_mask.masked_fill_(attn_mask, float('-inf')) attn_mask = new_attn_mask if not training: dropout_p = 0.0 attn_output, attn_output_weights = scale_dot_attention(q, k, v, attn_mask, dropout_p) attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn_output = nn.functional.linear(attn_output, out_proj_weight, out_proj_bias) if need_weights: attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len) return attn_output, attn_output_weights.sum(dim=1) / num_heads else: return attn_output, None def positional_encoding(X, num_features, dropout_p=0.1, max_len=512) ->Tensor: nn.Dropout(dropout_p) return X class MultiheadAttention(nn.Module): def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True, kdim= None, vdim=None, batch_first=False) ->None: super(MultiheadAttention, self).__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self._qkv_same_embed_dim = (self.kdim == self.embed_dim and self. vdim == self.embed_dim) self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads' if self._qkv_same_embed_dim is False: self.q_proj_weight = Parameter(torch.empty((embed_dim, embed_dim))) self.k_proj_weight = Parameter(torch.empty((embed_dim, self.kdim))) self.v_proj_weight = Parameter(torch.empty((embed_dim, self.vdim))) self.register_parameter('in_proj_weight', None) else: self.in_proj_weight = Parameter(torch.empty((3 * embed_dim, embed_dim))) self.register_parameter('q_proj_weight', None) self.register_parameter('k_proj_weight', None) self.register_parameter('v_proj_weight', None) if bias: self.in_proj_bias = Parameter(torch.empty(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self._reset_parameters() def _reset_parameters(self): if self._qkv_same_embed_dim: xavier_uniform_(self.in_proj_weight) else: xavier_uniform_(self.q_proj_weight) xavier_uniform_(self.k_proj_weight) xavier_uniform_(self.v_proj_weight) if self.in_proj_bias is not None: constant_(self.in_proj_bias, 0.0) constant_(self.out_proj.bias, 0.0) def forward(self, query: 'Tensor', key: 'Tensor', value: 'Tensor', key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'= True, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Optional[ Tensor]]: if self.batch_first: query, key, value = [x.transpose(1, 0) for x in (query, key, value) ] if not self._qkv_same_embed_dim: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask, use_separate_proj_weight=True, q_proj_weight= self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight) else: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask) if self.batch_first: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=F.relu, layer_norm_eps=1e-05, batch_first=False) ->None: super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=batch_first) 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, eps=layer_norm_eps) self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = activation def forward(self, src: 'Tensor', src_mask: 'Optional[Tensor]'=None, src_key_padding_mask: 'Optional[Tensor]'=None) ->Tensor: src = positional_encoding(src, src.shape[-1]) 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.dropout(src2) src = self.norm2(src) return src def get_inputs(): return [torch.rand([4, 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 math import warnings from torch import Tensor import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ import torch.nn.functional as F from typing import Optional from typing import Tuple from typing import List 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, 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 + (8 + x0 + 12 * x1), xmask) tmp1 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_div_1(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 % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (12 * (x0 // 4) + 48 * x1 + x0 % 4), xmask) tmp1 = tl.load(in_ptr1 + x2 % 4, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_clone_2(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 + 12 * x1), xmask) tmp1 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused__softmax_add_3(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 = 0.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 = tl_math.exp(tmp14) tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_poi_fused__softmax_4(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_clone_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 4 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 x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_native_layer_norm_6(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_7(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_8(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 % 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) 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_9(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_10(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_11(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, 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,)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (2048, 4), (4, 1)) assert_size_stride(primals_9, (2048,), (1,)) assert_size_stride(primals_10, (4, 2048), (2048, 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, 12), (12, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 12), (1, 4), 0), out=buf0) del primals_2 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(64)](buf0, primals_3, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((16, 4, 1), (1, 16, 64), torch.float32) triton_poi_fused_div_1[grid(64)](buf0, primals_3, buf2, 64, XBLOCK= 64, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_clone_2[grid(64)](buf0, primals_3, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 del primals_3 buf4 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf2, reinterpret_tensor(buf3, (16, 1, 4), (1, 0, 16), 0), out=buf4) buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_add_3[grid(256)](buf4, buf5, 256, XBLOCK= 128, num_warps=4, num_stages=1) buf6 = buf4 del buf4 triton_poi_fused__softmax_4[grid(256)](buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf5 buf7 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf6, reinterpret_tensor(buf1, (16, 4, 1), (1, 16, 0), 0), out=buf7) buf8 = empty_strided_cuda((4, 16, 1), (16, 1, 1), torch.float32) triton_poi_fused_clone_5[grid(4, 16)](buf7, buf8, 4, 16, XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1) buf9 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0) del buf7 extern_kernels.addmm(primals_5, reinterpret_tensor(buf8, (16, 4), ( 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf9) del primals_5 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_6[grid(16)](primals_1, 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_7[grid(64)](primals_1, 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, 2048), (2048, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor(primals_8, (4, 2048), (1, 4), 0), out=buf13) buf14 = reinterpret_tensor(buf13, (4, 4, 2048), (8192, 2048, 1), 0) del buf13 buf20 = empty_strided_cuda((4, 4, 2048), (8192, 2048, 1), torch.bool) triton_poi_fused_relu_threshold_backward_8[grid(32768)](buf14, primals_9, buf20, 32768, XBLOCK=128, num_warps=4, num_stages=1) del primals_9 buf15 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf14, (16, 2048), (2048, 1), 0), reinterpret_tensor(primals_10, (2048, 4), (1, 2048), 0), out=buf15) buf16 = reinterpret_tensor(buf15, (4, 4, 4), (16, 4, 1), 0) del buf15 triton_poi_fused_add_9[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_10[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_11[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_1, primals_6, primals_12, buf6, reinterpret_tensor( buf8, (16, 4), (4, 1), 0), buf9, reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor(buf14, (16, 2048), (2048, 1), 0 ), buf16, primals_10, buf20, primals_8, primals_4, reinterpret_tensor( buf1, (16, 1, 4), (1, 1, 16), 0), reinterpret_tensor(buf2, (16, 1, 4), (1, 1, 16), 0), reinterpret_tensor(buf3, (16, 4, 1), (1, 16, 1), 0) def _in_projection_packed(q: 'Tensor', k: 'Tensor', v: 'Tensor', w: 'Tensor', b: 'Optional[Tensor]'=None) ->List[Tensor]: E = q.size(-1) if k is v: if q is k: return F.linear(q, w, b).chunk(3, dim=-1) else: w_q, w_kv = w.split([E, E * 2]) if b is None: b_q = b_kv = None else: b_q, b_kv = b.split([E, E * 2]) return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk( 2, dim=-1) else: w_q, w_k, w_v = w.chunk(3) if b is None: b_q = b_k = b_v = None else: b_q, b_k, b_v = b.chunk(3) return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v) def scale_dot_attention(q: 'Tensor', k: 'Tensor', v: 'Tensor', dropout_p: 'float'=0.0, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Tensor]: _, _, E = q.shape q = q / math.sqrt(E) attn = torch.bmm(q, k.transpose(-2, -1)) if attn_mask is not None: attn = attn + attn_mask attn = F.softmax(attn, dim=-1) if dropout_p: attn = F.dropout(attn, p=dropout_p) out = torch.bmm(attn, v) return out, attn def multi_head_attention_forward(query: 'Tensor', key: 'Tensor', value: 'Tensor', num_heads: 'int', in_proj_weight: 'Tensor', in_proj_bias: 'Optional[Tensor]', dropout_p: 'float', out_proj_weight: 'Tensor', out_proj_bias: 'Optional[Tensor]', training: 'bool'=True, key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'=True, attn_mask: 'Optional[Tensor]'=None, use_separate_proj_weight=None, q_proj_weight: 'Optional[Tensor]'=None, k_proj_weight: 'Optional[Tensor]'=None, v_proj_weight: 'Optional[Tensor]'=None) ->Tuple[ Tensor, Optional[Tensor]]: tgt_len, bsz, embed_dim = query.shape src_len, _, _ = key.shape head_dim = embed_dim // num_heads q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias) if attn_mask is not None: if attn_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) attn_mask = attn_mask else: assert attn_mask.is_floating_point( ) or attn_mask.dtype == torch.bool, f'Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}' if attn_mask.dim() == 2: correct_2d_size = tgt_len, src_len if attn_mask.shape != correct_2d_size: raise RuntimeError( f'The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.' ) attn_mask = attn_mask.unsqueeze(0) elif attn_mask.dim() == 3: correct_3d_size = bsz * num_heads, tgt_len, src_len if attn_mask.shape != correct_3d_size: raise RuntimeError( f'The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.' ) else: raise RuntimeError( f"attn_mask's dimension {attn_mask.dim()} is not supported") if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) key_padding_mask = key_padding_mask q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) if key_padding_mask is not None: assert key_padding_mask.shape == (bsz, src_len ), f'expecting key_padding_mask shape of {bsz, src_len}, but got {key_padding_mask.shape}' key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len).expand( -1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len) if attn_mask is None: attn_mask = key_padding_mask elif attn_mask.dtype == torch.bool: attn_mask = attn_mask.logical_or(key_padding_mask) else: attn_mask = attn_mask.masked_fill(key_padding_mask, float('-inf')) if attn_mask is not None and attn_mask.dtype == torch.bool: new_attn_mask = torch.zeros_like(attn_mask, dtype=torch.float) new_attn_mask.masked_fill_(attn_mask, float('-inf')) attn_mask = new_attn_mask if not training: dropout_p = 0.0 attn_output, attn_output_weights = scale_dot_attention(q, k, v, attn_mask, dropout_p) attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn_output = nn.functional.linear(attn_output, out_proj_weight, out_proj_bias) if need_weights: attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len) return attn_output, attn_output_weights.sum(dim=1) / num_heads else: return attn_output, None def positional_encoding(X, num_features, dropout_p=0.1, max_len=512) ->Tensor: nn.Dropout(dropout_p) return X class MultiheadAttention(nn.Module): def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True, kdim= None, vdim=None, batch_first=False) ->None: super(MultiheadAttention, self).__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self._qkv_same_embed_dim = (self.kdim == self.embed_dim and self. vdim == self.embed_dim) self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads' if self._qkv_same_embed_dim is False: self.q_proj_weight = Parameter(torch.empty((embed_dim, embed_dim))) self.k_proj_weight = Parameter(torch.empty((embed_dim, self.kdim))) self.v_proj_weight = Parameter(torch.empty((embed_dim, self.vdim))) self.register_parameter('in_proj_weight', None) else: self.in_proj_weight = Parameter(torch.empty((3 * embed_dim, embed_dim))) self.register_parameter('q_proj_weight', None) self.register_parameter('k_proj_weight', None) self.register_parameter('v_proj_weight', None) if bias: self.in_proj_bias = Parameter(torch.empty(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self._reset_parameters() def _reset_parameters(self): if self._qkv_same_embed_dim: xavier_uniform_(self.in_proj_weight) else: xavier_uniform_(self.q_proj_weight) xavier_uniform_(self.k_proj_weight) xavier_uniform_(self.v_proj_weight) if self.in_proj_bias is not None: constant_(self.in_proj_bias, 0.0) constant_(self.out_proj.bias, 0.0) def forward(self, query: 'Tensor', key: 'Tensor', value: 'Tensor', key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'= True, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Optional[ Tensor]]: if self.batch_first: query, key, value = [x.transpose(1, 0) for x in (query, key, value) ] if not self._qkv_same_embed_dim: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask, use_separate_proj_weight=True, q_proj_weight= self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight) else: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask) if self.batch_first: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class TransformerEncoderLayerNew(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=F.relu, layer_norm_eps=1e-05, batch_first=False) ->None: super(TransformerEncoderLayerNew, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=batch_first) 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, eps=layer_norm_eps) self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = activation def forward(self, input_0): primals_2 = self.self_attn.in_proj_weight primals_3 = self.self_attn.in_proj_bias primals_4 = self.self_attn.out_proj.weight primals_5 = self.self_attn.out_proj.bias primals_8 = self.linear1.weight primals_9 = self.linear1.bias primals_10 = self.linear2.weight primals_6 = self.linear2.bias primals_7 = self.norm1.weight primals_11 = self.norm1.bias primals_12 = self.norm2.weight primals_13 = self.norm2.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]
Treedy2020/TransNet
TransformerEncoderLayer
false
18,051
[ "MIT" ]
4
dd0e43e1931153baea4e5fe8cb31dc5ff0cb7b09
https://github.com/Treedy2020/TransNet/tree/dd0e43e1931153baea4e5fe8cb31dc5ff0cb7b09
BertSelfAttention
from _paritybench_helpers import _mock_config import math import torch from torch import nn class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( 'The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config. num_attention_heads) self.all_head_size = (self.num_attention_heads * self. attention_head_size) self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self. attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self. attention_head_size) attention_scores = attention_scores + attention_mask attention_probs = nn.Softmax(dim=-1)(attention_scores) attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self. all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(hidden_size=4, num_attention_heads= 4, attention_probs_dropout_prob=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 import triton_helpers from torch._inductor.runtime.triton_helpers import 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_0(in_ptr0, in_ptr1, 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') tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask) @triton.jit def triton_poi_fused_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, 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 % 16 tmp0 = tl.load(in_ptr0 + 4 * x2, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x2), 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 * x2), 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 * x2), 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 = triton_helpers.maximum(tmp2, tmp5) tmp9 = tmp7 + tmp8 tmp10 = triton_helpers.maximum(tmp6, tmp9) tmp13 = tmp11 + tmp12 tmp14 = triton_helpers.maximum(tmp10, tmp13) tmp15 = tmp2 - tmp14 tmp16 = tl_math.exp(tmp15) tmp17 = tmp5 - tmp14 tmp18 = tl_math.exp(tmp17) tmp19 = tmp16 + tmp18 tmp20 = tmp9 - tmp14 tmp21 = tl_math.exp(tmp20) tmp22 = tmp19 + tmp21 tmp23 = tmp13 - tmp14 tmp24 = tl_math.exp(tmp23) tmp25 = tmp22 + tmp24 tmp26 = float('-inf') tmp27 = tmp2 == tmp26 tmp28 = tmp27 == 0 tmp29 = tmp28.to(tl.int64) tmp30 = tmp29 != 0 tmp31 = tmp5 == tmp26 tmp32 = tmp31 == 0 tmp33 = tmp32.to(tl.int64) tmp34 = tmp33 != 0 tmp35 = tmp30 | tmp34 tmp36 = tmp9 == tmp26 tmp37 = tmp36 == 0 tmp38 = tmp37.to(tl.int64) tmp39 = tmp38 != 0 tmp40 = tmp35 | tmp39 tmp41 = tmp13 == tmp26 tmp42 = tmp41 == 0 tmp43 = tmp42.to(tl.int64) tmp44 = tmp43 != 0 tmp45 = tmp40 | tmp44 tl.store(out_ptr0 + x2, tmp14, xmask) tl.store(out_ptr1 + x2, tmp25, xmask) tl.store(out_ptr2 + x2, tmp45, xmask) @triton.jit def triton_poi_fused_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex // 4 x4 = xindex x5 = xindex % 64 tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last').to(tl .int1) tmp2 = tl.load(in_out_ptr0 + x4, xmask) tmp3 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr3 + x3, xmask, eviction_policy='evict_last') tmp1 = tmp0 == 0 tmp4 = tmp2 + tmp3 tmp6 = tmp4 - tmp5 tmp7 = tl_math.exp(tmp6) tmp9 = tmp7 / tmp8 tmp10 = 0.0 tmp11 = tl.where(tmp1, tmp10, tmp9) tl.store(in_out_ptr0 + x4, tmp11, xmask) @triton.jit def triton_poi_fused_3(in_ptr0, in_ptr1, 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') tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask) @triton.jit def triton_poi_fused_clone_4(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, 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), (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, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4, 4), (16, 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_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) del primals_4 buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2) del primals_6 buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) del primals_2 buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf0 triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5) buf6 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 64), 0) del buf1 buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32) buf8 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.bool) triton_poi_fused_1[grid(64)](buf5, primals_8, buf6, buf7, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf5 triton_poi_fused_2[grid(256)](buf9, buf8, primals_8, buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf8 del primals_8 buf10 = reinterpret_tensor(buf7, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf7 triton_poi_fused_3[grid(16, 4)](buf2, primals_7, buf10, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) del primals_7 buf11 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0) del buf2 extern_kernels.bmm(reinterpret_tensor(buf9, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf10, (16, 4, 1), (4, 1, 0), 0), out=buf11) buf12 = reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf6 triton_poi_fused_clone_4[grid(16, 4)](buf11, buf12, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) del buf11 return reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0 ), buf9, reinterpret_tensor(buf10, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0) class BertSelfAttentionNew(nn.Module): def __init__(self, config): super(BertSelfAttentionNew, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( 'The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config. num_attention_heads) self.all_head_size = (self.num_attention_heads * self. attention_head_size) self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self. attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, input_0, input_1): primals_1 = self.query.weight primals_2 = self.query.bias primals_4 = self.key.weight primals_5 = self.key.bias primals_6 = self.value.weight primals_7 = self.value.bias primals_3 = input_0 primals_8 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8]) return output[0]
Ahren09/FinerFact
BertSelfAttention
false
18,052
[ "MIT" ]
9
68df3799fbfadd56fa69b019ca6fba0c482f21d3
https://github.com/Ahren09/FinerFact/tree/68df3799fbfadd56fa69b019ca6fba0c482f21d3
TransformerDecoderLayer
import math import torch import warnings from torch import Tensor import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ import torch.nn.functional as F from typing import Optional from typing import Tuple from typing import List def _in_projection_packed(q: 'Tensor', k: 'Tensor', v: 'Tensor', w: 'Tensor', b: 'Optional[Tensor]'=None) ->List[Tensor]: E = q.size(-1) if k is v: if q is k: return F.linear(q, w, b).chunk(3, dim=-1) else: w_q, w_kv = w.split([E, E * 2]) if b is None: b_q = b_kv = None else: b_q, b_kv = b.split([E, E * 2]) return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk( 2, dim=-1) else: w_q, w_k, w_v = w.chunk(3) if b is None: b_q = b_k = b_v = None else: b_q, b_k, b_v = b.chunk(3) return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v) def scale_dot_attention(q: 'Tensor', k: 'Tensor', v: 'Tensor', dropout_p: 'float'=0.0, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Tensor]: _, _, E = q.shape q = q / math.sqrt(E) attn = torch.bmm(q, k.transpose(-2, -1)) if attn_mask is not None: attn = attn + attn_mask attn = F.softmax(attn, dim=-1) if dropout_p: attn = F.dropout(attn, p=dropout_p) out = torch.bmm(attn, v) return out, attn def multi_head_attention_forward(query: 'Tensor', key: 'Tensor', value: 'Tensor', num_heads: 'int', in_proj_weight: 'Tensor', in_proj_bias: 'Optional[Tensor]', dropout_p: 'float', out_proj_weight: 'Tensor', out_proj_bias: 'Optional[Tensor]', training: 'bool'=True, key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'=True, attn_mask: 'Optional[Tensor]'=None, use_separate_proj_weight=None, q_proj_weight: 'Optional[Tensor]'=None, k_proj_weight: 'Optional[Tensor]'=None, v_proj_weight: 'Optional[Tensor]'=None) ->Tuple[ Tensor, Optional[Tensor]]: tgt_len, bsz, embed_dim = query.shape src_len, _, _ = key.shape head_dim = embed_dim // num_heads q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias) if attn_mask is not None: if attn_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) attn_mask = attn_mask else: assert attn_mask.is_floating_point( ) or attn_mask.dtype == torch.bool, f'Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}' if attn_mask.dim() == 2: correct_2d_size = tgt_len, src_len if attn_mask.shape != correct_2d_size: raise RuntimeError( f'The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.' ) attn_mask = attn_mask.unsqueeze(0) elif attn_mask.dim() == 3: correct_3d_size = bsz * num_heads, tgt_len, src_len if attn_mask.shape != correct_3d_size: raise RuntimeError( f'The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.' ) else: raise RuntimeError( f"attn_mask's dimension {attn_mask.dim()} is not supported") if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) key_padding_mask = key_padding_mask q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) if key_padding_mask is not None: assert key_padding_mask.shape == (bsz, src_len ), f'expecting key_padding_mask shape of {bsz, src_len}, but got {key_padding_mask.shape}' key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len).expand( -1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len) if attn_mask is None: attn_mask = key_padding_mask elif attn_mask.dtype == torch.bool: attn_mask = attn_mask.logical_or(key_padding_mask) else: attn_mask = attn_mask.masked_fill(key_padding_mask, float('-inf')) if attn_mask is not None and attn_mask.dtype == torch.bool: new_attn_mask = torch.zeros_like(attn_mask, dtype=torch.float) new_attn_mask.masked_fill_(attn_mask, float('-inf')) attn_mask = new_attn_mask if not training: dropout_p = 0.0 attn_output, attn_output_weights = scale_dot_attention(q, k, v, attn_mask, dropout_p) attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn_output = nn.functional.linear(attn_output, out_proj_weight, out_proj_bias) if need_weights: attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len) return attn_output, attn_output_weights.sum(dim=1) / num_heads else: return attn_output, None class MultiheadAttention(nn.Module): def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True, kdim= None, vdim=None, batch_first=False) ->None: super(MultiheadAttention, self).__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self._qkv_same_embed_dim = (self.kdim == self.embed_dim and self. vdim == self.embed_dim) self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads' if self._qkv_same_embed_dim is False: self.q_proj_weight = Parameter(torch.empty((embed_dim, embed_dim))) self.k_proj_weight = Parameter(torch.empty((embed_dim, self.kdim))) self.v_proj_weight = Parameter(torch.empty((embed_dim, self.vdim))) self.register_parameter('in_proj_weight', None) else: self.in_proj_weight = Parameter(torch.empty((3 * embed_dim, embed_dim))) self.register_parameter('q_proj_weight', None) self.register_parameter('k_proj_weight', None) self.register_parameter('v_proj_weight', None) if bias: self.in_proj_bias = Parameter(torch.empty(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self._reset_parameters() def _reset_parameters(self): if self._qkv_same_embed_dim: xavier_uniform_(self.in_proj_weight) else: xavier_uniform_(self.q_proj_weight) xavier_uniform_(self.k_proj_weight) xavier_uniform_(self.v_proj_weight) if self.in_proj_bias is not None: constant_(self.in_proj_bias, 0.0) constant_(self.out_proj.bias, 0.0) def forward(self, query: 'Tensor', key: 'Tensor', value: 'Tensor', key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'= True, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Optional[ Tensor]]: if self.batch_first: query, key, value = [x.transpose(1, 0) for x in (query, key, value) ] if not self._qkv_same_embed_dim: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask, use_separate_proj_weight=True, q_proj_weight= self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight) else: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask) if self.batch_first: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=F.relu, layer_norm_eps=1e-05, batch_first=False) ->None: super(TransformerDecoderLayer, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=batch_first) self.multihead_attn = MultiheadAttention(d_model, nhead, dropout= dropout, batch_first=batch_first) 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, eps=layer_norm_eps) self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps) self.norm3 = nn.LayerNorm(d_model, eps=layer_norm_eps) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout) self.activation = activation def forward(self, tgt: 'Tensor', memory: 'Tensor', tgt_mask: 'Optional[Tensor]'=None, memory_mask: 'Optional[Tensor]'=None, tgt_key_padding_mask: 'Optional[Tensor]'=None, memory_key_padding_mask: 'Optional[Tensor]'=None) ->Tensor: tgt2 = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt) tgt2 = self.multihead_attn(tgt, memory, memory, attn_mask= memory_mask, key_padding_mask=memory_key_padding_mask)[0] tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout3(tgt2) tgt = self.norm3(tgt) return tgt def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 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 math import warnings from torch import Tensor import torch.nn as nn from torch.nn.parameter import Parameter from torch.nn.init import xavier_uniform_ from torch.nn.init import constant_ import torch.nn.functional as F from typing import Optional from typing import Tuple from typing import List 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, 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 + (8 + x0 + 12 * x1), xmask) tmp1 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_div_1(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 % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (12 * (x0 // 4) + 48 * x1 + x0 % 4), xmask) tmp1 = tl.load(in_ptr1 + x2 % 4, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_clone_2(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 + 12 * x1), xmask) tmp1 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused__softmax_add_3(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 = 0.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 = tl_math.exp(tmp14) tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_poi_fused__softmax_4(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_clone_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 4 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 x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_native_layer_norm_6(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_7(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_clone_8(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 + 8 * x1), xmask) tmp1 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_div_9(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 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x2 % 4, 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_clone_10(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 + (x0 + 8 * x1), xmask) tmp1 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_add_11(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_12(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_13(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) @triton.jit def triton_poi_fused_relu_threshold_backward_14(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 % 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) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, None) tl.store(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, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17, primals_18, primals_19, primals_20) = args args.clear() assert_size_stride(primals_1, (12, 4), (4, 1)) assert_size_stride(primals_2, (12,), (1,)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_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, (12, 4), (4, 1)) assert_size_stride(primals_9, (12,), (1,)) assert_size_stride(primals_10, (4, 4), (4, 1)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_13, (4,), (1,)) assert_size_stride(primals_14, (4,), (1,)) assert_size_stride(primals_15, (2048, 4), (4, 1)) assert_size_stride(primals_16, (2048,), (1,)) assert_size_stride(primals_17, (4, 2048), (2048, 1)) assert_size_stride(primals_18, (4,), (1,)) assert_size_stride(primals_19, (4,), (1,)) assert_size_stride(primals_20, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 12), (12, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_5, (16, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 12), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(64)](buf0, primals_2, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((16, 4, 1), (1, 16, 64), torch.float32) triton_poi_fused_div_1[grid(64)](buf0, primals_2, buf2, 64, XBLOCK= 64, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_clone_2[grid(64)](buf0, primals_2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 del primals_2 buf4 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf2, reinterpret_tensor(buf3, (16, 1, 4), (1, 0, 16), 0), out=buf4) buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_add_3[grid(256)](buf4, buf5, 256, XBLOCK= 128, num_warps=4, num_stages=1) buf6 = buf4 del buf4 triton_poi_fused__softmax_4[grid(256)](buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1) buf7 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf6, reinterpret_tensor(buf1, (16, 4, 1), (1, 16, 0), 0), out=buf7) buf8 = empty_strided_cuda((4, 16, 1), (16, 1, 1), torch.float32) triton_poi_fused_clone_5[grid(4, 16)](buf7, buf8, 4, 16, XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1) buf9 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0) del buf7 extern_kernels.addmm(primals_4, reinterpret_tensor(buf8, (16, 4), ( 4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf9) del primals_4 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_6[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_7[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 = empty_strided_cuda((16, 8), (8, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_12, (16, 4), (4, 1), 0 ), reinterpret_tensor(primals_8, (4, 8), (1, 4), 16), out=buf14) buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_clone_8[grid(64)](buf14, primals_9, buf15, 64, XBLOCK=64, num_warps=1, num_stages=1) buf16 = reinterpret_tensor(buf13, (16, 4, 1), (1, 16, 64), 0) del buf13 triton_poi_fused_div_9[grid(64)](buf16, primals_9, 64, XBLOCK=64, num_warps=1, num_stages=1) buf17 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_clone_10[grid(64)](buf14, primals_9, buf17, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf14 del primals_9 buf18 = buf5 del buf5 extern_kernels.bmm(buf16, reinterpret_tensor(buf17, (16, 1, 4), (1, 0, 16), 0), out=buf18) buf19 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_add_3[grid(256)](buf18, buf19, 256, XBLOCK=128, num_warps=4, num_stages=1) buf20 = buf18 del buf18 triton_poi_fused__softmax_4[grid(256)](buf19, buf20, 256, XBLOCK= 128, num_warps=4, num_stages=1) del buf19 buf21 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf20, reinterpret_tensor(buf15, (16, 4, 1), (1, 16, 0), 0), out=buf21) buf22 = empty_strided_cuda((4, 16, 1), (16, 1, 1), torch.float32) triton_poi_fused_clone_5[grid(4, 16)](buf21, buf22, 4, 16, XBLOCK= 16, YBLOCK=4, num_warps=1, num_stages=1) buf23 = reinterpret_tensor(buf21, (16, 4), (4, 1), 0) del buf21 extern_kernels.mm(reinterpret_tensor(buf22, (16, 4), (4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf23) buf24 = reinterpret_tensor(buf23, (4, 4, 4), (16, 4, 1), 0) del buf23 triton_poi_fused_add_11[grid(64)](buf24, buf12, primals_11, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_11 buf25 = buf11 del buf11 buf26 = buf10 del buf10 triton_poi_fused_native_layer_norm_12[grid(16)](buf24, buf25, buf26, 16, XBLOCK=16, num_warps=1, num_stages=1) buf27 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_native_layer_norm_13[grid(64)](buf24, buf25, buf26, primals_13, primals_14, buf27, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_14 buf28 = empty_strided_cuda((16, 2048), (2048, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf27, (16, 4), (4, 1), 0), reinterpret_tensor(primals_15, (4, 2048), (1, 4), 0), out=buf28) buf29 = reinterpret_tensor(buf28, (4, 4, 2048), (8192, 2048, 1), 0) del buf28 buf35 = empty_strided_cuda((4, 4, 2048), (8192, 2048, 1), torch.bool) triton_poi_fused_relu_threshold_backward_14[grid(32768)](buf29, primals_16, buf35, 32768, XBLOCK=128, num_warps=4, num_stages=1) del primals_16 buf30 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf29, (16, 2048), (2048, 1), 0), reinterpret_tensor(primals_17, (2048, 4), (1, 2048), 0), out=buf30) buf31 = reinterpret_tensor(buf30, (4, 4, 4), (16, 4, 1), 0) del buf30 triton_poi_fused_add_11[grid(64)](buf31, buf27, primals_18, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_18 buf32 = buf26 del buf26 buf33 = buf25 del buf25 triton_poi_fused_native_layer_norm_12[grid(16)](buf31, buf32, buf33, 16, XBLOCK=16, num_warps=1, num_stages=1) buf34 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_native_layer_norm_13[grid(64)](buf31, buf32, buf33, primals_19, primals_20, buf34, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf32 del buf33 del primals_20 return (buf34, primals_5, primals_6, primals_13, primals_19, buf6, reinterpret_tensor(buf8, (16, 4), (4, 1), 0), buf9, reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor( primals_12, (16, 4), (4, 1), 0), buf20, reinterpret_tensor(buf22, ( 16, 4), (4, 1), 0), buf24, reinterpret_tensor(buf27, (16, 4), (4, 1 ), 0), reinterpret_tensor(buf29, (16, 2048), (2048, 1), 0), buf31, primals_17, buf35, primals_15, primals_10, reinterpret_tensor(buf15, (16, 1, 4), (1, 1, 16), 0), reinterpret_tensor(buf16, (16, 1, 4), ( 1, 1, 16), 0), reinterpret_tensor(buf17, (16, 4, 1), (1, 16, 1), 0), reinterpret_tensor(primals_8, (4, 4), (4, 1), 0), primals_3, reinterpret_tensor(buf1, (16, 1, 4), (1, 1, 16), 0), reinterpret_tensor(buf2, (16, 1, 4), (1, 1, 16), 0), reinterpret_tensor(buf3, (16, 4, 1), (1, 16, 1), 0)) def _in_projection_packed(q: 'Tensor', k: 'Tensor', v: 'Tensor', w: 'Tensor', b: 'Optional[Tensor]'=None) ->List[Tensor]: E = q.size(-1) if k is v: if q is k: return F.linear(q, w, b).chunk(3, dim=-1) else: w_q, w_kv = w.split([E, E * 2]) if b is None: b_q = b_kv = None else: b_q, b_kv = b.split([E, E * 2]) return (F.linear(q, w_q, b_q),) + F.linear(k, w_kv, b_kv).chunk( 2, dim=-1) else: w_q, w_k, w_v = w.chunk(3) if b is None: b_q = b_k = b_v = None else: b_q, b_k, b_v = b.chunk(3) return F.linear(q, w_q, b_q), F.linear(k, w_k, b_k), F.linear(v, w_v, b_v) def scale_dot_attention(q: 'Tensor', k: 'Tensor', v: 'Tensor', dropout_p: 'float'=0.0, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Tensor]: _, _, E = q.shape q = q / math.sqrt(E) attn = torch.bmm(q, k.transpose(-2, -1)) if attn_mask is not None: attn = attn + attn_mask attn = F.softmax(attn, dim=-1) if dropout_p: attn = F.dropout(attn, p=dropout_p) out = torch.bmm(attn, v) return out, attn def multi_head_attention_forward(query: 'Tensor', key: 'Tensor', value: 'Tensor', num_heads: 'int', in_proj_weight: 'Tensor', in_proj_bias: 'Optional[Tensor]', dropout_p: 'float', out_proj_weight: 'Tensor', out_proj_bias: 'Optional[Tensor]', training: 'bool'=True, key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'=True, attn_mask: 'Optional[Tensor]'=None, use_separate_proj_weight=None, q_proj_weight: 'Optional[Tensor]'=None, k_proj_weight: 'Optional[Tensor]'=None, v_proj_weight: 'Optional[Tensor]'=None) ->Tuple[ Tensor, Optional[Tensor]]: tgt_len, bsz, embed_dim = query.shape src_len, _, _ = key.shape head_dim = embed_dim // num_heads q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias) if attn_mask is not None: if attn_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) attn_mask = attn_mask else: assert attn_mask.is_floating_point( ) or attn_mask.dtype == torch.bool, f'Only float, byte, and bool types are supported for attn_mask, not {attn_mask.dtype}' if attn_mask.dim() == 2: correct_2d_size = tgt_len, src_len if attn_mask.shape != correct_2d_size: raise RuntimeError( f'The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.' ) attn_mask = attn_mask.unsqueeze(0) elif attn_mask.dim() == 3: correct_3d_size = bsz * num_heads, tgt_len, src_len if attn_mask.shape != correct_3d_size: raise RuntimeError( f'The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.' ) else: raise RuntimeError( f"attn_mask's dimension {attn_mask.dim()} is not supported") if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: warnings.warn( 'Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.' ) key_padding_mask = key_padding_mask q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) if key_padding_mask is not None: assert key_padding_mask.shape == (bsz, src_len ), f'expecting key_padding_mask shape of {bsz, src_len}, but got {key_padding_mask.shape}' key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len).expand( -1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len) if attn_mask is None: attn_mask = key_padding_mask elif attn_mask.dtype == torch.bool: attn_mask = attn_mask.logical_or(key_padding_mask) else: attn_mask = attn_mask.masked_fill(key_padding_mask, float('-inf')) if attn_mask is not None and attn_mask.dtype == torch.bool: new_attn_mask = torch.zeros_like(attn_mask, dtype=torch.float) new_attn_mask.masked_fill_(attn_mask, float('-inf')) attn_mask = new_attn_mask if not training: dropout_p = 0.0 attn_output, attn_output_weights = scale_dot_attention(q, k, v, attn_mask, dropout_p) attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn_output = nn.functional.linear(attn_output, out_proj_weight, out_proj_bias) if need_weights: attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len) return attn_output, attn_output_weights.sum(dim=1) / num_heads else: return attn_output, None class MultiheadAttention(nn.Module): def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True, kdim= None, vdim=None, batch_first=False) ->None: super(MultiheadAttention, self).__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self._qkv_same_embed_dim = (self.kdim == self.embed_dim and self. vdim == self.embed_dim) self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads' if self._qkv_same_embed_dim is False: self.q_proj_weight = Parameter(torch.empty((embed_dim, embed_dim))) self.k_proj_weight = Parameter(torch.empty((embed_dim, self.kdim))) self.v_proj_weight = Parameter(torch.empty((embed_dim, self.vdim))) self.register_parameter('in_proj_weight', None) else: self.in_proj_weight = Parameter(torch.empty((3 * embed_dim, embed_dim))) self.register_parameter('q_proj_weight', None) self.register_parameter('k_proj_weight', None) self.register_parameter('v_proj_weight', None) if bias: self.in_proj_bias = Parameter(torch.empty(3 * embed_dim)) else: self.register_parameter('in_proj_bias', None) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self._reset_parameters() def _reset_parameters(self): if self._qkv_same_embed_dim: xavier_uniform_(self.in_proj_weight) else: xavier_uniform_(self.q_proj_weight) xavier_uniform_(self.k_proj_weight) xavier_uniform_(self.v_proj_weight) if self.in_proj_bias is not None: constant_(self.in_proj_bias, 0.0) constant_(self.out_proj.bias, 0.0) def forward(self, query: 'Tensor', key: 'Tensor', value: 'Tensor', key_padding_mask: 'Optional[Tensor]'=None, need_weights: 'bool'= True, attn_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor, Optional[ Tensor]]: if self.batch_first: query, key, value = [x.transpose(1, 0) for x in (query, key, value) ] if not self._qkv_same_embed_dim: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask, use_separate_proj_weight=True, q_proj_weight= self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight) else: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.dropout, self.out_proj.weight, self .out_proj.bias, training=self.training, key_padding_mask= key_padding_mask, need_weights=need_weights, attn_mask= attn_mask) if self.batch_first: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class TransformerDecoderLayerNew(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=F.relu, layer_norm_eps=1e-05, batch_first=False) ->None: super(TransformerDecoderLayerNew, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout, batch_first=batch_first) self.multihead_attn = MultiheadAttention(d_model, nhead, dropout= dropout, batch_first=batch_first) 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, eps=layer_norm_eps) self.norm2 = nn.LayerNorm(d_model, eps=layer_norm_eps) self.norm3 = nn.LayerNorm(d_model, eps=layer_norm_eps) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout) self.activation = activation def forward(self, input_0, input_1): primals_1 = self.self_attn.in_proj_weight primals_2 = self.self_attn.in_proj_bias primals_3 = self.self_attn.out_proj.weight primals_4 = self.self_attn.out_proj.bias primals_8 = self.multihead_attn.in_proj_weight primals_9 = self.multihead_attn.in_proj_bias primals_10 = self.multihead_attn.out_proj.weight primals_6 = self.multihead_attn.out_proj.bias primals_15 = self.linear1.weight primals_16 = self.linear1.bias primals_17 = self.linear2.weight primals_7 = self.linear2.bias primals_11 = self.norm1.weight primals_13 = self.norm1.bias primals_14 = self.norm2.weight primals_18 = self.norm2.bias primals_19 = self.norm3.weight primals_20 = self.norm3.bias primals_5 = input_0 primals_12 = 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, primals_15, primals_16, primals_17, primals_18, primals_19, primals_20]) return output[0]
Treedy2020/TransNet
TransformerDecoderLayer
false
18,053
[ "MIT" ]
4
dd0e43e1931153baea4e5fe8cb31dc5ff0cb7b09
https://github.com/Treedy2020/TransNet/tree/dd0e43e1931153baea4e5fe8cb31dc5ff0cb7b09
distLinear
import torch import torch.nn as nn from torch.nn.utils.weight_norm import WeightNorm import torch.utils.data class distLinear(nn.Module): def __init__(self, indim, outdim): super(distLinear, self).__init__() self.L = nn.Linear(indim, outdim, bias=False) self.class_wise_learnable_norm = False if self.class_wise_learnable_norm: WeightNorm.apply(self.L, 'weight', dim=0) if outdim <= 200: self.scale_factor = 2 else: self.scale_factor = 10 def forward(self, x): x_norm = torch.norm(x, p=2, dim=1).unsqueeze(1).expand_as(x) x_normalized = x.div(x_norm + 1e-05) if not self.class_wise_learnable_norm: L_norm = torch.norm(self.L.weight.data, p=2, dim=1).unsqueeze(1 ).expand_as(self.L.weight.data) self.L.weight.data = self.L.weight.data.div(L_norm + 1e-05) cos_dist = self.L(x_normalized) scores = self.scale_factor * cos_dist return scores def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'indim': 4, 'outdim': 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.utils.weight_norm import WeightNorm 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_add_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1e-05 tmp14 = tmp12 + tmp13 tmp15 = tmp0 / tmp14 tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_poi_fused_add_div_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') 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') 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 = tmp0 / tmp14 tl.store(out_ptr0 + x3, tmp15, xmask) @triton.jit def triton_poi_fused_mul_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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 2.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, 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), (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_add_div_0[grid(16)](primals_2, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_div_1[grid(256)](primals_1, buf1, 256, XBLOCK= 256, num_warps=4, num_stages=1) del primals_1 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), out=buf2) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_2[grid(256)](buf2, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) buf4 = torch.ops.aten.set_.source_Tensor(primals_2, buf0) assert_size_stride(buf4, (4, 4), (4, 1)) del buf2 del primals_2 return buf3, reinterpret_tensor(buf1, (64, 4), (4, 1), 0) class distLinearNew(nn.Module): def __init__(self, indim, outdim): super(distLinearNew, self).__init__() self.L = nn.Linear(indim, outdim, bias=False) self.class_wise_learnable_norm = False if self.class_wise_learnable_norm: WeightNorm.apply(self.L, 'weight', dim=0) if outdim <= 200: self.scale_factor = 2 else: self.scale_factor = 10 def forward(self, input_0): primals_2 = self.L.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
VisionLearningGroup/CDS
distLinear
false
18,054
[ "MIT" ]
7
5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
https://github.com/VisionLearningGroup/CDS/tree/5b3644c286f19f76acdc03c6f6021a6f6e4ec4fc
BertAttention
from _paritybench_helpers import _mock_config import math import torch import torch.nn as nn class BertLayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): super(BertLayerNorm, self).__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = eps def forward(self, x): u = x.mean(-1, keepdim=True) s = (x - u).pow(2).mean(-1, keepdim=True) x = (x - u) / torch.sqrt(s + self.variance_epsilon) return self.weight * x + self.bias class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( 'The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config. num_attention_heads) self.all_head_size = (self.num_attention_heads * self. attention_head_size) self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self. attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self. attention_head_size) attention_scores = attention_scores + attention_mask attention_probs = nn.Softmax(dim=-1)(attention_scores) attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self. all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer, attention_probs class BertSelfOutput(nn.Module): def __init__(self, config): super(BertSelfOutput, self).__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttention(nn.Module): def __init__(self, config): super(BertAttention, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def forward(self, input_tensor, attention_mask): self_output, attn = self.self(input_tensor, attention_mask) attention_output = self.output(self_output, input_tensor) return attention_output, attn def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(hidden_size=4, num_attention_heads= 4, attention_probs_dropout_prob=0.5, hidden_dropout_prob=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 import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import 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_clone_0(in_ptr0, in_ptr1, 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') tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask) @triton.jit def triton_poi_fused__softmax_add_div_1(in_ptr0, in_ptr1, 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 x0 = xindex % 16 tmp0 = tl.load(in_ptr0 + 4 * x2, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (1 + 4 * x2), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr0 + (2 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp15 = tl.load(in_ptr0 + (3 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp17 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp5 * tmp1 tmp8 = tmp6 + tmp7 tmp9 = triton_helpers.maximum(tmp4, tmp8) tmp11 = tmp10 * tmp1 tmp13 = tmp11 + tmp12 tmp14 = triton_helpers.maximum(tmp9, tmp13) tmp16 = tmp15 * tmp1 tmp18 = tmp16 + tmp17 tmp19 = triton_helpers.maximum(tmp14, tmp18) tmp20 = tmp4 - tmp19 tmp21 = tl_math.exp(tmp20) tmp22 = tmp8 - tmp19 tmp23 = tl_math.exp(tmp22) tmp24 = tmp21 + tmp23 tmp25 = tmp13 - tmp19 tmp26 = tl_math.exp(tmp25) tmp27 = tmp24 + tmp26 tmp28 = tmp18 - tmp19 tmp29 = tl_math.exp(tmp28) tmp30 = tmp27 + tmp29 tl.store(out_ptr0 + x2, tmp19, xmask) tl.store(out_ptr1 + x2, tmp30, xmask) @triton.jit def triton_poi_fused__softmax_add_div_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, 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 % 64 x5 = xindex // 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp3 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last') tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 - tmp5 tmp7 = tl_math.exp(tmp6) tmp9 = tmp7 / tmp8 tl.store(in_out_ptr0 + x3, tmp9, xmask) @triton.jit def triton_poi_fused_clone_3(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_mean_pow_sub_4(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_div_mean_mul_sqrt_sub_5(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 x0 = xindex % 4 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask) tmp2 = tl.load(in_ptr2 + x2, xmask) tmp4 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 - tmp4 tmp7 = 1e-12 tmp8 = tmp6 + tmp7 tmp9 = libdevice.sqrt(tmp8) tmp10 = tmp5 / tmp9 tmp11 = tmp0 * tmp10 tmp13 = tmp11 + tmp12 tl.store(out_ptr0 + x2, tmp13, 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 ) = 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), (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, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_9, (4, 4), (4, 1)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (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_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) del primals_4 buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2) del primals_6 buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del primals_2 buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf0 triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del primals_5 buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5) buf6 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 64), 0) del buf1 buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32) triton_poi_fused__softmax_add_div_1[grid(64)](buf5, primals_8, buf6, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1) buf8 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf5 triton_poi_fused__softmax_add_div_2[grid(256)](buf8, primals_8, buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_8 buf9 = reinterpret_tensor(buf7, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf7 triton_poi_fused_clone_0[grid(16, 4)](buf2, primals_7, buf9, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del primals_7 buf10 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0) del buf2 extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), out=buf10) buf11 = reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf6 triton_poi_fused_clone_3[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf12 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0) del buf10 extern_kernels.addmm(primals_10, reinterpret_tensor(buf11, (16, 4), (4, 1), 0), reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf12) del primals_10 buf13 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf14 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) triton_poi_fused_add_mean_pow_sub_4[grid(16)](buf12, primals_3, buf13, buf14, 16, XBLOCK=16, num_warps=1, num_stages=1) buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_div_mean_mul_sqrt_sub_5[grid(64)](primals_11, buf12, primals_3, buf13, buf14, primals_12, buf15, 64, XBLOCK= 64, num_warps=1, num_stages=1) del buf13 del buf14 del primals_12 return buf15, buf8, primals_3, primals_11, buf8, reinterpret_tensor(buf11, (16, 4), (4, 1), 0), buf12, primals_9, reinterpret_tensor(buf9, (16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0) class BertLayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): super(BertLayerNorm, self).__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = eps def forward(self, x): u = x.mean(-1, keepdim=True) s = (x - u).pow(2).mean(-1, keepdim=True) x = (x - u) / torch.sqrt(s + self.variance_epsilon) return self.weight * x + self.bias class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( 'The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config. num_attention_heads) self.all_head_size = (self.num_attention_heads * self. attention_head_size) self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self. attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self. attention_head_size) attention_scores = attention_scores + attention_mask attention_probs = nn.Softmax(dim=-1)(attention_scores) attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self. all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer, attention_probs class BertSelfOutput(nn.Module): def __init__(self, config): super(BertSelfOutput, self).__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = BertLayerNorm(config.hidden_size, eps=1e-12) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, input_tensor): hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.LayerNorm(hidden_states + input_tensor) return hidden_states class BertAttentionNew(nn.Module): def __init__(self, config): super(BertAttentionNew, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def forward(self, input_0, input_1): primals_1 = self.self.query.weight primals_2 = self.self.query.bias primals_4 = self.self.key.weight primals_5 = self.self.key.bias primals_6 = self.self.value.weight primals_7 = self.self.value.bias primals_9 = self.output.dense.weight primals_10 = self.output.dense.bias primals_11 = self.output.LayerNorm.weight primals_12 = self.output.LayerNorm.bias primals_3 = input_0 primals_8 = 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]) return output[0], output[1]
Vitvicky/mrc-for-flat-nested-ner
BertAttention
false
18,055
[ "Apache-2.0" ]
9
37099625e3002c334884fe982a6476e2c783da63
https://github.com/Vitvicky/mrc-for-flat-nested-ner/tree/37099625e3002c334884fe982a6476e2c783da63
ContrastiveLoss
import torch import torch.nn.functional as F class ContrastiveLoss(torch.nn.Module): def __init__(self, margin=2.0): super(ContrastiveLoss, self).__init__() self.margin = margin def forward(self, output1, output2, label): euclidean_distance = F.pairwise_distance(output1, output2) loss_contrastive = torch.mean((1 - label) * torch.pow( euclidean_distance, 2) + label * torch.pow(torch.clamp(self. margin - euclidean_distance, min=0.0), 2)) return loss_contrastive def get_inputs(): return [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 libdevice 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_norm_sub_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 tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp18 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 - tmp1 tmp3 = 1e-06 tmp4 = tmp2 + tmp3 tmp5 = tmp4 * tmp4 tmp8 = tmp6 - tmp7 tmp9 = tmp8 + tmp3 tmp10 = tmp9 * tmp9 tmp11 = tmp5 + tmp10 tmp14 = tmp12 - tmp13 tmp15 = tmp14 + tmp3 tmp16 = tmp15 * tmp15 tmp17 = tmp11 + tmp16 tmp20 = tmp18 - tmp19 tmp21 = tmp20 + tmp3 tmp22 = tmp21 * tmp21 tmp23 = tmp17 + tmp22 tmp24 = libdevice.sqrt(tmp23) tl.store(out_ptr0 + x0, tmp24, xmask) @triton.jit def triton_per_fused_add_clamp_mean_mul_pow_rsub_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) r2 = rindex r0 = rindex % 64 tmp0 = tl.load(in_ptr0 + r2, None) tmp3 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last') tmp1 = 1.0 tmp2 = tmp1 - tmp0 tmp4 = tmp3 * tmp3 tmp5 = tmp2 * tmp4 tmp6 = 2.0 tmp7 = tmp6 - tmp3 tmp8 = 0.0 tmp9 = triton_helpers.maximum(tmp7, tmp8) tmp10 = tmp9 * tmp9 tmp11 = tmp0 * tmp10 tmp12 = tmp5 + tmp11 tmp13 = tl.broadcast_to(tmp12, [RBLOCK]) tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0)) tmp16 = 256.0 tmp17 = tmp15 / tmp16 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None) def call(args): arg0_1, arg1_1, arg2_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)) 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_add_norm_sub_0[grid(64)](arg1_1, arg0_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del arg0_1 del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused_add_clamp_mean_mul_pow_rsub_1[grid(1)](buf2, arg2_1, buf0, 1, 256, num_warps=2, num_stages=1) del arg2_1 del buf0 return buf2, class ContrastiveLossNew(torch.nn.Module): def __init__(self, margin=2.0): super(ContrastiveLossNew, self).__init__() self.margin = margin def forward(self, input_0, input_1, input_2): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
WLYLab/PepFormer
ContrastiveLoss
false
18,056
[ "MIT" ]
6
9bac4544dc88bcd66e975a6714a264dcc9c55304
https://github.com/WLYLab/PepFormer/tree/9bac4544dc88bcd66e975a6714a264dcc9c55304
WeightNet
import torch import torch.nn as nn class WeightNet(nn.Module): """WeightNet in Temporal interlace module. The WeightNet consists of two parts: one convolution layer and a sigmoid function. Following the convolution layer, the sigmoid function and rescale module can scale our output to the range (0, 2). Here we set the initial bias of the convolution layer to 0, and the final initial output will be 1.0. Args: in_channels (int): Channel num of input features. groups (int): Number of groups for fc layer outputs. """ def __init__(self, in_channels, groups): super().__init__() self.sigmoid = nn.Sigmoid() self.groups = groups self.conv = nn.Conv1d(in_channels, groups, 3, padding=1) self.init_weights() def init_weights(self): """Initiate the parameters either from existing checkpoint or from scratch.""" self.conv.bias.data[...] = 0 def forward(self, x): """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The output of the module. """ n, _, t = x.shape x = self.conv(x) x = x.view(n, self.groups, t) x = x.permute(0, 2, 1) x = 2 * self.sigmoid(x) return x def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'groups': 1}]
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_mul_sigmoid_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 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) tmp5 = 2.0 tmp6 = tmp4 * tmp5 tl.store(in_out_ptr0 + x0, tmp3, xmask) tl.store(out_ptr0 + x0, tmp6, 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, (1, 4, 3), (12, 3, 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,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf0, (4, 1, 4), (4, 4, 1)) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_convolution_mul_sigmoid_0[grid(16)](buf1, primals_3, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 return buf2, primals_1, primals_2, buf1 class WeightNetNew(nn.Module): """WeightNet in Temporal interlace module. The WeightNet consists of two parts: one convolution layer and a sigmoid function. Following the convolution layer, the sigmoid function and rescale module can scale our output to the range (0, 2). Here we set the initial bias of the convolution layer to 0, and the final initial output will be 1.0. Args: in_channels (int): Channel num of input features. groups (int): Number of groups for fc layer outputs. """ def __init__(self, in_channels, groups): super().__init__() self.sigmoid = nn.Sigmoid() self.groups = groups self.conv = nn.Conv1d(in_channels, groups, 3, padding=1) self.init_weights() def init_weights(self): """Initiate the parameters either from existing checkpoint or from scratch.""" self.conv.bias.data[...] = 0 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]
Viditagarwal7479/Video-Swin-Transformer
WeightNet
false
18,057
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
PatchMerging
import torch import torch.nn.functional as F import torch.nn as nn class PatchMerging(nn.Module): """ Patch Merging Layer Args: dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, x): """ Forward function. Args: x: Input feature, tensor size (B, D, H, W, C). """ _B, _D, H, W, _C = x.shape pad_input = H % 2 == 1 or W % 2 == 1 if pad_input: x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) x0 = x[:, :, 0::2, 0::2, :] x1 = x[:, :, 1::2, 0::2, :] x2 = x[:, :, 0::2, 1::2, :] x3 = x[:, :, 1::2, 1::2, :] x = torch.cat([x0, x1, x2, x3], -1) x = self.norm(x) x = self.reduction(x) return x def get_inputs(): return [torch.rand([4, 4, 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 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_cat_native_layer_norm_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr ): xnumel = 64 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 x0 = xindex % 2 x1 = xindex // 2 x3 = xindex tmp46 = tl.load(in_ptr1 + r2, None, eviction_policy='evict_last') tmp48 = tl.load(in_ptr2 + r2, None, eviction_policy='evict_last') tmp0 = r2 tl.full([1, 1], 0, tl.int64) tmp3 = tl.full([1, 1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (8 * x0 + 32 * x1 + r2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1, 1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr0 + (16 + 8 * x0 + 32 * x1 + (-4 + r2)), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1, 1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (4 + 8 * x0 + 32 * x1 + (-8 + r2)), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1, 1], 16, tl.int64) tmp19 = tl.load(in_ptr0 + (20 + 8 * x0 + 32 * x1 + (-12 + r2)), 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) tmp23 = tl.broadcast_to(tmp22, [XBLOCK, RBLOCK]) tl.where(xmask, tmp23, 0) tmp26 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK]) tmp28 = tl.where(xmask, tmp26, 0) tmp29 = tl.sum(tmp28, 1)[:, None] tmp30 = tl.full([XBLOCK, 1], 16, tl.int32) tmp31 = tmp30.to(tl.float32) tmp32 = tmp29 / tmp31 tmp33 = tmp23 - tmp32 tmp34 = tmp33 * tmp33 tmp35 = tl.broadcast_to(tmp34, [XBLOCK, RBLOCK]) tmp37 = tl.where(xmask, tmp35, 0) tmp38 = tl.sum(tmp37, 1)[:, None] tmp39 = 16.0 tmp40 = tmp38 / tmp39 tmp41 = 1e-05 tmp42 = tmp40 + tmp41 tmp43 = libdevice.rsqrt(tmp42) tmp44 = tmp22 - tmp32 tmp45 = tmp44 * tmp43 tmp47 = tmp45 * tmp46 tmp49 = tmp47 + tmp48 tl.store(out_ptr0 + (r2 + 16 * x3), tmp22, xmask) tl.debug_barrier() tl.store(in_out_ptr0 + x3, tmp43, xmask) tl.store(out_ptr2 + (r2 + 16 * x3), tmp49, xmask) tl.store(out_ptr1 + x3, tmp32, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1)) assert_size_stride(primals_2, (16,), (1,)) assert_size_stride(primals_3, (16,), (1,)) assert_size_stride(primals_4, (8, 16), (16, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 2, 2, 16), (256, 64, 32, 16, 1), torch.float32) buf1 = empty_strided_cuda((4, 4, 2, 2, 1), (16, 4, 2, 1, 1), torch. float32) buf2 = empty_strided_cuda((4, 4, 2, 2, 1), (16, 4, 2, 1, 64), torch .float32) buf4 = reinterpret_tensor(buf2, (4, 4, 2, 2, 1), (16, 4, 2, 1, 1), 0) del buf2 buf5 = empty_strided_cuda((4, 4, 2, 2, 16), (256, 64, 32, 16, 1), torch.float32) get_raw_stream(0) triton_per_fused_cat_native_layer_norm_0[grid(64)](buf4, primals_1, primals_2, primals_3, buf0, buf1, buf5, 64, 16, XBLOCK=8, num_warps=2, num_stages=1) del primals_1 del primals_2 del primals_3 buf6 = empty_strided_cuda((64, 8), (8, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (64, 16), (16, 1), 0), reinterpret_tensor(primals_4, (16, 8), (1, 16), 0), out=buf6) return reinterpret_tensor(buf6, (4, 4, 2, 2, 8), (128, 32, 16, 8, 1), 0 ), buf0, buf1, buf4, reinterpret_tensor(buf5, (64, 16), (16, 1), 0 ), primals_4 class PatchMergingNew(nn.Module): """ Patch Merging Layer Args: dim (int): Number of input channels. norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__(self, dim, norm_layer=nn.LayerNorm): super().__init__() self.dim = dim self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) self.norm = norm_layer(4 * dim) def forward(self, input_0): primals_4 = self.reduction.weight primals_2 = self.norm.weight primals_3 = self.norm.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
Viditagarwal7479/Video-Swin-Transformer
PatchMerging
false
18,058
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
TripletLoss
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import * from torch.optim.lr_scheduler import * def _batch_hard(mat_distance, mat_similarity, indice=False): sorted_mat_distance, positive_indices = torch.sort(mat_distance + - 9999999.0 * (1 - mat_similarity), dim=1, descending=True) hard_p = sorted_mat_distance[:, 0] hard_p_indice = positive_indices[:, 0] sorted_mat_distance, negative_indices = torch.sort(mat_distance + 9999999.0 * mat_similarity, dim=1, descending=False) hard_n = sorted_mat_distance[:, 0] hard_n_indice = negative_indices[:, 0] if indice: return hard_p, hard_n, hard_p_indice, hard_n_indice return hard_p, hard_n def euclidean_dist(x, y): m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t() dist = xx + yy dist.addmm_(1, -2, x, y.t()) dist = dist.clamp(min=1e-12).sqrt() return dist class TripletLoss(nn.Module): """ Compute Triplet loss augmented with Batch Hard Details can be seen in 'In defense of the Triplet Loss for Person Re-Identification' """ def __init__(self, margin, normalize_feature=False): super(TripletLoss, self).__init__() self.margin = margin self.normalize_feature = normalize_feature self.margin_loss = nn.MarginRankingLoss(margin=margin) def forward(self, emb, label): if self.normalize_feature: emb = F.normalize(emb) mat_dist = euclidean_dist(emb, emb) assert mat_dist.size(0) == mat_dist.size(1) N = mat_dist.size(0) mat_sim = label.expand(N, N).eq(label.expand(N, N).t()).float() dist_ap, dist_an = _batch_hard(mat_dist, mat_sim) assert dist_an.size(0) == dist_ap.size(0) y = torch.ones_like(dist_ap) loss = self.margin_loss(dist_an, dist_ap, y) prec = (dist_an.data > dist_ap.data).sum() * 1.0 / y.size(0) return loss, prec def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'margin': 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 from torch.nn import * from torch.optim.lr_scheduler 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_per_fused__to_copy_add_clamp_eq_mul_rsub_sort_sqrt_0(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr ): xnumel = 4 RBLOCK: tl.constexpr = 4 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 + 4 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr0 + 4 * r1, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr0 + (1 + 4 * r1), None, eviction_policy='evict_last') tmp17 = tl.load(in_ptr0 + (2 + 4 * r1), None, eviction_policy='evict_last') tmp20 = tl.load(in_ptr0 + (3 + 4 * r1), None, eviction_policy='evict_last') tmp28 = tl.load(in_ptr1 + (r1 + 4 * x0), xmask, other=0.0) tmp29 = tl.load(in_ptr1 + (x0 + 4 * r1), xmask, other=0.0) tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp13 = tmp12 * tmp12 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp21 = tmp20 * tmp20 tmp22 = tmp19 + tmp21 tmp23 = tmp11 + tmp22 tmp24 = tmp0 + tmp23 tmp25 = 1e-12 tmp26 = triton_helpers.maximum(tmp24, tmp25) tmp27 = libdevice.sqrt(tmp26) tmp30 = tmp28 == tmp29 tmp31 = tmp30.to(tl.float32) tmp32 = 1.0 tmp33 = tmp32 - tmp31 tmp34 = -9999999.0 tmp35 = tmp33 * tmp34 tmp36 = tmp27 + tmp35 tmp37 = r1 tmp38 = tmp37.to(tl.int16) tmp39 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK]) tmp40 = tl.broadcast_to(tmp38, [XBLOCK, RBLOCK]) tmp41, _tmp42 = triton_helpers.sort_with_index(tmp39, tmp40, None, 1, stable=False, descending=True) tmp43 = 9999999.0 tmp44 = tmp31 * tmp43 tmp45 = tmp27 + tmp44 tmp46 = tl.broadcast_to(tmp45, [XBLOCK, RBLOCK]) tmp47, _tmp48 = triton_helpers.sort_with_index(tmp46, tmp40, None, 1, stable=False, descending=False) tl.store(in_out_ptr0 + (r1 + 4 * x0), tmp24, xmask) tl.store(out_ptr0 + (r1 + 4 * x0), tmp41, xmask) tl.store(out_ptr1 + (r1 + 4 * x0), tmp47, xmask) @triton.jit def triton_per_fused_add_clamp_min_div_gt_mean_mul_neg_sub_sum_1(in_out_ptr0, in_ptr0, in_ptr1, out_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') tmp2 = tmp0 - tmp1 tmp3 = -1.0 tmp4 = tmp3 * tmp2 tmp5 = 4.0 tmp6 = tmp4 + tmp5 tmp7 = 0.0 tmp8 = triton_helpers.maximum(tmp6, tmp7) tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK]) tmp11 = tl.sum(tmp9, 1)[:, None] tmp12 = tmp0 > tmp1 tmp13 = tmp12.to(tl.int64) tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK]) tmp16 = tl.sum(tmp14, 1)[:, None] tmp17 = tmp16.to(tl.float32) tmp18 = 1.0 tmp19 = tmp17 * tmp18 tmp20 = 0.25 tmp21 = tmp19 * tmp20 tmp22 = tmp11 / tmp5 tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp21, None) tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp22, 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) extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4), 0), out=buf0) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_per_fused__to_copy_add_clamp_eq_mul_rsub_sort_sqrt_0[grid(4)]( buf1, arg0_1, arg1_1, buf2, buf4, 4, 4, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del buf1 buf6 = empty_strided_cuda((), (), torch.float32) buf9 = empty_strided_cuda((), (), torch.float32) buf8 = buf6 del buf6 triton_per_fused_add_clamp_min_div_gt_mean_mul_neg_sub_sum_1[grid(1)]( buf8, buf4, buf2, buf9, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf2 del buf4 return buf8, buf9 def _batch_hard(mat_distance, mat_similarity, indice=False): sorted_mat_distance, positive_indices = torch.sort(mat_distance + - 9999999.0 * (1 - mat_similarity), dim=1, descending=True) hard_p = sorted_mat_distance[:, 0] hard_p_indice = positive_indices[:, 0] sorted_mat_distance, negative_indices = torch.sort(mat_distance + 9999999.0 * mat_similarity, dim=1, descending=False) hard_n = sorted_mat_distance[:, 0] hard_n_indice = negative_indices[:, 0] if indice: return hard_p, hard_n, hard_p_indice, hard_n_indice return hard_p, hard_n def euclidean_dist(x, y): m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t() dist = xx + yy dist.addmm_(1, -2, x, y.t()) dist = dist.clamp(min=1e-12).sqrt() return dist class TripletLossNew(nn.Module): """ Compute Triplet loss augmented with Batch Hard Details can be seen in 'In defense of the Triplet Loss for Person Re-Identification' """ def __init__(self, margin, normalize_feature=False): super(TripletLossNew, self).__init__() self.margin = margin self.normalize_feature = normalize_feature self.margin_loss = nn.MarginRankingLoss(margin=margin) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0], output[1]
WangWenhao0716/DomainMix
TripletLoss
false
18,059
[ "MIT" ]
8
2d9a20c1536177d1d71fbdc99f714eaf98fdfe92
https://github.com/WangWenhao0716/DomainMix/tree/2d9a20c1536177d1d71fbdc99f714eaf98fdfe92
PatchEmbed3D
import torch import torch.nn.functional as F import torch.nn as nn class PatchEmbed3D(nn.Module): """ Video to Patch Embedding. Args: patch_size (int): Patch token size. Default: (2,4,4). in_chans (int): Number of input video channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """ def __init__(self, patch_size=(2, 4, 4), in_chans=3, embed_dim=96, norm_layer=None): super().__init__() self.patch_size = patch_size self.in_chans = in_chans self.embed_dim = embed_dim self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, x): """Forward function.""" _, _, D, H, W = x.size() if W % self.patch_size[2] != 0: x = F.pad(x, (0, self.patch_size[2] - W % self.patch_size[2])) if H % self.patch_size[1] != 0: x = F.pad(x, (0, 0, 0, self.patch_size[1] - H % self.patch_size[1]) ) if D % self.patch_size[0] != 0: x = F.pad(x, (0, 0, 0, 0, 0, self.patch_size[0] - D % self. patch_size[0])) x = self.proj(x) if self.norm is not None: D, Wh, Ww = x.size(2), x.size(3), x.size(4) x = x.flatten(2).transpose(1, 2) x = self.norm(x) x = x.transpose(1, 2).view(-1, self.embed_dim, D, Wh, Ww) return x def get_inputs(): return [torch.rand([4, 3, 64, 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 @triton.jit def triton_poi_fused_convolution_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 // 8192 % 96 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) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 3, 64, 64, 64), (786432, 262144, 4096, 64, 1)) assert_size_stride(primals_2, (96, 3, 2, 4, 4), (96, 32, 16, 4, 1)) assert_size_stride(primals_3, (96,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(2, 4, 4), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 96, 32, 16, 16), (786432, 8192, 256, 16, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(3145728)](buf1, primals_3, 3145728, XBLOCK=1024, num_warps=4, num_stages=1) del primals_3 return buf1, primals_1, primals_2 class PatchEmbed3DNew(nn.Module): """ Video to Patch Embedding. Args: patch_size (int): Patch token size. Default: (2,4,4). in_chans (int): Number of input video channels. Default: 3. embed_dim (int): Number of linear projection output channels. Default: 96. norm_layer (nn.Module, optional): Normalization layer. Default: None """ def __init__(self, patch_size=(2, 4, 4), in_chans=3, embed_dim=96, norm_layer=None): super().__init__() self.patch_size = patch_size self.in_chans = in_chans self.embed_dim = embed_dim self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) if norm_layer is not None: self.norm = norm_layer(embed_dim) else: self.norm = None def forward(self, input_0): primals_2 = self.proj.weight primals_3 = self.proj.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
Viditagarwal7479/Video-Swin-Transformer
PatchEmbed3D
false
18,060
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
RobertaClassificationHead
from _paritybench_helpers import _mock_config import torch import torch.nn as nn class RobertaClassificationHead(nn.Module): """Head for sentence-level classification tasks.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) classifier_dropout = (config.classifier_dropout if config. classifier_dropout is not None else config.hidden_dropout_prob) self.dropout = nn.Dropout(classifier_dropout) self.out_proj = nn.Linear(config.hidden_size, config.num_labels) def forward(self, x, **kwargs): x = self.dropout(x) x = self.dense(x) x = torch.tanh(x) x = self.dropout(x) x = self.out_proj(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(hidden_size=4, classifier_dropout= 0.5, 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_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 = 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 = 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.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 return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), buf1, primals_4 class RobertaClassificationHeadNew(nn.Module): """Head for sentence-level classification tasks.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) classifier_dropout = (config.classifier_dropout if config. classifier_dropout is not None else config.hidden_dropout_prob) self.dropout = nn.Dropout(classifier_dropout) self.out_proj = nn.Linear(config.hidden_size, config.num_labels) def forward(self, input_0): primals_2 = self.dense.weight primals_3 = self.dense.bias primals_4 = self.out_proj.weight primals_5 = self.out_proj.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
Amber-Chaeeunk/Open-Domain-Question-Answering
RobertaClassificationHead
false
18,061
[ "MIT" ]
5
725e369a4409c54bf11bcfb9db53865d8fc1f935
https://github.com/Amber-Chaeeunk/Open-Domain-Question-Answering/tree/725e369a4409c54bf11bcfb9db53865d8fc1f935
TemporallyBatchedAdditiveAttention
import torch import torch.nn as nn import torch.nn.functional as F class AdditiveAttention(nn.Module): def __init__(self, encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim=None): super(AdditiveAttention, self).__init__() if internal_dim is None: internal_dim = int((encoder_hidden_state_dim + decoder_hidden_state_dim) / 2) self.w1 = nn.Linear(encoder_hidden_state_dim, internal_dim, bias=False) self.w2 = nn.Linear(decoder_hidden_state_dim, internal_dim, bias=False) self.v = nn.Linear(internal_dim, 1, bias=False) def score(self, encoder_state, decoder_state): return self.v(torch.tanh(self.w1(encoder_state) + self.w2( decoder_state))) def forward(self, encoder_states, decoder_state): score_vec = torch.cat([self.score(encoder_states[:, i], decoder_state) for i in range(encoder_states.shape[1])], dim=1) attention_probs = torch.unsqueeze(F.softmax(score_vec, dim=1), dim=2) final_context_vec = torch.sum(attention_probs * encoder_states, dim=1) return final_context_vec, attention_probs class TemporallyBatchedAdditiveAttention(AdditiveAttention): def __init__(self, encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim=None): super(TemporallyBatchedAdditiveAttention, self).__init__( encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim) def score(self, encoder_state, decoder_state): return self.v(torch.tanh(self.w1(encoder_state) + torch.unsqueeze( self.w2(decoder_state), dim=1))) def forward(self, encoder_states, decoder_state): score_vec = self.score(encoder_states, decoder_state) attention_probs = F.softmax(score_vec, dim=1) final_context_vec = torch.sum(attention_probs * encoder_states, dim=1) return final_context_vec, torch.squeeze(torch.transpose( attention_probs, 1, 2), dim=3) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'encoder_hidden_state_dim': 4, 'decoder_hidden_state_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 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_add_tanh_0(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 % 256 x0 = xindex % 64 x2 = xindex // 256 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') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(out_ptr0 + x4, tmp3, 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) @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 x1 = xindex // 4 % 16 x2 = xindex // 64 x3 = xindex % 64 x4 = xindex tmp0 = tl.load(in_ptr0 + (x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (16 + x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr1 + (64 + x3), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (32 + x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp8 = tl.load(in_ptr1 + (128 + x3), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (48 + x1 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr1 + (192 + x3), 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 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_5, (1, 4), (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_2, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (64, 4), (4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1) del primals_3 buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_tanh_0[grid(1024)](buf0, buf1, buf2, 1024, XBLOCK=128, num_warps=4, num_stages=1) buf3 = reinterpret_tensor(buf1, (256, 1), (1, 1), 0) del buf1 extern_kernels.mm(reinterpret_tensor(buf2, (256, 4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 1), (1, 4), 0), out=buf3) buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4, 1), (64, 16, 4, 1, 256), 0 ) del buf0 triton_poi_fused__softmax_1[grid(256)](buf3, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4, 1), (64, 16, 4, 1, 1), 0) del buf3 triton_poi_fused__softmax_2[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_mul_sum_3[grid(256)](buf5, primals_2, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf6, reinterpret_tensor(buf5, (4, 4, 4, 4, 1), (64, 4, 16, 1, 1), 0 ), primals_2, reinterpret_tensor(primals_4, (64, 4), (4, 1), 0 ), buf2, buf5, primals_5 class AdditiveAttention(nn.Module): def __init__(self, encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim=None): super(AdditiveAttention, self).__init__() if internal_dim is None: internal_dim = int((encoder_hidden_state_dim + decoder_hidden_state_dim) / 2) self.w1 = nn.Linear(encoder_hidden_state_dim, internal_dim, bias=False) self.w2 = nn.Linear(decoder_hidden_state_dim, internal_dim, bias=False) self.v = nn.Linear(internal_dim, 1, bias=False) def score(self, encoder_state, decoder_state): return self.v(torch.tanh(self.w1(encoder_state) + self.w2( decoder_state))) def forward(self, encoder_states, decoder_state): score_vec = torch.cat([self.score(encoder_states[:, i], decoder_state) for i in range(encoder_states.shape[1])], dim=1) attention_probs = torch.unsqueeze(F.softmax(score_vec, dim=1), dim=2) final_context_vec = torch.sum(attention_probs * encoder_states, dim=1) return final_context_vec, attention_probs class TemporallyBatchedAdditiveAttentionNew(AdditiveAttention): def __init__(self, encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim=None): super(TemporallyBatchedAdditiveAttentionNew, self).__init__( encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim) def score(self, encoder_state, decoder_state): return self.v(torch.tanh(self.w1(encoder_state) + torch.unsqueeze( self.w2(decoder_state), dim=1))) def forward(self, input_0, input_1): primals_1 = self.w1.weight primals_3 = self.w2.weight primals_5 = self.v.weight primals_2 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1]
Vision-CAIR/HalentNet
TemporallyBatchedAdditiveAttention
false
18,062
[ "MIT" ]
4
dedef73c57c63aa580fc497fa42d512f4241a64b
https://github.com/Vision-CAIR/HalentNet/tree/dedef73c57c63aa580fc497fa42d512f4241a64b
FocalLoss
import torch import torch.nn as nn import torch.nn.functional as F class FocalLoss(nn.Module): def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2, reduction: 'str'='none'): """ Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py . Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples or -1 for ignore. Default = 0.25 gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. reduction: 'none' | 'mean' | 'sum' 'none': No reduction will be applied to the output. 'mean': The output will be averaged. 'sum': The output will be summed. Returns: Loss tensor with the reduction option applied. """ super().__init__() self.alpha = alpha self.gamma = gamma self.reduction = reduction def forward(self, inputs, targets): p = torch.sigmoid(inputs) ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction='none') p_t = p * targets + (1 - p) * (1 - targets) loss = ce_loss * (1 - p_t) ** self.gamma if self.alpha >= 0: alpha_t = self.alpha * targets + (1 - self.alpha) * (1 - targets) loss = alpha_t * loss return loss.mean() if self.reduction == 'mean' 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_poi_fused_add_binary_cross_entropy_with_logits_mul_pow_rsub_sigmoid_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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp8 = tl.load(in_ptr1 + x0, xmask) tmp1 = 0.25 tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp3 - tmp0 tmp5 = 0.75 tmp6 = tmp4 * tmp5 tmp7 = tmp2 + tmp6 tmp9 = tmp4 * tmp8 tmp10 = 0.0 tmp11 = triton_helpers.minimum(tmp10, tmp8) tmp12 = tl_math.abs(tmp8) tmp13 = -tmp12 tmp14 = tl_math.exp(tmp13) tmp15 = libdevice.log1p(tmp14) tmp16 = tmp11 - tmp15 tmp17 = tmp9 - tmp16 tmp18 = tl.sigmoid(tmp8) tmp19 = tmp18 * tmp0 tmp20 = tmp3 - tmp18 tmp21 = tmp20 * tmp4 tmp22 = tmp19 + tmp21 tmp23 = tmp3 - tmp22 tmp24 = tmp23 * tmp23 tmp25 = tmp17 * tmp24 tmp26 = tmp7 * tmp25 tl.store(out_ptr0 + x0, tmp26, xmask) 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_add_binary_cross_entropy_with_logits_mul_pow_rsub_sigmoid_0[ grid(256)](arg1_1, arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 del arg1_1 return buf0, class FocalLossNew(nn.Module): def __init__(self, alpha: 'float'=0.25, gamma: 'float'=2, reduction: 'str'='none'): """ Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py . Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). alpha: (optional) Weighting factor in range (0,1) to balance positive vs negative examples or -1 for ignore. Default = 0.25 gamma: Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples. reduction: 'none' | 'mean' | 'sum' 'none': No reduction will be applied to the output. 'mean': The output will be averaged. 'sum': The output will be summed. Returns: Loss tensor with the reduction option applied. """ super().__init__() self.alpha = alpha self.gamma = gamma self.reduction = reduction def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
VisualJoyce/ChengyuBERT
FocalLoss
false
18,063
[ "MIT" ]
8
605db3a4b3241dd4d02baa41a68bf23b5b00b36d
https://github.com/VisualJoyce/ChengyuBERT/tree/605db3a4b3241dd4d02baa41a68bf23b5b00b36d
BMNLoss
import torch import torch.nn.functional as F import torch.nn as nn def binary_logistic_regression_loss(reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-05): """Binary Logistic Regression Loss.""" label = label.view(-1) reg_score = reg_score.contiguous().view(-1) pmask = (label > threshold).float() num_positive = max(torch.sum(pmask), 1) num_entries = len(label) ratio = num_entries / num_positive ratio = min(max(ratio, ratio_range[0]), ratio_range[1]) coef_0 = 0.5 * ratio / (ratio - 1) coef_1 = 0.5 * ratio loss = coef_1 * pmask * torch.log(reg_score + eps) + coef_0 * (1.0 - pmask ) * torch.log(1.0 - reg_score + eps) loss = -torch.mean(loss) return loss class BMNLoss(nn.Module): """BMN Loss. From paper https://arxiv.org/abs/1907.09702, code https://github.com/JJBOY/BMN-Boundary-Matching-Network. It will calculate loss for BMN Model. This loss is a weighted sum of 1) temporal evaluation loss based on confidence score of start and end positions. 2) proposal evaluation regression loss based on confidence scores of candidate proposals. 3) proposal evaluation classification loss based on classification results of candidate proposals. """ @staticmethod def tem_loss(pred_start, pred_end, gt_start, gt_end): """Calculate Temporal Evaluation Module Loss. This function calculate the binary_logistic_regression_loss for start and end respectively and returns the sum of their losses. Args: pred_start (torch.Tensor): Predicted start score by BMN model. pred_end (torch.Tensor): Predicted end score by BMN model. gt_start (torch.Tensor): Groundtruth confidence score for start. gt_end (torch.Tensor): Groundtruth confidence score for end. Returns: torch.Tensor: Returned binary logistic loss. """ loss_start = binary_logistic_regression_loss(pred_start, gt_start) loss_end = binary_logistic_regression_loss(pred_end, gt_end) loss = loss_start + loss_end return loss @staticmethod def pem_reg_loss(pred_score, gt_iou_map, mask, high_temporal_iou_threshold=0.7, low_temporal_iou_threshold=0.3): """Calculate Proposal Evaluation Module Regression Loss. Args: pred_score (torch.Tensor): Predicted temporal_iou score by BMN. gt_iou_map (torch.Tensor): Groundtruth temporal_iou score. mask (torch.Tensor): Boundary-Matching mask. high_temporal_iou_threshold (float): Higher threshold of temporal_iou. Default: 0.7. low_temporal_iou_threshold (float): Higher threshold of temporal_iou. Default: 0.3. Returns: torch.Tensor: Proposal evalutaion regression loss. """ u_hmask = (gt_iou_map > high_temporal_iou_threshold).float() u_mmask = ((gt_iou_map <= high_temporal_iou_threshold) & ( gt_iou_map > low_temporal_iou_threshold)).float() u_lmask = ((gt_iou_map <= low_temporal_iou_threshold) & (gt_iou_map > 0.0)).float() u_lmask = u_lmask * mask num_h = torch.sum(u_hmask) num_m = torch.sum(u_mmask) num_l = torch.sum(u_lmask) r_m = num_h / num_m u_smmask = torch.rand_like(gt_iou_map) u_smmask = u_mmask * u_smmask u_smmask = (u_smmask > 1.0 - r_m).float() r_l = num_h / num_l u_slmask = torch.rand_like(gt_iou_map) u_slmask = u_lmask * u_slmask u_slmask = (u_slmask > 1.0 - r_l).float() weights = u_hmask + u_smmask + u_slmask loss = F.mse_loss(pred_score * weights, gt_iou_map * weights) loss = 0.5 * torch.sum(loss * torch.ones_like(weights)) / torch.sum( weights) return loss @staticmethod def pem_cls_loss(pred_score, gt_iou_map, mask, threshold=0.9, ratio_range=(1.05, 21), eps=1e-05): """Calculate Proposal Evaluation Module Classification Loss. Args: pred_score (torch.Tensor): Predicted temporal_iou score by BMN. gt_iou_map (torch.Tensor): Groundtruth temporal_iou score. mask (torch.Tensor): Boundary-Matching mask. threshold (float): Threshold of temporal_iou for positive instances. Default: 0.9. ratio_range (tuple): Lower bound and upper bound for ratio. Default: (1.05, 21) eps (float): Epsilon for small value. Default: 1e-5 Returns: torch.Tensor: Proposal evalutaion classification loss. """ pmask = (gt_iou_map > threshold).float() nmask = (gt_iou_map <= threshold).float() nmask = nmask * mask num_positive = max(torch.sum(pmask), 1) num_entries = num_positive + torch.sum(nmask) ratio = num_entries / num_positive ratio = torch.clamp(ratio, ratio_range[0], ratio_range[1]) coef_0 = 0.5 * ratio / (ratio - 1) coef_1 = 0.5 * ratio loss_pos = coef_1 * torch.log(pred_score + eps) * pmask loss_neg = coef_0 * torch.log(1.0 - pred_score + eps) * nmask loss = -1 * torch.sum(loss_pos + loss_neg) / num_entries return loss def forward(self, pred_bm, pred_start, pred_end, gt_iou_map, gt_start, gt_end, bm_mask, weight_tem=1.0, weight_pem_reg=10.0, weight_pem_cls=1.0): """Calculate Boundary Matching Network Loss. Args: pred_bm (torch.Tensor): Predicted confidence score for boundary matching map. pred_start (torch.Tensor): Predicted confidence score for start. pred_end (torch.Tensor): Predicted confidence score for end. gt_iou_map (torch.Tensor): Groundtruth score for boundary matching map. gt_start (torch.Tensor): Groundtruth temporal_iou score for start. gt_end (torch.Tensor): Groundtruth temporal_iou score for end. bm_mask (torch.Tensor): Boundary-Matching mask. weight_tem (float): Weight for tem loss. Default: 1.0. weight_pem_reg (float): Weight for pem regression loss. Default: 10.0. weight_pem_cls (float): Weight for pem classification loss. Default: 1.0. Returns: tuple([torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]): (loss, tem_loss, pem_reg_loss, pem_cls_loss). Loss is the bmn loss, tem_loss is the temporal evaluation loss, pem_reg_loss is the proposal evaluation regression loss, pem_cls_loss is the proposal evaluation classification loss. """ pred_bm_reg = pred_bm[:, 0].contiguous() pred_bm_cls = pred_bm[:, 1].contiguous() gt_iou_map = gt_iou_map * bm_mask pem_reg_loss = self.pem_reg_loss(pred_bm_reg, gt_iou_map, bm_mask) pem_cls_loss = self.pem_cls_loss(pred_bm_cls, gt_iou_map, bm_mask) tem_loss = self.tem_loss(pred_start, pred_end, gt_start, gt_end) loss = (weight_tem * tem_loss + weight_pem_reg * pem_reg_loss + weight_pem_cls * pem_cls_loss) return loss, tem_loss, pem_reg_loss, pem_cls_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]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch from torch import device 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 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 @triton.jit def triton_per_fused__to_copy_add_bitwise_and_clamp_clone_div_gt_le_log_mean_mse_loss_mul_neg_ones_like_reciprocal_rsub_sub_sum_0( in_out_ptr0, in_out_ptr1, in_out_ptr2, in_out_ptr3, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, out_ptr12, 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 r1 = rindex % 16 r2 = rindex // 16 % 4 tmp0 = tl.load(in_ptr0 + r0, None) tmp19 = tl.load(in_ptr1 + r0, None) tmp36 = tl.load(in_ptr2 + r0, None) tmp37 = tl.load(in_ptr3 + r0, None) tmp62 = tl.load(in_ptr4 + r0, None) tmp69 = tl.load(in_out_ptr0 + r0, None) tmp76 = tl.load(in_ptr5 + (r1 + 64 * r2), None, eviction_policy= 'evict_last') tmp110 = tl.load(in_ptr5 + (16 + r1 + 64 * r2), None, eviction_policy= 'evict_last') tmp126 = tl.load(in_ptr6 + r0, None) tmp139 = tl.load(in_ptr7 + r0, None) tmp1 = 0.5 tmp2 = tmp0 > tmp1 tmp3 = tmp2.to(tl.float32) tmp4 = tl.broadcast_to(tmp3, [RBLOCK]) tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0)) tmp7 = 1.0 tmp8 = triton_helpers.maximum(tmp6, tmp7) tmp9 = tl.full([1], 1, tl.int32) tmp10 = tmp9 / tmp8 tmp11 = 256.0 tmp12 = tmp10 * tmp11 tmp13 = 1.05 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = 21.0 tmp16 = triton_helpers.minimum(tmp14, tmp15) tmp17 = tmp16 * tmp1 tmp18 = tmp17 * tmp3 tmp20 = 1e-05 tmp21 = tmp19 + tmp20 tmp22 = tl_math.log(tmp21) tmp23 = tmp18 * tmp22 tmp24 = tmp16 - tmp7 tmp25 = tmp17 / tmp24 tmp26 = tmp7 - tmp3 tmp27 = tmp25 * tmp26 tmp28 = tmp7 - tmp19 tmp29 = tmp28 + tmp20 tmp30 = tl_math.log(tmp29) tmp31 = tmp27 * tmp30 tmp32 = tmp23 + tmp31 tmp33 = tl.broadcast_to(tmp32, [RBLOCK]) tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0)) tmp38 = tmp36 * tmp37 tmp39 = 0.7 tmp40 = tmp38 > tmp39 tmp41 = tmp40.to(tl.float32) tmp42 = tl.broadcast_to(tmp41, [RBLOCK]) tmp44 = triton_helpers.promote_to_tensor(tl.sum(tmp42, 0)) tmp45 = tmp38 <= tmp39 tmp46 = 0.3 tmp47 = tmp38 > tmp46 tmp48 = tmp45 & tmp47 tmp49 = tmp48.to(tl.float32) tmp50 = tl.broadcast_to(tmp49, [RBLOCK]) tmp52 = triton_helpers.promote_to_tensor(tl.sum(tmp50, 0)) tmp53 = tmp38 <= tmp46 tmp54 = 0.0 tmp55 = tmp38 > tmp54 tmp56 = tmp53 & tmp55 tmp57 = tmp56.to(tl.float32) tmp58 = tmp57 * tmp37 tmp59 = tl.broadcast_to(tmp58, [RBLOCK]) tmp61 = triton_helpers.promote_to_tensor(tl.sum(tmp59, 0)) tmp63 = tmp49 * tmp62 tmp64 = tmp44 / tmp52 tmp65 = tmp7 - tmp64 tmp66 = tmp63 > tmp65 tmp67 = tmp66.to(tl.float32) tmp68 = tmp41 + tmp67 tmp70 = tmp58 * tmp69 tmp71 = tmp44 / tmp61 tmp72 = tmp7 - tmp71 tmp73 = tmp70 > tmp72 tmp74 = tmp73.to(tl.float32) tmp75 = tmp68 + tmp74 tmp77 = tmp76 * tmp75 tmp78 = tmp38 * tmp75 tmp79 = tmp77 - tmp78 tmp80 = tmp79 * tmp79 tmp81 = tl.broadcast_to(tmp80, [RBLOCK]) tmp83 = triton_helpers.promote_to_tensor(tl.sum(tmp81, 0)) tmp84 = 0.9 tmp85 = tmp38 > tmp84 tmp86 = tmp85.to(tl.float32) tmp87 = tl.broadcast_to(tmp86, [RBLOCK]) tmp89 = triton_helpers.promote_to_tensor(tl.sum(tmp87, 0)) tmp90 = tmp38 <= tmp84 tmp91 = tmp90.to(tl.float32) tmp92 = tmp91 * tmp37 tmp93 = tl.broadcast_to(tmp92, [RBLOCK]) tmp95 = triton_helpers.promote_to_tensor(tl.sum(tmp93, 0)) tmp96 = tl.broadcast_to(tmp75, [RBLOCK]) tmp98 = triton_helpers.promote_to_tensor(tl.sum(tmp96, 0)) tmp99 = tmp83 / tmp11 tmp100 = tmp99 * tmp7 tmp101 = tl.broadcast_to(tmp100, [RBLOCK]) tmp103 = triton_helpers.promote_to_tensor(tl.sum(tmp101, 0)) tmp104 = triton_helpers.maximum(tmp89, tmp7) tmp105 = tmp104 + tmp95 tmp106 = tmp105 / tmp104 tmp107 = triton_helpers.maximum(tmp106, tmp13) tmp108 = triton_helpers.minimum(tmp107, tmp15) tmp109 = tmp108 * tmp1 tmp111 = tmp110 + tmp20 tmp112 = tl_math.log(tmp111) tmp113 = tmp109 * tmp112 tmp114 = tmp113 * tmp86 tmp115 = tmp108 - tmp7 tmp116 = tmp109 / tmp115 tmp117 = tmp7 - tmp110 tmp118 = tmp117 + tmp20 tmp119 = tl_math.log(tmp118) tmp120 = tmp116 * tmp119 tmp121 = tmp120 * tmp92 tmp122 = tmp114 + tmp121 tmp123 = tl.broadcast_to(tmp122, [RBLOCK]) tmp125 = triton_helpers.promote_to_tensor(tl.sum(tmp123, 0)) tmp127 = tmp126 > tmp1 tmp128 = tmp127.to(tl.float32) tmp129 = tl.broadcast_to(tmp128, [RBLOCK]) tmp131 = triton_helpers.promote_to_tensor(tl.sum(tmp129, 0)) tmp132 = triton_helpers.maximum(tmp131, tmp7) tmp133 = tmp9 / tmp132 tmp134 = tmp133 * tmp11 tmp135 = triton_helpers.maximum(tmp134, tmp13) tmp136 = triton_helpers.minimum(tmp135, tmp15) tmp137 = tmp136 * tmp1 tmp138 = tmp137 * tmp128 tmp140 = tmp139 + tmp20 tmp141 = tl_math.log(tmp140) tmp142 = tmp138 * tmp141 tmp143 = tmp136 - tmp7 tmp144 = tmp137 / tmp143 tmp145 = tmp7 - tmp128 tmp146 = tmp144 * tmp145 tmp147 = tmp7 - tmp139 tmp148 = tmp147 + tmp20 tmp149 = tl_math.log(tmp148) tmp150 = tmp146 * tmp149 tmp151 = tmp142 + tmp150 tmp152 = tl.broadcast_to(tmp151, [RBLOCK]) tmp154 = triton_helpers.promote_to_tensor(tl.sum(tmp152, 0)) tmp155 = tmp35 / tmp11 tmp156 = -tmp155 tmp157 = tmp154 / tmp11 tmp158 = -tmp157 tmp159 = tmp156 + tmp158 tmp160 = tmp103 * tmp1 tmp161 = tmp160 / tmp98 tmp162 = -1.0 tmp163 = tmp125 * tmp162 tmp164 = tmp163 / tmp105 tmp165 = tmp159 * tmp7 tmp166 = 10.0 tmp167 = tmp161 * tmp166 tmp168 = tmp165 + tmp167 tmp169 = tmp164 * tmp7 tmp170 = tmp168 + tmp169 tl.debug_barrier() tl.store(in_out_ptr2 + tl.full([1], 0, tl.int32), tmp159, None) tl.debug_barrier() tl.store(in_out_ptr1 + tl.full([1], 0, tl.int32), tmp161, None) tl.debug_barrier() tl.store(in_out_ptr3 + tl.full([1], 0, tl.int32), tmp164, None) tl.store(out_ptr12 + tl.full([1], 0, tl.int32), tmp170, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1, arg6_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)) assert_size_stride(arg6_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf11 = torch.ops.aten.rand.default([4, 4, 4, 4], dtype=torch. float32, device=device(type='cuda', index=0), pin_memory=False) buf12 = buf11 del buf11 buf7 = torch.ops.aten.rand.default([4, 4, 4, 4], dtype=torch. float32, device=device(type='cuda', index=0), pin_memory=False) buf8 = buf7 del buf7 buf2 = empty_strided_cuda((), (), torch.float32) buf14 = buf12 del buf12 buf15 = empty_strided_cuda((), (), torch.float32) buf16 = buf15 del buf15 buf22 = empty_strided_cuda((), (), torch.float32) buf6 = buf2 del buf2 buf18 = buf16 del buf16 buf23 = buf22 del buf22 buf24 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_per_fused__to_copy_add_bitwise_and_clamp_clone_div_gt_le_log_mean_mse_loss_mul_neg_ones_like_reciprocal_rsub_sub_sum_0[ grid(1)](buf14, buf18, buf6, buf23, arg4_1, arg3_1, arg1_1, arg2_1, buf8, arg0_1, arg6_1, arg5_1, buf24, 1, 256, num_warps= 2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 del arg4_1 del arg5_1 del arg6_1 del buf14 del buf8 return buf24, buf6, buf18, buf23 def binary_logistic_regression_loss(reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-05): """Binary Logistic Regression Loss.""" label = label.view(-1) reg_score = reg_score.contiguous().view(-1) pmask = (label > threshold).float() num_positive = max(torch.sum(pmask), 1) num_entries = len(label) ratio = num_entries / num_positive ratio = min(max(ratio, ratio_range[0]), ratio_range[1]) coef_0 = 0.5 * ratio / (ratio - 1) coef_1 = 0.5 * ratio loss = coef_1 * pmask * torch.log(reg_score + eps) + coef_0 * (1.0 - pmask ) * torch.log(1.0 - reg_score + eps) loss = -torch.mean(loss) return loss class BMNLossNew(nn.Module): """BMN Loss. From paper https://arxiv.org/abs/1907.09702, code https://github.com/JJBOY/BMN-Boundary-Matching-Network. It will calculate loss for BMN Model. This loss is a weighted sum of 1) temporal evaluation loss based on confidence score of start and end positions. 2) proposal evaluation regression loss based on confidence scores of candidate proposals. 3) proposal evaluation classification loss based on classification results of candidate proposals. """ @staticmethod def tem_loss(pred_start, pred_end, gt_start, gt_end): """Calculate Temporal Evaluation Module Loss. This function calculate the binary_logistic_regression_loss for start and end respectively and returns the sum of their losses. Args: pred_start (torch.Tensor): Predicted start score by BMN model. pred_end (torch.Tensor): Predicted end score by BMN model. gt_start (torch.Tensor): Groundtruth confidence score for start. gt_end (torch.Tensor): Groundtruth confidence score for end. Returns: torch.Tensor: Returned binary logistic loss. """ loss_start = binary_logistic_regression_loss(pred_start, gt_start) loss_end = binary_logistic_regression_loss(pred_end, gt_end) loss = loss_start + loss_end return loss @staticmethod def pem_reg_loss(pred_score, gt_iou_map, mask, high_temporal_iou_threshold=0.7, low_temporal_iou_threshold=0.3): """Calculate Proposal Evaluation Module Regression Loss. Args: pred_score (torch.Tensor): Predicted temporal_iou score by BMN. gt_iou_map (torch.Tensor): Groundtruth temporal_iou score. mask (torch.Tensor): Boundary-Matching mask. high_temporal_iou_threshold (float): Higher threshold of temporal_iou. Default: 0.7. low_temporal_iou_threshold (float): Higher threshold of temporal_iou. Default: 0.3. Returns: torch.Tensor: Proposal evalutaion regression loss. """ u_hmask = (gt_iou_map > high_temporal_iou_threshold).float() u_mmask = ((gt_iou_map <= high_temporal_iou_threshold) & ( gt_iou_map > low_temporal_iou_threshold)).float() u_lmask = ((gt_iou_map <= low_temporal_iou_threshold) & (gt_iou_map > 0.0)).float() u_lmask = u_lmask * mask num_h = torch.sum(u_hmask) num_m = torch.sum(u_mmask) num_l = torch.sum(u_lmask) r_m = num_h / num_m u_smmask = torch.rand_like(gt_iou_map) u_smmask = u_mmask * u_smmask u_smmask = (u_smmask > 1.0 - r_m).float() r_l = num_h / num_l u_slmask = torch.rand_like(gt_iou_map) u_slmask = u_lmask * u_slmask u_slmask = (u_slmask > 1.0 - r_l).float() weights = u_hmask + u_smmask + u_slmask loss = F.mse_loss(pred_score * weights, gt_iou_map * weights) loss = 0.5 * torch.sum(loss * torch.ones_like(weights)) / torch.sum( weights) return loss @staticmethod def pem_cls_loss(pred_score, gt_iou_map, mask, threshold=0.9, ratio_range=(1.05, 21), eps=1e-05): """Calculate Proposal Evaluation Module Classification Loss. Args: pred_score (torch.Tensor): Predicted temporal_iou score by BMN. gt_iou_map (torch.Tensor): Groundtruth temporal_iou score. mask (torch.Tensor): Boundary-Matching mask. threshold (float): Threshold of temporal_iou for positive instances. Default: 0.9. ratio_range (tuple): Lower bound and upper bound for ratio. Default: (1.05, 21) eps (float): Epsilon for small value. Default: 1e-5 Returns: torch.Tensor: Proposal evalutaion classification loss. """ pmask = (gt_iou_map > threshold).float() nmask = (gt_iou_map <= threshold).float() nmask = nmask * mask num_positive = max(torch.sum(pmask), 1) num_entries = num_positive + torch.sum(nmask) ratio = num_entries / num_positive ratio = torch.clamp(ratio, ratio_range[0], ratio_range[1]) coef_0 = 0.5 * ratio / (ratio - 1) coef_1 = 0.5 * ratio loss_pos = coef_1 * torch.log(pred_score + eps) * pmask loss_neg = coef_0 * torch.log(1.0 - pred_score + eps) * nmask loss = -1 * torch.sum(loss_pos + loss_neg) / num_entries return loss def forward(self, input_0, input_1, input_2, input_3, input_4, input_5, input_6): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 arg3_1 = input_3 arg4_1 = input_4 arg5_1 = input_5 arg6_1 = input_6 output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1, arg6_1]) return output[0], output[1], output[2], output[3]
Viditagarwal7479/Video-Swin-Transformer
BMNLoss
false
18,064
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
LanguageModelCriterion
import torch import torch.nn as nn from torch.autograd import * import torch.nn.init def to_contiguous(tensor): if tensor.is_contiguous(): return tensor else: return tensor.contiguous() class LanguageModelCriterion(nn.Module): def __init__(self): super(LanguageModelCriterion, self).__init__() def forward(self, input, target, mask): target = target[:, :input.size(1)] mask = mask[:, :input.size(1)] input = to_contiguous(input).view(-1, input.size(2)) target = to_contiguous(target).view(-1, 1) mask = to_contiguous(mask).view(-1, 1) output = -input.gather(1, target) * mask output = torch.sum(output) / torch.sum(mask) return output def get_inputs(): return [torch.ones([4, 4, 4], dtype=torch.int64), torch.ones([4, 4], dtype=torch.int64), 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 import torch.nn as nn from torch.autograd import * import torch.nn.init 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_div_gather_mul_neg_sum_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 16 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) tmp9 = tl.load(in_ptr2 + r0, None) tmp1 = tl.full([XBLOCK, RBLOCK], 4, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 4), 'index out of bounds: 0 <= tmp4 < 4') tmp6 = tl.load(in_ptr1 + (tmp4 + 4 * r0), None, eviction_policy= 'evict_last') tmp7 = -tmp6 tmp8 = tmp7.to(tl.float32) tmp10 = tmp8 * tmp9 tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK]) tmp13 = tl.sum(tmp11, 1)[:, None] tmp14 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK]) tmp16 = tl.sum(tmp14, 1)[:, None] tmp17 = tmp13 / tmp16 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp17, None) def call(args): arg0_1, arg1_1, arg2_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(arg1_1, (4, 4), (4, 1)) assert_size_stride(arg2_1, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_div_gather_mul_neg_sum_0[grid(1)](buf2, arg1_1, arg0_1, arg2_1, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 return buf2, def to_contiguous(tensor): if tensor.is_contiguous(): return tensor else: return tensor.contiguous() class LanguageModelCriterionNew(nn.Module): def __init__(self): super(LanguageModelCriterionNew, self).__init__() def forward(self, input_0, input_1, input_2): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
WuJie1010/Fine-Grained-Image-Captioning
LanguageModelCriterion
false
18,065
[ "MIT" ]
9
340bc1868634f3bf0fdd62d439fec32ee1b45407
https://github.com/WuJie1010/Fine-Grained-Image-Captioning/tree/340bc1868634f3bf0fdd62d439fec32ee1b45407
ImgAttention
from _paritybench_helpers import _mock_config import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import * import torch.nn.init class ImgAttention(nn.Module): def __init__(self, opt): super(ImgAttention, self).__init__() self.rnn_size = opt.rnn_size self.att_hid_size = opt.att_hid_size self.h2att = nn.Linear(self.rnn_size, self.att_hid_size) self.alpha_net = nn.Linear(self.att_hid_size, 1) def forward(self, h, att_feats, p_att_feats): att_size = att_feats.numel() // att_feats.size(0) // self.rnn_size att = p_att_feats.view(-1, att_size, self.att_hid_size) att_h = self.h2att(h) att_h = att_h.unsqueeze(1).expand_as(att) dot = att + att_h dot = F.tanh(dot) dot = dot.view(-1, self.att_hid_size) dot = self.alpha_net(dot) dot = dot.view(-1, att_size) weight = F.softmax(dot) att_feats_ = att_feats.view(-1, att_size, self.rnn_size) att_res = torch.bmm(weight.unsqueeze(1), att_feats_).squeeze(1) return att_res def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'opt': _mock_config(rnn_size=4, att_hid_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 libdevice, math as tl_math import torch.nn as nn from torch.autograd import * import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_add_tanh_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 x0 = xindex % 4 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tmp5 = libdevice.tanh(tmp4) tl.store(out_ptr0 + x3, tmp5, xmask) @triton.jit def triton_per_fused__softmax_1(in_ptr0, out_ptr0, out_ptr1, out_ptr2, 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_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, float('-inf')) tmp4 = triton_helpers.max2(tmp3, 1)[:, None] tmp5 = tmp0 - tmp4 tmp6 = tl_math.exp(tmp5) tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK]) tmp9 = tl.where(xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tmp11 = tmp6 / tmp10 tl.store(out_ptr2 + (r1 + 16 * x0), tmp11, xmask) tl.store(out_ptr0 + x0, tmp4, xmask) tl.store(out_ptr1 + x0, tmp10, 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, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4, 4), (4, 1)) assert_size_stride(primals_6, (1, 4), (4, 1)) assert_size_stride(primals_7, (1,), (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_5, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf0) del primals_3 buf1 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_tanh_0[grid(256)](primals_2, buf0, primals_4, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 del primals_4 buf3 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_6, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_7 buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32) buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32) buf6 = empty_strided_cuda((4, 16), (16, 1), torch.float32) triton_per_fused__softmax_1[grid(4)](buf3, buf4, buf5, buf6, 4, 16, XBLOCK=1, num_warps=2, num_stages=1) buf7 = reinterpret_tensor(buf0, (4, 1, 4), (4, 4, 1), 0) del buf0 extern_kernels.bmm(reinterpret_tensor(buf6, (4, 1, 16), (16, 0, 1), 0), reinterpret_tensor(primals_1, (4, 16, 4), (64, 4, 1), 0), out=buf7) del buf6 return reinterpret_tensor(buf7, (4, 4), (4, 1), 0 ), primals_5, buf1, buf3, buf4, buf5, reinterpret_tensor(primals_1, (4, 4, 16), (64, 1, 4), 0), primals_6 class ImgAttentionNew(nn.Module): def __init__(self, opt): super(ImgAttentionNew, self).__init__() self.rnn_size = opt.rnn_size self.att_hid_size = opt.att_hid_size self.h2att = nn.Linear(self.rnn_size, self.att_hid_size) self.alpha_net = nn.Linear(self.att_hid_size, 1) def forward(self, input_0, input_1, input_2): primals_3 = self.h2att.weight primals_4 = self.h2att.bias primals_6 = self.alpha_net.weight primals_7 = self.alpha_net.bias primals_5 = input_0 primals_1 = input_1 primals_2 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
WuJie1010/Fine-Grained-Image-Captioning
ImgAttention
false
18,066
[ "MIT" ]
9
340bc1868634f3bf0fdd62d439fec32ee1b45407
https://github.com/WuJie1010/Fine-Grained-Image-Captioning/tree/340bc1868634f3bf0fdd62d439fec32ee1b45407
UNET
import torch import torch.nn as nn def concat(c1, c2): return torch.cat([c1, c2], dim=1) def conv1x1(in_c, out_c, k, s): return nn.ConvTranspose2d(in_c, out_c, kernel_size=k, stride=s) def conv3x3(in_c, out_c, k, s): return nn.Conv2d(in_c, out_c, kernel_size=k, stride=s) def cut(c1, c2): x1, y1 = c1.size()[2:] x2, y2 = c2.size()[2:] c2 = c2[:, :, int((x2 - x1) / 2):int((x1 + x2) / 2), int((y2 - y1) / 2) :int((y2 + y1) / 2)] return c2 def upconv2x2(in_c, out_c, k, s): return nn.ConvTranspose2d(in_c, out_c, kernel_size=k, stride=s) class UNET(nn.Module): def __init__(self, in_channels, n_classes): super(UNET, self).__init__() self.conv0 = conv3x3(in_channels, 64, 3, 1) self.relu = nn.ReLU(inplace=True) self.conv1 = conv3x3(64, 64, 3, 1) self.maxpool_0 = nn.MaxPool2d(kernel_size=2) self.conv2 = conv3x3(64, 128, 3, 1) self.conv3 = conv3x3(128, 128, 3, 1) self.conv4 = conv3x3(128, 256, 3, 1) self.conv5 = conv3x3(256, 256, 3, 1) self.conv6 = conv3x3(256, 512, 3, 1) self.conv7 = conv3x3(512, 512, 3, 1) self.conv8 = conv3x3(512, 1024, 3, 1) self.conv9 = conv3x3(1024, 1024, 3, 1) self.conv10 = conv3x3(1024, 512, 3, 1) self.conv11 = conv3x3(512, 256, 3, 1) self.conv12 = conv3x3(256, 128, 3, 1) self.conv13 = conv3x3(128, 64, 3, 1) self.conv14 = conv1x1(64, n_classes, 1, 1) self.upconv0 = upconv2x2(1024, 512, 2, 2) self.upconv1 = upconv2x2(512, 256, 2, 2) self.upconv2 = upconv2x2(256, 128, 2, 2) self.upconv3 = upconv2x2(128, 64, 2, 2) def forward(self, x): x = self.conv0(x) x = self.relu(x) x = self.conv1(x) x = self.relu(x) stage1 = x x = self.maxpool_0(x) x = self.conv2(x) x = self.conv3(x) stage2 = x x = self.maxpool_0(x) x = self.conv4(x) x = self.conv5(x) stage3 = x x = self.maxpool_0(x) x = self.conv6(x) x = self.conv7(x) stage4 = x x = self.maxpool_0(x) x = self.conv8(x) x = self.conv9(x) x = self.upconv0(x) stage4 = cut(x, stage4) x = concat(x, stage4) x = self.conv10(x) x = self.conv7(x) x = self.upconv1(x) stage3 = cut(x, stage3) x = concat(x, stage3) x = self.conv11(x) x = self.conv5(x) x = self.upconv2(x) stage2 = cut(x, stage2) x = concat(x, stage2) x = self.conv12(x) x = self.conv3(x) x = self.upconv3(x) stage1 = cut(x, stage1) x = concat(x, stage1) x = self.conv13(x) x = self.conv1(x) x = self.conv14(x) return x def get_inputs(): return [torch.rand([4, 4, 256, 256])] def get_init_inputs(): return [[], {'in_channels': 4, 'n_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 @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16516096 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 64516 % 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_convolution_relu_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 // 63504 % 64 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, 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 + x3, tmp4, None) @triton.jit def triton_poi_fused_max_pool2d_with_indices_2(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4064256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 126 x3 = xindex // 126 x2 = xindex // 15876 x4 = xindex % 15876 tmp0 = tl.load(in_ptr0 + (2 * x0 + 504 * x3), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 504 * x3), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (252 + 2 * x0 + 504 * x3), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (253 + 2 * x0 + 504 * x3), 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 + (x4 + 15904 * x2), tmp6, xmask) tl.store(out_ptr1 + (x4 + 16000 * x2), tmp16, xmask) @triton.jit def triton_poi_fused_convolution_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) x3 = xindex x1 = xindex // 15376 % 128 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_4(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 // 14884 % 128 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_max_pool2d_with_indices_5(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 1905152 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 61 x3 = xindex // 61 x2 = xindex // 3721 x4 = xindex % 3721 tmp0 = tl.load(in_ptr0 + (2 * x0 + 244 * x3), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 244 * x3), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (122 + 2 * x0 + 244 * x3), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (123 + 2 * x0 + 244 * x3), 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 + (x4 + 3744 * x2), tmp6, xmask) tl.store(out_ptr1 + (x4 + 3840 * x2), tmp16, xmask) @triton.jit def triton_poi_fused_convolution_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 3564544 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3481 % 256 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_convolution_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 3326976 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3249 % 256 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_8(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex % 28 x1 = xindex // 28 % 28 x2 = xindex // 784 x3 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 114 * x1 + 3249 * x2), None, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 114 * x1 + 3249 * x2), None, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (57 + 2 * x0 + 114 * x1 + 3249 * x2), None, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (58 + 2 * x0 + 114 * x1 + 3249 * x2), None, 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 + x3, tmp6, None) tl.store(out_ptr1 + x3, tmp16, None) @triton.jit def triton_poi_fused_convolution_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) x3 = xindex x1 = xindex // 676 % 512 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_10(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 // 576 % 512 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_max_pool2d_with_indices_11(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex % 12 x1 = xindex // 12 x2 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 48 * x1), None, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 48 * x1), None, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (24 + 2 * x0 + 48 * x1), None, eviction_policy ='evict_last') tmp5 = tl.load(in_ptr0 + (25 + 2 * x0 + 48 * x1), None, 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 + x2, tmp6, None) tl.store(out_ptr1 + x2, tmp16, None) @triton.jit def triton_poi_fused_convolution_12(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 // 100 % 1024 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_13(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 // 64 % 1024 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_cat_14(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) x2 = xindex // 256 % 1024 x3 = xindex // 262144 x4 = xindex % 256 x0 = xindex % 16 x1 = xindex // 16 % 16 x5 = xindex tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 512, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x4 + 256 * x2 + 131072 * x3), tmp4, other=0.0) tmp6 = tl.load(in_ptr1 + x2, 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], 1024, tl.int64) tmp13 = tl.load(in_ptr2 + (100 + x0 + 24 * x1 + 576 * (-512 + x2) + 294912 * x3), tmp10, other=0.0) tmp14 = tl.where(tmp4, tmp9, tmp13) tl.store(out_ptr0 + x5, tmp14, None) @triton.jit def triton_poi_fused_convolution_15(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 // 196 % 512 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_16(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 // 144 % 512 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_cat_17(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) x2 = xindex // 576 % 512 x3 = xindex // 294912 x4 = xindex % 576 x0 = xindex % 24 x1 = xindex // 24 % 24 x5 = xindex tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 256, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x4 + 576 * x2 + 147456 * x3), tmp4, other=0.0) tmp6 = tl.load(in_ptr1 + x2, 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], 512, tl.int64) tmp13 = tl.load(in_ptr2 + (928 + x0 + 57 * x1 + 3249 * (-256 + x2) + 831744 * x3), tmp10, other=0.0) tmp14 = tl.where(tmp4, tmp9, tmp13) tl.store(out_ptr0 + x5, tmp14, None) @triton.jit def triton_poi_fused_convolution_18(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 // 484 % 256 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_19(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 // 400 % 256 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_cat_20(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) x2 = xindex // 1600 % 256 x3 = xindex // 409600 x4 = xindex % 1600 x0 = xindex % 40 x1 = xindex // 40 % 40 x5 = xindex tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 128, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x4 + 1600 * x2 + 204800 * x3), tmp4, other=0.0) tmp6 = tl.load(in_ptr1 + x2, 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], 256, tl.int64) tmp13 = tl.load(in_ptr2 + (5043 + x0 + 122 * x1 + 14884 * (-128 + x2) + 1905152 * x3), tmp10, other=0.0) tmp14 = tl.where(tmp4, tmp9, tmp13) tl.store(out_ptr0 + x5, tmp14, None) @triton.jit def triton_poi_fused_convolution_21(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 // 1444 % 128 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_22(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 // 1296 % 128 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_cat_23(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) x2 = xindex // 5184 % 128 x3 = xindex // 663552 x4 = xindex % 5184 x0 = xindex % 72 x1 = xindex // 72 % 72 x5 = xindex tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 64, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x4 + 5184 * x2 + 331776 * x3), tmp4, other=0.0) tmp6 = tl.load(in_ptr1 + x2, 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], 128, tl.int64) tmp13 = tl.load(in_ptr2 + (22770 + x0 + 252 * x1 + 63504 * (-64 + x2) + 4064256 * x3), tmp10, other=0.0) tmp14 = tl.where(tmp4, tmp9, tmp13) tl.store(out_ptr0 + x5, tmp14, None) @triton.jit def triton_poi_fused_convolution_24(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1254400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4900 % 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_convolution_25(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 // 4624 % 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_26(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 73984 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4624 % 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, 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, primals_28, primals_29, primals_30, primals_31, primals_32, primals_33, primals_34, primals_35, primals_36, primals_37, primals_38, primals_39) = args args.clear() assert_size_stride(primals_1, (64, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 4, 256, 256), (262144, 65536, 256, 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, (128, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_9, (128,), (1,)) assert_size_stride(primals_10, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_11, (256,), (1,)) assert_size_stride(primals_12, (256, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_13, (256,), (1,)) assert_size_stride(primals_14, (512, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_15, (512,), (1,)) assert_size_stride(primals_16, (512, 512, 3, 3), (4608, 9, 3, 1)) assert_size_stride(primals_17, (512,), (1,)) assert_size_stride(primals_18, (1024, 512, 3, 3), (4608, 9, 3, 1)) assert_size_stride(primals_19, (1024,), (1,)) assert_size_stride(primals_20, (1024, 1024, 3, 3), (9216, 9, 3, 1)) assert_size_stride(primals_21, (1024,), (1,)) assert_size_stride(primals_22, (1024, 512, 2, 2), (2048, 4, 2, 1)) assert_size_stride(primals_23, (512,), (1,)) assert_size_stride(primals_24, (512, 1024, 3, 3), (9216, 9, 3, 1)) assert_size_stride(primals_25, (512,), (1,)) assert_size_stride(primals_26, (512, 256, 2, 2), (1024, 4, 2, 1)) assert_size_stride(primals_27, (256,), (1,)) assert_size_stride(primals_28, (256, 512, 3, 3), (4608, 9, 3, 1)) assert_size_stride(primals_29, (256,), (1,)) assert_size_stride(primals_30, (256, 128, 2, 2), (512, 4, 2, 1)) assert_size_stride(primals_31, (128,), (1,)) assert_size_stride(primals_32, (128, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_33, (128,), (1,)) assert_size_stride(primals_34, (128, 64, 2, 2), (256, 4, 2, 1)) assert_size_stride(primals_35, (64,), (1,)) assert_size_stride(primals_36, (64, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_37, (64,), (1,)) assert_size_stride(primals_38, (64, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_39, (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, 64, 254, 254), (4129024, 64516, 254, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(16516096)](buf1, primals_2, 16516096, XBLOCK=1024, num_warps=4, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, 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, 64, 252, 252), (4064256, 63504, 252, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_1[grid(16257024)](buf3, primals_5, 16257024, XBLOCK=1024, num_warps=4, num_stages=1) buf4 = empty_strided_cuda((4, 64, 126, 126), (1017856, 15904, 126, 1), torch.float32) buf5 = empty_strided_cuda((4, 64, 126, 126), (1024000, 16000, 126, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_2[grid(4064256)](buf3, buf4, buf5, 4064256, XBLOCK=512, num_warps=8, num_stages=1) buf6 = extern_kernels.convolution(buf4, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 128, 124, 124), (1968128, 15376, 124, 1)) buf7 = buf6 del buf6 triton_poi_fused_convolution_3[grid(7872512)](buf7, primals_7, 7872512, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 128, 122, 122), (1905152, 14884, 122, 1)) buf9 = buf8 del buf8 triton_poi_fused_convolution_4[grid(7620608)](buf9, primals_9, 7620608, XBLOCK=1024, num_warps=4, num_stages=1) buf10 = empty_strided_cuda((4, 128, 61, 61), (479232, 3744, 61, 1), torch.float32) buf11 = empty_strided_cuda((4, 128, 61, 61), (491520, 3840, 61, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_5[grid(1905152)](buf9, buf10, buf11, 1905152, XBLOCK=512, num_warps=8, num_stages=1) buf12 = extern_kernels.convolution(buf10, primals_10, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 256, 59, 59), (891136, 3481, 59, 1)) buf13 = buf12 del buf12 triton_poi_fused_convolution_6[grid(3564544)](buf13, primals_11, 3564544, XBLOCK=1024, num_warps=4, num_stages=1) del primals_11 buf14 = extern_kernels.convolution(buf13, primals_12, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf14, (4, 256, 57, 57), (831744, 3249, 57, 1)) buf15 = buf14 del buf14 triton_poi_fused_convolution_7[grid(3326976)](buf15, primals_13, 3326976, XBLOCK=1024, num_warps=4, num_stages=1) buf16 = empty_strided_cuda((4, 256, 28, 28), (200704, 784, 28, 1), torch.float32) buf17 = empty_strided_cuda((4, 256, 28, 28), (200704, 784, 28, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_8[grid(802816)](buf15, buf16, buf17, 802816, XBLOCK=512, num_warps=8, num_stages=1) buf18 = extern_kernels.convolution(buf16, primals_14, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf18, (4, 512, 26, 26), (346112, 676, 26, 1)) buf19 = buf18 del buf18 triton_poi_fused_convolution_9[grid(1384448)](buf19, primals_15, 1384448, XBLOCK=1024, num_warps=4, num_stages=1) del primals_15 buf20 = extern_kernels.convolution(buf19, primals_16, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf20, (4, 512, 24, 24), (294912, 576, 24, 1)) buf21 = buf20 del buf20 triton_poi_fused_convolution_10[grid(1179648)](buf21, primals_17, 1179648, XBLOCK=1024, num_warps=4, num_stages=1) buf22 = empty_strided_cuda((4, 512, 12, 12), (73728, 144, 12, 1), torch.float32) buf23 = empty_strided_cuda((4, 512, 12, 12), (73728, 144, 12, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_11[grid(294912)](buf21, buf22, buf23, 294912, XBLOCK=512, num_warps=8, num_stages=1) buf24 = extern_kernels.convolution(buf22, primals_18, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf24, (4, 1024, 10, 10), (102400, 100, 10, 1)) buf25 = buf24 del buf24 triton_poi_fused_convolution_12[grid(409600)](buf25, primals_19, 409600, XBLOCK=1024, num_warps=4, num_stages=1) del primals_19 buf26 = extern_kernels.convolution(buf25, primals_20, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf26, (4, 1024, 8, 8), (65536, 64, 8, 1)) buf27 = buf26 del buf26 triton_poi_fused_convolution_13[grid(262144)](buf27, primals_21, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del primals_21 buf28 = extern_kernels.convolution(buf27, primals_22, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf28, (4, 512, 16, 16), (131072, 256, 16, 1)) buf29 = empty_strided_cuda((4, 1024, 16, 16), (262144, 256, 16, 1), torch.float32) triton_poi_fused_cat_14[grid(1048576)](buf28, primals_23, buf21, buf29, 1048576, XBLOCK=1024, num_warps=4, num_stages=1) del buf28 del primals_23 buf30 = extern_kernels.convolution(buf29, primals_24, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf30, (4, 512, 14, 14), (100352, 196, 14, 1)) buf31 = buf30 del buf30 triton_poi_fused_convolution_15[grid(401408)](buf31, primals_25, 401408, XBLOCK=1024, num_warps=4, num_stages=1) del primals_25 buf32 = extern_kernels.convolution(buf31, primals_16, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf32, (4, 512, 12, 12), (73728, 144, 12, 1)) buf33 = buf32 del buf32 triton_poi_fused_convolution_16[grid(294912)](buf33, primals_17, 294912, XBLOCK=1024, num_warps=4, num_stages=1) del primals_17 buf34 = extern_kernels.convolution(buf33, primals_26, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf34, (4, 256, 24, 24), (147456, 576, 24, 1)) buf35 = empty_strided_cuda((4, 512, 24, 24), (294912, 576, 24, 1), torch.float32) triton_poi_fused_cat_17[grid(1179648)](buf34, primals_27, buf15, buf35, 1179648, XBLOCK=1024, num_warps=4, num_stages=1) del buf34 del primals_27 buf36 = extern_kernels.convolution(buf35, primals_28, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf36, (4, 256, 22, 22), (123904, 484, 22, 1)) buf37 = buf36 del buf36 triton_poi_fused_convolution_18[grid(495616)](buf37, primals_29, 495616, XBLOCK=1024, num_warps=4, num_stages=1) del primals_29 buf38 = extern_kernels.convolution(buf37, primals_12, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf38, (4, 256, 20, 20), (102400, 400, 20, 1)) buf39 = buf38 del buf38 triton_poi_fused_convolution_19[grid(409600)](buf39, primals_13, 409600, XBLOCK=1024, num_warps=4, num_stages=1) del primals_13 buf40 = extern_kernels.convolution(buf39, primals_30, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf40, (4, 128, 40, 40), (204800, 1600, 40, 1)) buf41 = empty_strided_cuda((4, 256, 40, 40), (409600, 1600, 40, 1), torch.float32) triton_poi_fused_cat_20[grid(1638400)](buf40, primals_31, buf9, buf41, 1638400, XBLOCK=1024, num_warps=4, num_stages=1) del buf40 del primals_31 buf42 = extern_kernels.convolution(buf41, primals_32, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf42, (4, 128, 38, 38), (184832, 1444, 38, 1)) buf43 = buf42 del buf42 triton_poi_fused_convolution_21[grid(739328)](buf43, primals_33, 739328, XBLOCK=1024, num_warps=4, num_stages=1) del primals_33 buf44 = extern_kernels.convolution(buf43, primals_8, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf44, (4, 128, 36, 36), (165888, 1296, 36, 1)) buf45 = buf44 del buf44 triton_poi_fused_convolution_22[grid(663552)](buf45, primals_9, 663552, XBLOCK=1024, num_warps=4, num_stages=1) del primals_9 buf46 = extern_kernels.convolution(buf45, primals_34, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf46, (4, 64, 72, 72), (331776, 5184, 72, 1)) buf47 = empty_strided_cuda((4, 128, 72, 72), (663552, 5184, 72, 1), torch.float32) triton_poi_fused_cat_23[grid(2654208)](buf46, primals_35, buf3, buf47, 2654208, XBLOCK=1024, num_warps=4, num_stages=1) del buf46 del primals_35 buf48 = extern_kernels.convolution(buf47, primals_36, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf48, (4, 64, 70, 70), (313600, 4900, 70, 1)) buf49 = buf48 del buf48 triton_poi_fused_convolution_24[grid(1254400)](buf49, primals_37, 1254400, XBLOCK=1024, num_warps=4, num_stages=1) del primals_37 buf50 = extern_kernels.convolution(buf49, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf50, (4, 64, 68, 68), (295936, 4624, 68, 1)) buf51 = buf50 del buf50 triton_poi_fused_convolution_25[grid(1183744)](buf51, primals_5, 1183744, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf52 = extern_kernels.convolution(buf51, primals_38, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf52, (4, 4, 68, 68), (18496, 4624, 68, 1)) buf53 = buf52 del buf52 triton_poi_fused_convolution_26[grid(73984)](buf53, primals_39, 73984, XBLOCK=1024, num_warps=4, num_stages=1) del primals_39 return (buf53, primals_1, primals_3, primals_4, primals_6, primals_8, primals_10, primals_12, primals_14, primals_16, primals_18, primals_20, primals_22, primals_24, primals_26, primals_28, primals_30, primals_32, primals_34, primals_36, primals_38, buf1, buf3, buf4, buf5, buf7, buf9, buf10, buf11, buf13, buf15, buf16, buf17, buf19, buf21, buf22, buf23, buf25, buf27, buf29, buf31, buf33, buf35, buf37, buf39, buf41, buf43, buf45, buf47, buf49, buf51) def concat(c1, c2): return torch.cat([c1, c2], dim=1) def conv1x1(in_c, out_c, k, s): return nn.ConvTranspose2d(in_c, out_c, kernel_size=k, stride=s) def conv3x3(in_c, out_c, k, s): return nn.Conv2d(in_c, out_c, kernel_size=k, stride=s) def cut(c1, c2): x1, y1 = c1.size()[2:] x2, y2 = c2.size()[2:] c2 = c2[:, :, int((x2 - x1) / 2):int((x1 + x2) / 2), int((y2 - y1) / 2) :int((y2 + y1) / 2)] return c2 def upconv2x2(in_c, out_c, k, s): return nn.ConvTranspose2d(in_c, out_c, kernel_size=k, stride=s) class UNETNew(nn.Module): def __init__(self, in_channels, n_classes): super(UNETNew, self).__init__() self.conv0 = conv3x3(in_channels, 64, 3, 1) self.relu = nn.ReLU(inplace=True) self.conv1 = conv3x3(64, 64, 3, 1) self.maxpool_0 = nn.MaxPool2d(kernel_size=2) self.conv2 = conv3x3(64, 128, 3, 1) self.conv3 = conv3x3(128, 128, 3, 1) self.conv4 = conv3x3(128, 256, 3, 1) self.conv5 = conv3x3(256, 256, 3, 1) self.conv6 = conv3x3(256, 512, 3, 1) self.conv7 = conv3x3(512, 512, 3, 1) self.conv8 = conv3x3(512, 1024, 3, 1) self.conv9 = conv3x3(1024, 1024, 3, 1) self.conv10 = conv3x3(1024, 512, 3, 1) self.conv11 = conv3x3(512, 256, 3, 1) self.conv12 = conv3x3(256, 128, 3, 1) self.conv13 = conv3x3(128, 64, 3, 1) self.conv14 = conv1x1(64, n_classes, 1, 1) self.upconv0 = upconv2x2(1024, 512, 2, 2) self.upconv1 = upconv2x2(512, 256, 2, 2) self.upconv2 = upconv2x2(256, 128, 2, 2) self.upconv3 = upconv2x2(128, 64, 2, 2) def forward(self, input_0): primals_1 = self.conv0.weight primals_2 = self.conv0.bias primals_4 = self.conv1.weight primals_5 = self.conv1.bias primals_6 = self.conv2.weight primals_7 = self.conv2.bias primals_8 = self.conv3.weight primals_9 = self.conv3.bias primals_10 = self.conv4.weight primals_11 = self.conv4.bias primals_12 = self.conv5.weight primals_13 = self.conv5.bias primals_14 = self.conv6.weight primals_15 = self.conv6.bias primals_16 = self.conv7.weight primals_17 = self.conv7.bias primals_18 = self.conv8.weight primals_19 = self.conv8.bias primals_20 = self.conv9.weight primals_21 = self.conv9.bias primals_24 = self.conv10.weight primals_23 = self.conv10.bias primals_28 = self.conv11.weight primals_27 = self.conv11.bias primals_32 = self.conv12.weight primals_31 = self.conv12.bias primals_36 = self.conv13.weight primals_35 = self.conv13.bias primals_38 = self.conv14.weight primals_39 = self.conv14.bias primals_22 = self.upconv0.weight primals_25 = self.upconv0.bias primals_26 = self.upconv1.weight primals_29 = self.upconv1.bias primals_30 = self.upconv2.weight primals_33 = self.upconv2.bias primals_34 = self.upconv3.weight primals_37 = self.upconv3.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, primals_18, primals_19, primals_20, primals_21, primals_22, primals_23, primals_24, primals_25, primals_26, primals_27, primals_28, primals_29, primals_30, primals_31, primals_32, primals_33, primals_34, primals_35, primals_36, primals_37, primals_38, primals_39]) return output[0]
TerenceChen95/Retina-Unet-Pytorch
UNET
false
18,067
[ "MIT" ]
5
fad5a9a0bcab5d81a0f1bb2537b9a2ead87828ca
https://github.com/TerenceChen95/Retina-Unet-Pytorch/tree/fad5a9a0bcab5d81a0f1bb2537b9a2ead87828ca
MNIST_CNN
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data class MNIST_CNN(nn.Module): def __init__(self): super(MNIST_CNN, self).__init__() self.conv1 = nn.Conv2d(1, 64, 3, 1, padding=1) self.conv2 = nn.Conv2d(64, 128, 3, stride=2, padding=1) self.conv3 = nn.Conv2d(128, 128, 3, 1, padding=1) self.conv4 = nn.Conv2d(128, 128, 3, 1, padding=1) self.bn0 = nn.GroupNorm(8, 64) self.bn1 = nn.GroupNorm(8, 128) self.bn2 = nn.GroupNorm(8, 128) self.bn3 = nn.GroupNorm(8, 128) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.bn0(x) x = self.conv2(x) x = F.relu(x) x = self.bn1(x) x = self.conv3(x) x = F.relu(x) x = self.bn2(x) x = self.conv4(x) x = F.relu(x) x = self.bn3(x) x = self.avgpool(x) x = x.view(len(x), -1) return x 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 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_0(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 % 64 y1 = yindex // 64 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask) @triton.jit def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): xnumel = 9 yoffset = tl.program_id(1) * 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_2(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 256 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 % 64 y1 = yindex // 64 tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (y0 + 64 * x2 + 262144 * y1), tmp2, ymask) @triton.jit def triton_per_fused_native_group_norm_3(in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 128 xoffset = tl.program_id(0) * XBLOCK xindex = 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) r3 = rindex x0 = xindex % 32 x1 = xindex // 32 % 64 x2 = xindex // 2048 x4 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * ((r3 + 128 * x1) % 4096) + 262144 * x2 + (r3 + 128 * x1) // 4096), None, eviction_policy= 'evict_last') tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp7 = tl.sum(tmp5, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 128, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp3 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.sum(tmp13, 1)[:, None] tl.store(out_ptr0 + x4, tmp10, None) tl.store(out_ptr1 + x4, tmp15, None) tl.store(out_ptr2 + x4, tmp9, None) @triton.jit def triton_per_fused_native_group_norm_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 128 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 % 32 x1 = xindex // 32 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 32 * r2 + 2048 * x1), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (x0 + 32 * r2 + 2048 * x1), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (x0 + 32 * r2 + 2048 * x1), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp15 = tmp12[:, None] tl.store(out_ptr0 + x3, tmp13, xmask) tl.store(out_ptr1 + x3, tmp14, xmask) tl.store(out_ptr2 + x3, tmp15, xmask) @triton.jit def triton_per_fused_native_group_norm_5(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 32 RBLOCK: tl.constexpr = 4 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 + 4 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 4 * x0), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (r1 + 4 * x0), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp12[:, None] tmp16 = 32768.0 tmp17 = tmp14 / tmp16 tmp18 = 1e-05 tmp19 = tmp17 + tmp18 tmp20 = libdevice.rsqrt(tmp19) tl.store(out_ptr2 + x0, tmp20, xmask) tl.store(out_ptr0 + x0, tmp13, xmask) tl.store(out_ptr1 + x0, tmp14, xmask) @triton.jit def triton_poi_fused_native_group_norm_6(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 % 64 x2 = xindex // 262144 tmp0 = tl.load(in_ptr0 + x3, None) tmp3 = tl.load(in_ptr1 + (8 * x2 + x0 // 8), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr2 + (8 * x2 + x0 // 8), None, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr3 + x0, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 - tmp3 tmp6 = 32768.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp4 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tl.store(out_ptr0 + x3, tmp15, None) @triton.jit def triton_poi_fused_convolution_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 tl.store(in_out_ptr0 + x2, tmp2, None) @triton.jit def triton_per_fused_native_group_norm_8(in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 128 xoffset = tl.program_id(0) * XBLOCK xindex = 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) r3 = rindex x0 = xindex % 16 x1 = xindex // 16 % 64 x2 = xindex // 1024 x4 = xindex tmp0 = tl.load(in_ptr0 + (8 * x0 + 128 * ((r3 + 128 * x1) % 1024) + 131072 * x2 + (r3 + 128 * x1) // 1024), None, eviction_policy= 'evict_last') tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp7 = tl.sum(tmp5, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 128, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp3 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.sum(tmp13, 1)[:, None] tl.store(out_ptr0 + x4, tmp10, None) tl.store(out_ptr1 + x4, tmp15, None) tl.store(out_ptr2 + x4, tmp9, None) @triton.jit def triton_per_fused_native_group_norm_9(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, 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 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp15 = tmp12[:, None] tl.store(out_ptr0 + x3, tmp13, xmask) tl.store(out_ptr1 + x3, tmp14, xmask) tl.store(out_ptr2 + x3, tmp15, xmask) @triton.jit def triton_per_fused_native_group_norm_10(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 32 RBLOCK: tl.constexpr = 2 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 + 2 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 2 * x0), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (r1 + 2 * x0), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp12[:, None] tmp16 = 16384.0 tmp17 = tmp14 / tmp16 tmp18 = 1e-05 tmp19 = tmp17 + tmp18 tmp20 = libdevice.rsqrt(tmp19) tl.store(out_ptr2 + x0, tmp20, xmask) tl.store(out_ptr0 + x0, tmp13, xmask) tl.store(out_ptr1 + x0, tmp14, xmask) @triton.jit def triton_poi_fused_native_group_norm_11(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 % 128 x2 = xindex // 131072 tmp0 = tl.load(in_ptr0 + x3, None) tmp3 = tl.load(in_ptr1 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr2 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr3 + x0, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 - tmp3 tmp6 = 16384.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp4 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tl.store(out_ptr0 + x3, tmp15, None) @triton.jit def triton_red_fused_mean_native_group_norm_12(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr): rnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rbase = tl.arange(0, RBLOCK)[None, :] x0 = xindex % 128 x4 = xindex // 128 x2 = xindex // 1024 tmp3 = tl.load(in_ptr1 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr2 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr3 + x0, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') _tmp17 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) x5 = xindex for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r3 = rindex tmp0 = tl.load(in_ptr0 + (x0 + 128 * r3 + 4096 * (r3 % 32 // 32) + 16384 * x4), rmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 - tmp3 tmp6 = 16384.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp4 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK]) tmp18 = _tmp17 + tmp16 _tmp17 = tl.where(rmask, tmp18, _tmp17) tmp17 = tl.sum(_tmp17, 1)[:, None] tl.store(out_ptr0 + x5, tmp17, None) @triton.jit def triton_per_fused_mean_native_group_norm_13(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 512 RBLOCK: tl.constexpr = 8 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 % 128 x1 = xindex // 128 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 128 * r2 + 1024 * x1), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp5 = 1024.0 tmp6 = tmp4 / tmp5 tl.debug_barrier() tl.store(in_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, primals_14, primals_15, primals_16, primals_17) = args args.clear() assert_size_stride(primals_1, (64, 1, 3, 3), (9, 9, 3, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1)) assert_size_stride(primals_4, (64,), (1,)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (128, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (128,), (1,)) assert_size_stride(primals_9, (128,), (1,)) assert_size_stride(primals_10, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_11, (128,), (1,)) assert_size_stride(primals_12, (128,), (1,)) assert_size_stride(primals_13, (128,), (1,)) assert_size_stride(primals_14, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_15, (128,), (1,)) assert_size_stride(primals_16, (128,), (1,)) assert_size_stride(primals_17, (128,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch .float32) get_raw_stream(0) triton_poi_fused_0[grid(8192, 9)](primals_6, buf0, 8192, 9, XBLOCK= 16, YBLOCK=64, num_warps=4, num_stages=1) del primals_6 buf1 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_1[grid(16384, 9)](primals_10, buf1, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_10 buf2 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_1[grid(16384, 9)](primals_14, buf2, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_14 buf3 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 64, 64, 64), (262144, 4096, 64, 1)) buf4 = empty_strided_cuda((4, 64, 64, 64), (262144, 1, 4096, 64), torch.float32) triton_poi_fused_convolution_2[grid(256, 4096)](buf3, primals_2, buf4, 256, 4096, XBLOCK=16, YBLOCK=256, num_warps=8, num_stages=1) del primals_2 buf5 = empty_strided_cuda((4, 8, 1, 1, 4, 64), (2048, 4, 8192, 8192, 1, 32), torch.float32) buf6 = empty_strided_cuda((4, 8, 1, 1, 4, 64), (2048, 4, 8192, 8192, 1, 32), torch.float32) buf7 = empty_strided_cuda((4, 8, 1, 1, 4, 64), (2048, 4, 8192, 8192, 1, 32), torch.float32) triton_per_fused_native_group_norm_3[grid(8192)](buf4, buf5, buf6, buf7, 8192, 128, XBLOCK=8, num_warps=8, num_stages=1) buf8 = empty_strided_cuda((4, 8, 1, 1, 4), (32, 4, 128, 128, 1), torch.float32) buf9 = empty_strided_cuda((4, 8, 1, 1, 4), (32, 4, 128, 128, 1), torch.float32) buf10 = empty_strided_cuda((4, 8, 1, 1, 4), (32, 4, 128, 128, 1), torch.float32) triton_per_fused_native_group_norm_4[grid(128)](buf5, buf6, buf7, buf8, buf9, buf10, 128, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf5 del buf6 del buf7 buf11 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf12 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf15 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_5[grid(32)](buf8, buf9, buf10, buf11, buf12, buf15, 32, 4, XBLOCK=32, num_warps=2, num_stages=1) del buf10 del buf8 del buf9 buf14 = reinterpret_tensor(buf3, (4, 64, 64, 64), (262144, 1, 4096, 64), 0) del buf3 triton_poi_fused_native_group_norm_6[grid(1048576)](buf4, buf11, buf12, primals_4, primals_5, buf14, 1048576, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf16 = extern_kernels.convolution(buf14, buf0, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf16, (4, 128, 32, 32), (131072, 1, 4096, 128)) buf17 = buf16 del buf16 triton_poi_fused_convolution_7[grid(524288)](buf17, primals_7, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf18 = empty_strided_cuda((4, 8, 1, 1, 2, 64), (1024, 2, 4096, 4096, 1, 16), torch.float32) buf19 = empty_strided_cuda((4, 8, 1, 1, 2, 64), (1024, 2, 4096, 4096, 1, 16), torch.float32) buf20 = empty_strided_cuda((4, 8, 1, 1, 2, 64), (1024, 2, 4096, 4096, 1, 16), torch.float32) triton_per_fused_native_group_norm_8[grid(4096)](buf17, buf18, buf19, buf20, 4096, 128, XBLOCK=8, num_warps=8, num_stages=1) buf21 = empty_strided_cuda((4, 8, 1, 1, 2), (16, 2, 64, 64, 1), torch.float32) buf22 = empty_strided_cuda((4, 8, 1, 1, 2), (16, 2, 64, 64, 1), torch.float32) buf23 = empty_strided_cuda((4, 8, 1, 1, 2), (16, 2, 64, 64, 1), torch.float32) triton_per_fused_native_group_norm_9[grid(64)](buf18, buf19, buf20, buf21, buf22, buf23, 64, 64, XBLOCK=1, num_warps=2, num_stages=1) buf24 = buf12 del buf12 buf25 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf28 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_10[grid(32)](buf21, buf22, buf23, buf24, buf25, buf28, 32, 2, XBLOCK=32, num_warps=2, num_stages=1) buf27 = empty_strided_cuda((4, 128, 32, 32), (131072, 1, 4096, 128), torch.float32) triton_poi_fused_native_group_norm_11[grid(524288)](buf17, buf24, buf25, primals_8, primals_9, buf27, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_9 buf29 = extern_kernels.convolution(buf27, buf1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf29, (4, 128, 32, 32), (131072, 1, 4096, 128)) buf30 = buf29 del buf29 triton_poi_fused_convolution_7[grid(524288)](buf30, primals_11, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_11 buf31 = buf20 del buf20 buf32 = buf19 del buf19 buf33 = buf18 del buf18 triton_per_fused_native_group_norm_8[grid(4096)](buf30, buf31, buf32, buf33, 4096, 128, XBLOCK=8, num_warps=8, num_stages=1) buf34 = buf23 del buf23 buf35 = buf22 del buf22 buf36 = buf21 del buf21 triton_per_fused_native_group_norm_9[grid(64)](buf31, buf32, buf33, buf34, buf35, buf36, 64, 64, XBLOCK=1, num_warps=2, num_stages=1) buf37 = buf25 del buf25 buf38 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf41 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_10[grid(32)](buf34, buf35, buf36, buf37, buf38, buf41, 32, 2, XBLOCK=32, num_warps=2, num_stages=1) buf40 = empty_strided_cuda((4, 128, 32, 32), (131072, 1, 4096, 128), torch.float32) triton_poi_fused_native_group_norm_11[grid(524288)](buf30, buf37, buf38, primals_12, primals_13, buf40, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_13 buf42 = extern_kernels.convolution(buf40, buf2, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf42, (4, 128, 32, 32), (131072, 1, 4096, 128)) buf43 = buf42 del buf42 triton_poi_fused_convolution_7[grid(524288)](buf43, primals_15, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_15 buf44 = buf33 del buf33 buf45 = buf32 del buf32 buf46 = buf31 del buf31 triton_per_fused_native_group_norm_8[grid(4096)](buf43, buf44, buf45, buf46, 4096, 128, XBLOCK=8, num_warps=8, num_stages=1) buf47 = buf36 del buf36 buf48 = buf35 del buf35 buf49 = buf34 del buf34 triton_per_fused_native_group_norm_9[grid(64)](buf44, buf45, buf46, buf47, buf48, buf49, 64, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf44 del buf45 buf50 = buf38 del buf38 buf51 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf53 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_10[grid(32)](buf47, buf48, buf49, buf50, buf51, buf53, 32, 2, XBLOCK=32, num_warps=2, num_stages=1) del buf47 del buf48 del buf49 buf54 = reinterpret_tensor(buf46, (4, 128, 1, 1, 8), (1024, 1, 4096, 4096, 128), 0) del buf46 triton_red_fused_mean_native_group_norm_12[grid(4096)](buf43, buf50, buf51, primals_16, primals_17, buf54, 4096, 128, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1) del buf51 del primals_17 buf55 = empty_strided_cuda((4, 128, 1, 1), (128, 1, 512, 512), torch.float32) buf56 = buf55 del buf55 triton_per_fused_mean_native_group_norm_13[grid(512)](buf56, buf54, 512, 8, XBLOCK=64, num_warps=4, num_stages=1) del buf54 return (reinterpret_tensor(buf56, (4, 128), (128, 1), 0), primals_1, primals_3, primals_4, buf0, primals_8, buf1, primals_12, buf2, primals_16, buf4, buf14, reinterpret_tensor(buf11, (4, 8), (8, 1), 0), reinterpret_tensor(buf15, (4, 8), (8, 1), 0), buf17, buf27, reinterpret_tensor(buf24, (4, 8), (8, 1), 0), reinterpret_tensor( buf28, (4, 8), (8, 1), 0), buf30, buf40, reinterpret_tensor(buf37, (4, 8), (8, 1), 0), reinterpret_tensor(buf41, (4, 8), (8, 1), 0), buf43, reinterpret_tensor(buf50, (4, 8), (8, 1), 0), reinterpret_tensor(buf53, (4, 8), (8, 1), 0)) class MNIST_CNNNew(nn.Module): def __init__(self): super(MNIST_CNNNew, self).__init__() self.conv1 = nn.Conv2d(1, 64, 3, 1, padding=1) self.conv2 = nn.Conv2d(64, 128, 3, stride=2, padding=1) self.conv3 = nn.Conv2d(128, 128, 3, 1, padding=1) self.conv4 = nn.Conv2d(128, 128, 3, 1, padding=1) self.bn0 = nn.GroupNorm(8, 64) self.bn1 = nn.GroupNorm(8, 128) self.bn2 = nn.GroupNorm(8, 128) self.bn3 = nn.GroupNorm(8, 128) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_6 = self.conv2.weight primals_7 = self.conv2.bias primals_10 = self.conv3.weight primals_8 = self.conv3.bias primals_14 = self.conv4.weight primals_9 = self.conv4.bias primals_4 = self.bn0.weight primals_5 = self.bn0.bias primals_11 = self.bn1.weight primals_12 = self.bn1.bias primals_13 = self.bn2.weight primals_15 = self.bn2.bias primals_16 = self.bn3.weight primals_17 = self.bn3.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]
VinAIResearch/mDSDI
MNIST_CNN
false
18,068
[ "Apache-2.0" ]
9
8ec49085d8389ab490ec633c3ae4bf66be085366
https://github.com/VinAIResearch/mDSDI/tree/8ec49085d8389ab490ec633c3ae4bf66be085366
CNNBlock
import torch import torch.nn.functional as F import torch.nn as nn class CNNLayer(nn.Module): """Conv1d layer. nn.Conv1d layer require the input shape is (batch_size, in_channels, length), however, our input shape is (batch_size, length, in_channels), so we need to transpose our input data into (B, C, L_in) and send it to conv layer, and then transpose the conv output into (B, L_out, C). """ def __init__(self, in_dim, out_dim, win=3, pad=1): super().__init__() self.conv = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=win, padding=pad) def forward(self, x): """ Args: x: shape=(batch_size, max_seq_len, input_dim) """ x = x.permute(0, 2, 1) out = self.conv(x).permute(0, 2, 1) return out class MaxPool1d(nn.Module): def __init__(self, win=2, stride=None, pad=0): super().__init__() self.pooling = nn.MaxPool1d(kernel_size=win, stride=stride, padding=pad ) def forward(self, x): """ Args: x: shape=(batch_size, max_seq_len, dim) """ x = x.permute(0, 2, 1) x = self.pooling(x).permute(0, 2, 1) return x class CNNBlock(nn.Module): """Block of DPCNN. """ def __init__(self): super().__init__() hidden_dim = 250 self.pooling = MaxPool1d(3, 2, 1) self.conv1 = CNNLayer(hidden_dim, hidden_dim, 3, 1) self.conv2 = CNNLayer(hidden_dim, hidden_dim, 3, 1) def forward(self, x): res = self.pooling(x) x = self.conv1(F.relu(res)) x = self.conv2(F.relu(x)) out = x + res return out def get_inputs(): return [torch.rand([4, 250, 250])] 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 125000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 250 % 125 x0 = xindex % 250 x3 = xindex // 250 x4 = xindex tmp0 = tl.full([1], 0, tl.int64) tmp1 = tmp0 >= tmp0 tmp2 = tl.full([1], 1, tl.int64) tmp3 = tmp0 < tmp2 tmp4 = tmp1 & tmp3 tmp5 = -1 + 2 * x1 tmp6 = tmp5 >= tmp0 tmp7 = tl.full([1], 250, tl.int64) tmp8 = tmp5 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tmp4 & tmp9 tmp11 = tl.load(in_ptr0 + (-250 + x0 + 500 * x3), tmp10 & xmask, other= float('-inf')) tmp12 = 2 * x1 tmp13 = tmp12 >= tmp0 tmp14 = tmp12 < tmp7 tmp15 = tmp13 & tmp14 tmp16 = tmp4 & tmp15 tmp17 = tl.load(in_ptr0 + (x0 + 500 * x3), tmp16 & xmask, other=float( '-inf')) tmp18 = triton_helpers.maximum(tmp17, tmp11) tmp19 = 1 + 2 * x1 tmp20 = tmp19 >= tmp0 tmp21 = tmp19 < tmp7 tmp22 = tmp20 & tmp21 tmp23 = tmp4 & tmp22 tmp24 = tl.load(in_ptr0 + (250 + x0 + 500 * x3), tmp23 & xmask, other= float('-inf')) tmp25 = triton_helpers.maximum(tmp24, tmp18) tmp26 = tl.full([1], 0, tl.int32) tmp27 = triton_helpers.maximum(tmp26, tmp25) tl.store(out_ptr0 + x4, tmp27, xmask) @triton.jit def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 1000 xnumel = 125 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 % 250 y1 = yindex // 250 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 250 * x2 + 31250 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 125 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_relu_threshold_backward_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 500 xnumel = 250 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 % 125 y1 = yindex // 125 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 125 * x2 + 31250 * y1), xmask & ymask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask, 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 + 250 * y3), tmp4, xmask & ymask) tl.store(out_ptr1 + (y0 + 125 * x2 + 31360 * y1), tmp6, xmask & ymask) @triton.jit def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, in_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 500 xnumel = 250 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 % 125 y1 = yindex // 125 y3 = yindex tmp0 = tl.load(in_out_ptr0 + (y0 + 125 * x2 + 31250 * y1), xmask & ymask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int64) tmp4 = tmp3 >= tmp3 tmp5 = tl.full([1, 1], 1, tl.int64) tmp6 = tmp3 < tmp5 tmp7 = tmp4 & tmp6 tmp8 = -1 + 2 * y0 tmp9 = tmp8 >= tmp3 tmp10 = tl.full([1, 1], 250, tl.int64) tmp11 = tmp8 < tmp10 tmp12 = tmp9 & tmp11 tmp13 = tmp7 & tmp12 tmp14 = tl.load(in_ptr1 + (-250 + x2 + 500 * y3), tmp13 & xmask & ymask, eviction_policy='evict_last', other=float('-inf')) tmp15 = 2 * y0 tmp16 = tmp15 >= tmp3 tmp17 = tmp15 < tmp10 tmp18 = tmp16 & tmp17 tmp19 = tmp7 & tmp18 tmp20 = tl.load(in_ptr1 + (x2 + 500 * y3), tmp19 & xmask & ymask, eviction_policy='evict_last', other=float('-inf')) tmp21 = triton_helpers.maximum(tmp20, tmp14) tmp22 = 1 + 2 * y0 tmp23 = tmp22 >= tmp3 tmp24 = tmp22 < tmp10 tmp25 = tmp23 & tmp24 tmp26 = tmp7 & tmp25 tmp27 = tl.load(in_ptr1 + (250 + x2 + 500 * y3), tmp26 & xmask & ymask, eviction_policy='evict_last', other=float('-inf')) tmp28 = triton_helpers.maximum(tmp27, tmp21) tmp29 = tmp2 + tmp28 tl.debug_barrier() tl.store(in_out_ptr0 + (y0 + 125 * x2 + 31250 * y1), tmp29, xmask & ymask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 250, 250), (62500, 250, 1)) assert_size_stride(primals_2, (250, 250, 3), (750, 3, 1)) assert_size_stride(primals_3, (250,), (1,)) assert_size_stride(primals_4, (250, 250, 3), (750, 3, 1)) assert_size_stride(primals_5, (250,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 125, 250), (31250, 250, 1), torch.float32 ) get_raw_stream(0) triton_poi_fused_relu_0[grid(125000)](primals_1, buf0, 125000, XBLOCK=512, num_warps=8, num_stages=1) buf1 = empty_strided_cuda((4, 250, 125), (31250, 125, 1), torch.float32 ) triton_poi_fused_convolution_1[grid(1000, 125)](buf0, buf1, 1000, 125, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf2, (4, 250, 125), (31250, 125, 1)) buf3 = reinterpret_tensor(buf1, (4, 125, 250), (31250, 250, 1), 0) del buf1 buf7 = empty_strided_cuda((4, 125, 250), (31360, 1, 125), torch.bool) triton_poi_fused_relu_threshold_backward_2[grid(500, 250)](buf2, primals_3, buf3, buf7, 500, 250, XBLOCK=2, YBLOCK=512, num_warps=4, num_stages=1) del primals_3 buf4 = buf2 del buf2 triton_poi_fused_convolution_1[grid(1000, 125)](buf3, buf4, 1000, 125, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del buf3 buf5 = extern_kernels.convolution(buf4, primals_4, stride=(1,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf5, (4, 250, 125), (31250, 125, 1)) buf6 = reinterpret_tensor(buf5, (4, 125, 250), (31250, 1, 125), 0) del buf5 triton_poi_fused_add_3[grid(500, 250)](buf6, primals_5, primals_1, 500, 250, XBLOCK=256, YBLOCK=4, num_warps=4, num_stages=1) del primals_1 del primals_5 return buf6, primals_2, primals_4, reinterpret_tensor(buf0, (4, 250, 125), (31250, 1, 250), 0), buf4, buf7 class CNNLayer(nn.Module): """Conv1d layer. nn.Conv1d layer require the input shape is (batch_size, in_channels, length), however, our input shape is (batch_size, length, in_channels), so we need to transpose our input data into (B, C, L_in) and send it to conv layer, and then transpose the conv output into (B, L_out, C). """ def __init__(self, in_dim, out_dim, win=3, pad=1): super().__init__() self.conv = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=win, padding=pad) def forward(self, x): """ Args: x: shape=(batch_size, max_seq_len, input_dim) """ x = x.permute(0, 2, 1) out = self.conv(x).permute(0, 2, 1) return out class MaxPool1d(nn.Module): def __init__(self, win=2, stride=None, pad=0): super().__init__() self.pooling = nn.MaxPool1d(kernel_size=win, stride=stride, padding=pad ) def forward(self, x): """ Args: x: shape=(batch_size, max_seq_len, dim) """ x = x.permute(0, 2, 1) x = self.pooling(x).permute(0, 2, 1) return x class CNNBlockNew(nn.Module): """Block of DPCNN. """ def __init__(self): super().__init__() hidden_dim = 250 self.pooling = MaxPool1d(3, 2, 1) self.conv1 = CNNLayer(hidden_dim, hidden_dim, 3, 1) self.conv2 = CNNLayer(hidden_dim, hidden_dim, 3, 1) def forward(self, input_0): primals_2 = self.conv1.conv.weight primals_3 = self.conv1.conv.bias primals_4 = self.conv2.conv.weight primals_5 = self.conv2.conv.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
WiseDoge/Text-Classification-PyTorch
CNNBlock
false
18,069
[ "MIT" ]
6
9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
https://github.com/WiseDoge/Text-Classification-PyTorch/tree/9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
AttnLayer
import torch import torch.nn.functional as F import torch.nn as nn class AttnLayer(nn.Module): """Attention layer. w is context vector. Formula: $$ v_i=tanh(Wh_i+b)\\ lpha_i = v_i^Tw\\ lpha_i = softmax(lpha_i)\\ Vec = \\sum_0^L lpha_ih_i $$ """ def __init__(self, hidden_dim, attn_dim): super().__init__() self.weight = nn.Linear(hidden_dim, attn_dim) self.context = nn.Parameter(torch.randn(attn_dim)) def forward(self, x): """ x: shape=(batch_size, max_len, hidden_dim) """ query = self.weight(x).tanh() scores = torch.einsum('bld,d->bl', query, self.context) scores = F.softmax(scores, dim=-1) attn_vec = torch.einsum('bl,blh->bh', scores, x) return attn_vec def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'hidden_dim': 4, 'attn_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_tanh_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 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) @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 = 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 = 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) def call(args): primals_1, primals_2, primals_3, primals_4 = 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), (16, 4, 1)) assert_size_stride(primals_4, (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_3, (16, 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), (16, 4, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_tanh_0[grid(64)](buf1, primals_2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_2 buf2 = empty_strided_cuda((1, 16, 1), (16, 1, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf1, (1, 16, 4), (64, 4, 1), 0), reinterpret_tensor(primals_4, (1, 4, 1), (4, 1, 1), 0), out =buf2) buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__softmax_1[grid(16)](buf2, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__softmax_2[grid(16)](buf3, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) buf5 = reinterpret_tensor(buf3, (4, 1, 4), (4, 4, 1), 0) del buf3 extern_kernels.bmm(reinterpret_tensor(buf4, (4, 1, 4), (4, 0, 1), 0 ), primals_3, out=buf5) del buf4 return reinterpret_tensor(buf5, (4, 4), (4, 1), 0 ), primals_3, buf1, buf2, reinterpret_tensor(primals_4, (1, 1, 4), (4, 1, 1), 0) class AttnLayerNew(nn.Module): """Attention layer. w is context vector. Formula: $$ v_i=tanh(Wh_i+b)\\ lpha_i = v_i^Tw\\ lpha_i = softmax(lpha_i)\\ Vec = \\sum_0^L lpha_ih_i $$ """ def __init__(self, hidden_dim, attn_dim): super().__init__() self.weight = nn.Linear(hidden_dim, attn_dim) self.context = nn.Parameter(torch.randn(attn_dim)) def forward(self, input_0): primals_2 = self.context primals_1 = self.weight.weight primals_4 = self.weight.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
WiseDoge/Text-Classification-PyTorch
AttnLayer
false
18,070
[ "MIT" ]
6
9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
https://github.com/WiseDoge/Text-Classification-PyTorch/tree/9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
knn_ContrastiveLoss
import torch import torch.nn as nn from torch.autograd import * import torch.nn.init def cosine_sim(im, s): """Cosine similarity between all the image and sentence pairs """ return im.mm(s.t()) def order_sim(im, s): """Order embeddings similarity measure $max(0, s-im)$ """ YmX = s.unsqueeze(1).expand(s.size(0), im.size(0), s.size(1) ) - im.unsqueeze(0).expand(s.size(0), im.size(0), s.size(1)) score = -YmX.clamp(min=0).pow(2).sum(2).sqrt().t() return score class knn_ContrastiveLoss(nn.Module): """ Compute contrastive loss """ def __init__(self, margin=0, measure=False): super(knn_ContrastiveLoss, self).__init__() self.margin = margin if measure == 'order': self.sim = order_sim else: self.sim = cosine_sim def forward(self, im, knn_im, s): scores = self.sim(im, s) diagonal = scores.diag().view(im.size(0), 1) knn_scores = self.sim(knn_im, s) knn_diagonal = knn_scores.diag().view(knn_im.size(0), 1) cost = (self.margin + knn_diagonal - diagonal).clamp(min=0) return cost def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([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.autograd import * import torch.nn.init assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_add_clamp_sub_0(in_ptr0, in_ptr1, 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 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + 5 * x0, xmask, eviction_policy='evict_last') tmp1 = 0.0 tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp5 = triton_helpers.maximum(tmp4, tmp1) tl.store(out_ptr0 + x0, tmp5, 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, 1)) assert_size_stride(arg2_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) extern_kernels.mm(arg2_1, reinterpret_tensor(arg1_1, (4, 4), (1, 4), 0), out=buf0) del arg2_1 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(arg0_1, reinterpret_tensor(arg1_1, (4, 4), (1, 4), 0), out=buf1) del arg0_1 del arg1_1 buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_clamp_sub_0[grid(4)](buf0, buf1, buf2, 4, XBLOCK=4, num_warps=1, num_stages=1) del buf0 del buf1 return buf2, def cosine_sim(im, s): """Cosine similarity between all the image and sentence pairs """ return im.mm(s.t()) def order_sim(im, s): """Order embeddings similarity measure $max(0, s-im)$ """ YmX = s.unsqueeze(1).expand(s.size(0), im.size(0), s.size(1) ) - im.unsqueeze(0).expand(s.size(0), im.size(0), s.size(1)) score = -YmX.clamp(min=0).pow(2).sum(2).sqrt().t() return score class knn_ContrastiveLossNew(nn.Module): """ Compute contrastive loss """ def __init__(self, margin=0, measure=False): super(knn_ContrastiveLossNew, self).__init__() self.margin = margin if measure == 'order': self.sim = order_sim else: self.sim = cosine_sim def forward(self, input_0, input_1, input_2): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
WuJie1010/Fine-Grained-Image-Captioning
knn_ContrastiveLoss
false
18,071
[ "MIT" ]
9
340bc1868634f3bf0fdd62d439fec32ee1b45407
https://github.com/WuJie1010/Fine-Grained-Image-Captioning/tree/340bc1868634f3bf0fdd62d439fec32ee1b45407
HuberLoss
import torch from torch import nn class HuberLoss(nn.Module): def __init__(self, delta=1): super().__init__() self.huber_loss_delta1 = nn.SmoothL1Loss() self.delta = delta def forward(self, x, x_hat): loss = self.huber_loss_delta1(x / self.delta, x_hat / self.delta) return loss * self.delta * self.delta 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 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_div_mul_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 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp3 * tmp1 tmp5 = tmp2 - tmp4 tmp6 = tl_math.abs(tmp5) tmp7 = tmp6 < tmp1 tmp8 = tmp6 * tmp6 tmp9 = 0.5 tmp10 = tmp8 * tmp9 tmp11 = tmp10 * tmp1 tmp12 = tmp6 - tmp9 tmp13 = tl.where(tmp7, tmp11, tmp12) tmp14 = tl.broadcast_to(tmp13, [RBLOCK]) tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0)) tmp17 = 256.0 tmp18 = tmp16 / tmp17 tmp19 = tmp18 * tmp1 tmp20 = tmp19 * tmp1 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_div_mul_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 HuberLossNew(nn.Module): def __init__(self, delta=1): super().__init__() self.huber_loss_delta1 = nn.SmoothL1Loss() self.delta = delta def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
UT-Austin-RPL/maple
HuberLoss
false
18,072
[ "MIT" ]
9
aef9fe9869945df5bbd1b02fd40813aac135cf5a
https://github.com/UT-Austin-RPL/maple/tree/aef9fe9869945df5bbd1b02fd40813aac135cf5a
Conv1dSamePadding
import torch import torch.nn.functional as F import torch.nn as nn class Conv1dSamePadding(nn.Conv1d): """ 1D convolutional layer with "same" padding (no downsampling), that is also compatible with strides > 1 """ def __init__(self, *args, **kwargs): super(Conv1dSamePadding, self).__init__(*args, **kwargs) def forward(self, inputs): """ Given an input of size [B, CI, WI], return an output [B, CO, WO], where WO = [CI + 2P - K - (K - 1) * (D - 1)] / S + 1, by computing P on-the-fly ay forward time B: batch size CI: input channels WI: input width CO: output channels WO: output width P: padding K: kernel size D: dilation S: stride """ padding = (self.stride[0] * (inputs.shape[-1] - 1) - inputs.shape[- 1] + self.kernel_size[0] + (self.dilation[0] - 1) * (self. kernel_size[0] - 1)) // 2 return self._conv_forward(F.pad(inputs, (padding, padding)), self. weight, self.bias) def get_inputs(): return [torch.rand([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 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_constant_pad_nd_0(in_ptr0, 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 = -1 + x0 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1), tmp5 & xmask, other=0.0) 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 = 12 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 3 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x1, 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, 1)) assert_size_stride(primals_2, (4, 4, 4), (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, 6), (6, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(24)](primals_1, buf0, 24, XBLOCK=32, num_warps=1, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (1, 4, 6 ), (0, 6, 1), 0), primals_2, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=(0,), groups=1, bias=None) assert_size_stride(buf1, (1, 4, 3), (12, 3, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_1[grid(12)](buf2, primals_3, 12, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 return reinterpret_tensor(buf2, (4, 3), (3, 1), 0 ), primals_2, reinterpret_tensor(buf0, (1, 4, 6), (24, 6, 1), 0) class Conv1dSamePaddingNew(nn.Conv1d): """ 1D convolutional layer with "same" padding (no downsampling), that is also compatible with strides > 1 """ def __init__(self, *args, **kwargs): super(Conv1dSamePaddingNew, self).__init__(*args, **kwargs) 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]
Wadaboa/titanet
Conv1dSamePadding
false
18,073
[ "MIT" ]
4
b07e3074e79ea8c1129fb0adb8315e06bb4943ea
https://github.com/Wadaboa/titanet/tree/b07e3074e79ea8c1129fb0adb8315e06bb4943ea
Wang
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F class Wang(nn.Module): """Neural network model for linear combination of EDU scores. """ def __init__(self, nrels): """Class constructor. Args: nrels (int): total number of relations """ super(Wang, self).__init__() d = np.ones((nrels, 1), dtype=np.float32) d[0] = 0 self.d = nn.Parameter(torch.tensor(d)) self.b = nn.Parameter(torch.tensor(0.5)) def forward(self, rel_indices, x): rel_coeffs = self.d[rel_indices] ret = torch.sum(rel_coeffs * x, dim=1) + self.b return F.softmax(ret, dim=-1) def get_inputs(): return [torch.ones([4], dtype=torch.int64), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'nrels': 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 numpy as np 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_index_mul_sum_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 x1 = xindex // 4 % 4 x2 = xindex // 16 x3 = xindex % 16 x4 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr2 + (x3 + 64 * x2), xmask) tmp9 = tl.load(in_ptr2 + (16 + x3 + 64 * x2), xmask) tmp12 = tl.load(in_ptr2 + (32 + x3 + 64 * x2), xmask) tmp15 = tl.load(in_ptr2 + (48 + x3 + 64 * x2), xmask) tmp18 = tl.load(in_ptr3 + 0) tmp19 = tl.broadcast_to(tmp18, [XBLOCK]) tmp1 = tl.full([XBLOCK], 4, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask, 'index out of bounds: 0 <= tmp4 < 4') tmp6 = tl.load(in_ptr1 + tmp4, xmask, eviction_policy='evict_last') tmp8 = tmp6 * tmp7 tmp10 = tmp6 * tmp9 tmp11 = tmp8 + tmp10 tmp13 = tmp6 * tmp12 tmp14 = tmp11 + tmp13 tmp16 = tmp6 * tmp15 tmp17 = tmp14 + tmp16 tmp20 = tmp17 + tmp19 tl.store(out_ptr0 + x4, tmp20, 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) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_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, (), ()) 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_add_index_mul_sum_0[grid(64)](primals_2, primals_1, primals_3, primals_4, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_4 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(64)](buf0, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) buf2 = buf0 del buf0 triton_poi_fused__softmax_2[grid(64)](buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf1 return buf2, primals_2, primals_3, buf2 class WangNew(nn.Module): """Neural network model for linear combination of EDU scores. """ def __init__(self, nrels): """Class constructor. Args: nrels (int): total number of relations """ super(WangNew, self).__init__() d = np.ones((nrels, 1), dtype=np.float32) d[0] = 0 self.d = nn.Parameter(torch.tensor(d)) self.b = nn.Parameter(torch.tensor(0.5)) def forward(self, input_0, input_1): primals_1 = self.d primals_4 = self.b primals_2 = input_0 primals_3 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
WladimirSidorenko/DASA
Wang
false
18,074
[ "MIT" ]
7
618d9060a5fd6f567628c8dec5e26943c8c49ad4
https://github.com/WladimirSidorenko/DASA/tree/618d9060a5fd6f567628c8dec5e26943c8c49ad4
AdditiveAttention
import torch import torch.nn as nn import torch.nn.functional as F class AdditiveAttention(nn.Module): def __init__(self, encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim=None): super(AdditiveAttention, self).__init__() if internal_dim is None: internal_dim = int((encoder_hidden_state_dim + decoder_hidden_state_dim) / 2) self.w1 = nn.Linear(encoder_hidden_state_dim, internal_dim, bias=False) self.w2 = nn.Linear(decoder_hidden_state_dim, internal_dim, bias=False) self.v = nn.Linear(internal_dim, 1, bias=False) def score(self, encoder_state, decoder_state): return self.v(torch.tanh(self.w1(encoder_state) + self.w2( decoder_state))) def forward(self, encoder_states, decoder_state): score_vec = torch.cat([self.score(encoder_states[:, i], decoder_state) for i in range(encoder_states.shape[1])], dim=1) attention_probs = torch.unsqueeze(F.softmax(score_vec, dim=1), dim=2) final_context_vec = torch.sum(attention_probs * encoder_states, dim=1) return final_context_vec, attention_probs def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'encoder_hidden_state_dim': 4, 'decoder_hidden_state_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_mm_0(in_ptr0, 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 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_mm_1(in_ptr0, 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 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_mm_2(in_ptr0, 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 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_mm_3(in_ptr0, 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 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_add_tanh_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr): xnumel = 16 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.load(in_ptr1 + x2, xmask) tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tmp5 = tmp4 + tmp1 tmp6 = libdevice.tanh(tmp5) tmp8 = tmp7 + tmp1 tmp9 = libdevice.tanh(tmp8) tmp11 = tmp10 + tmp1 tmp12 = libdevice.tanh(tmp11) tl.store(out_ptr0 + x2, tmp3, xmask) tl.store(out_ptr1 + x2, tmp6, xmask) tl.store(out_ptr2 + x2, tmp9, xmask) tl.store(out_ptr3 + x2, tmp12, xmask) @triton.jit def triton_poi_fused__softmax_5(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_6(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_poi_fused_mul_sum_7(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 x1 = xindex // 4 x0 = xindex % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (12 + 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 tl.store(out_ptr0 + x2, tmp14, 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, 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, (1, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((1, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mm_0[grid(4)](primals_1, buf0, 4, XBLOCK=4, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((1, 4), (4, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_2, (4, 4), (1, 4 ), 0), out=buf1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_4, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf2) del primals_3 buf10 = buf0 del buf0 triton_poi_fused_mm_1[grid(4)](primals_1, buf10, 4, XBLOCK=4, num_warps=1, num_stages=1) buf11 = empty_strided_cuda((1, 4), (4, 1), torch.float32) extern_kernels.mm(buf10, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf11) buf4 = buf10 del buf10 triton_poi_fused_mm_2[grid(4)](primals_1, buf4, 4, XBLOCK=4, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((1, 4), (4, 1), torch.float32) extern_kernels.mm(buf4, reinterpret_tensor(primals_2, (4, 4), (1, 4 ), 0), out=buf5) buf7 = buf4 del buf4 triton_poi_fused_mm_3[grid(4)](primals_1, buf7, 4, XBLOCK=4, num_warps=1, num_stages=1) buf8 = empty_strided_cuda((1, 4), (4, 1), torch.float32) extern_kernels.mm(buf7, reinterpret_tensor(primals_2, (4, 4), (1, 4 ), 0), out=buf8) del buf7 del primals_2 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_add_tanh_4[grid(16)](buf1, buf2, buf5, buf8, buf11, buf3, buf6, buf9, buf12, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf1 del buf11 del buf5 del buf8 buf17 = buf2 del buf2 buf13 = reinterpret_tensor(buf17, (4, 1), (4, 1), 0) extern_kernels.mm(buf3, reinterpret_tensor(primals_5, (4, 1), (1, 4 ), 0), out=buf13) buf14 = reinterpret_tensor(buf17, (4, 1), (4, 1), 1) extern_kernels.mm(buf6, reinterpret_tensor(primals_5, (4, 1), (1, 4 ), 0), out=buf14) buf15 = reinterpret_tensor(buf17, (4, 1), (4, 1), 2) extern_kernels.mm(buf9, reinterpret_tensor(primals_5, (4, 1), (1, 4 ), 0), out=buf15) buf16 = reinterpret_tensor(buf17, (4, 1), (4, 1), 3) extern_kernels.mm(buf12, reinterpret_tensor(primals_5, (4, 1), (1, 4), 0), out=buf16) buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused__softmax_5[grid(16)](buf17, buf18, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf13 del buf14 del buf15 del buf16 buf19 = buf17 del buf17 triton_poi_fused__softmax_6[grid(16)](buf18, buf19, 16, XBLOCK=16, num_warps=1, num_stages=1) buf20 = buf18 del buf18 triton_poi_fused_mul_sum_7[grid(16)](buf19, primals_1, buf20, 16, XBLOCK=16, num_warps=1, num_stages=1) return buf20, reinterpret_tensor(buf19, (4, 4, 1), (4, 1, 1), 0 ), primals_1, primals_4, reinterpret_tensor(primals_1, (1, 4), (16, 4), 0), buf3, reinterpret_tensor(primals_1, (1, 4), (16, 4), 1 ), buf6, reinterpret_tensor(primals_1, (1, 4), (16, 4), 2 ), buf9, reinterpret_tensor(primals_1, (1, 4), (16, 4), 3 ), buf12, buf19, primals_5 class AdditiveAttentionNew(nn.Module): def __init__(self, encoder_hidden_state_dim, decoder_hidden_state_dim, internal_dim=None): super(AdditiveAttentionNew, self).__init__() if internal_dim is None: internal_dim = int((encoder_hidden_state_dim + decoder_hidden_state_dim) / 2) self.w1 = nn.Linear(encoder_hidden_state_dim, internal_dim, bias=False) self.w2 = nn.Linear(decoder_hidden_state_dim, internal_dim, bias=False) self.v = nn.Linear(internal_dim, 1, bias=False) def score(self, encoder_state, decoder_state): return self.v(torch.tanh(self.w1(encoder_state) + self.w2( decoder_state))) def forward(self, input_0, input_1): primals_1 = self.w1.weight primals_2 = self.w2.weight primals_5 = self.v.weight primals_3 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1]
Vision-CAIR/HalentNet
AdditiveAttention
false
18,075
[ "MIT" ]
4
dedef73c57c63aa580fc497fa42d512f4241a64b
https://github.com/Vision-CAIR/HalentNet/tree/dedef73c57c63aa580fc497fa42d512f4241a64b
SVM
import torch import torch.nn as nn class SVM(nn.Module): def __init__(self, hidden_size): super(SVM, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, x): y = self.sigmoid(self.linear1(x)) return y.view(-1) def get_inputs(): return [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 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_sigmoid_sigmoid_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 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) tmp5 = 1.0 tmp6 = tmp5 - tmp4 tmp7 = tmp4 * tmp6 tl.store(in_out_ptr0 + x0, tmp4, xmask) tl.store(out_ptr0 + x0, tmp7, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (1, 4), (4, 1)) assert_size_stride(primals_2, (1,), (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((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf0 buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_sigmoid_sigmoid_backward_0[grid(64)](buf1, primals_2, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_2 return reinterpret_tensor(buf1, (64,), (1,), 0), reinterpret_tensor( primals_3, (64, 4), (4, 1), 0), buf2 class SVMNew(nn.Module): def __init__(self, hidden_size): super(SVMNew, self).__init__() self.linear1 = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_1 = self.linear1.weight primals_2 = self.linear1.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
XIAOYEJIAYOU/GSAN
SVM
false
18,076
[ "MIT" ]
6
8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
https://github.com/XIAOYEJIAYOU/GSAN/tree/8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
MLP
import torch import torch.nn as nn class MLP(nn.Module): def __init__(self, num_actions): super(MLP, self).__init__() self.fc = nn.Linear(4, 128) self.logits = nn.Linear(128, num_actions) self.value = nn.Linear(128, 1) def forward(self, x): x = torch.relu(self.fc(x)) logits = self.logits(x) value = self.value(x) return logits, value def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_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_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 % 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) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, None) tl.store(out_ptr0 + x2, tmp6, 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, (128, 4), (4, 1)) assert_size_stride(primals_2, (128,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 128), (128, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (1, 128), (128, 1)) assert_size_stride(primals_7, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 128), (128, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 128), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0) del buf0 buf5 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf1, primals_2, buf5, 8192, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 128), (128, 1), 0), reinterpret_tensor(primals_4, (128, 4), (1, 128), 0), alpha=1, beta=1, out=buf2) del primals_5 buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 128), (128, 1), 0), reinterpret_tensor(primals_6, (128, 1), (1, 128), 0), alpha=1, beta=1, out=buf4) del primals_7 return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 128), (128, 1), 0 ), primals_6, primals_4, buf5 class MLPNew(nn.Module): def __init__(self, num_actions): super(MLPNew, self).__init__() self.fc = nn.Linear(4, 128) self.logits = nn.Linear(128, num_actions) self.value = nn.Linear(128, 1) def forward(self, input_0): primals_1 = self.fc.weight primals_2 = self.fc.bias primals_4 = self.logits.weight primals_5 = self.logits.bias primals_6 = self.value.weight primals_7 = self.value.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0], output[1]
XFFXFF/endorphin
MLP
false
18,077
[ "Apache-2.0" ]
5
a29d6faf76284e5346d900dfd4fdeda82c710744
https://github.com/XFFXFF/endorphin/tree/a29d6faf76284e5346d900dfd4fdeda82c710744
Attention
import torch import torch.nn as nn import torch.nn.functional as F class Attention(nn.Module): def __init__(self, n_hidden_enc, n_hidden_dec): super().__init__() self.h_hidden_enc = n_hidden_enc self.h_hidden_dec = n_hidden_dec self.W = nn.Linear(n_hidden_enc + n_hidden_dec, n_hidden_dec, bias= False) self.V = nn.Parameter(torch.rand(n_hidden_dec)) def forward(self, hidden_dec, last_layer_enc, attention_mask): """ PARAMS: hidden_dec: [b, n_hidden_dec] last_layer_enc: [b, seq_len, n_hidden_enc * 2] RETURN: att_weights: [b, src_seq_len] """ batch_size = last_layer_enc.size(0) src_seq_len = last_layer_enc.size(1) hidden_dec = hidden_dec.unsqueeze(1).repeat(1, src_seq_len, 1) tanh_W_s_h = torch.tanh(self.W(torch.cat((hidden_dec, last_layer_enc), dim=-1))) tanh_W_s_h = tanh_W_s_h.permute(0, 2, 1) V = self.V.repeat(batch_size, 1).unsqueeze(1) e = torch.bmm(V, tanh_W_s_h).squeeze(1) e = attention_mask + e att_weights = F.softmax(e, dim=1) return att_weights def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4, 4]) ] def get_init_inputs(): return [[], {'n_hidden_enc': 4, 'n_hidden_dec': 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_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x2 = xindex // 32 x3 = xindex // 8 x4 = 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 * x2 + 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 * x3 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x4, tmp10, xmask) @triton.jit def triton_poi_fused_tanh_1(in_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 tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp1 = libdevice.tanh(tmp0) tl.store(in_out_ptr0 + x0, tmp1, xmask) @triton.jit def triton_poi_fused_repeat_2(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 % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x2, tmp0, xmask) @triton.jit def triton_poi_fused__softmax_add_3(in_ptr0, in_ptr1, 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 x0 = xindex % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp3 + tmp1 tmp5 = triton_helpers.maximum(tmp2, tmp4) tmp7 = tmp6 + tmp1 tmp8 = triton_helpers.maximum(tmp5, tmp7) tmp10 = tmp9 + tmp1 tmp11 = triton_helpers.maximum(tmp8, tmp10) tmp12 = tmp2 - tmp11 tmp13 = tl_math.exp(tmp12) tmp14 = tmp4 - tmp11 tmp15 = tl_math.exp(tmp14) tmp16 = tmp13 + tmp15 tmp17 = tmp7 - tmp11 tmp18 = tl_math.exp(tmp17) tmp19 = tmp16 + tmp18 tmp20 = tmp10 - tmp11 tmp21 = tl_math.exp(tmp20) tmp22 = tmp19 + tmp21 tl.store(out_ptr0 + x2, tmp11, xmask) tl.store(out_ptr1 + x2, tmp22, xmask) @triton.jit def triton_poi_fused__softmax_add_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr3 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp5 = tl_math.exp(tmp4) tmp7 = tmp5 / tmp6 tl.store(out_ptr0 + x3, tmp7, 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, 8), (8, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(128)](primals_2, primals_1, buf0, 128, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 del primals_2 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (16, 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), (16, 4, 1), 0) del buf1 triton_poi_fused_tanh_1[grid(64)](buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_repeat_2[grid(16)](primals_4, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_4 buf4 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (4, 1, 4), (4, 0, 1), 0 ), reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), out=buf4) buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) buf6 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) triton_poi_fused__softmax_add_3[grid(64)](primals_5, buf4, buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1) buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_add_4[grid(256)](primals_5, buf4, buf5, buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf4 del buf5 del buf6 del primals_5 return buf7, reinterpret_tensor(buf0, (16, 8), (8, 1), 0 ), buf2, buf7, reinterpret_tensor(buf3, (4, 4, 1), (4, 1, 4), 0) class AttentionNew(nn.Module): def __init__(self, n_hidden_enc, n_hidden_dec): super().__init__() self.h_hidden_enc = n_hidden_enc self.h_hidden_dec = n_hidden_dec self.W = nn.Linear(n_hidden_enc + n_hidden_dec, n_hidden_dec, bias= False) self.V = nn.Parameter(torch.rand(n_hidden_dec)) def forward(self, input_0, input_1, input_2): primals_4 = self.V primals_3 = self.W.weight primals_2 = input_0 primals_1 = input_1 primals_5 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
VisualJoyce/ChengyuBERT
Attention
false
18,078
[ "MIT" ]
8
605db3a4b3241dd4d02baa41a68bf23b5b00b36d
https://github.com/VisualJoyce/ChengyuBERT/tree/605db3a4b3241dd4d02baa41a68bf23b5b00b36d
SEModule
import torch import torch.nn as nn class SEModule(nn.Module): def __init__(self, channels, reduction): super().__init__() self.avg_pool = nn.AdaptiveAvgPool3d(1) self.bottleneck = self._round_width(channels, reduction) self.fc1 = nn.Conv3d(channels, self.bottleneck, kernel_size=1, padding=0) self.relu = nn.ReLU() self.fc2 = nn.Conv3d(self.bottleneck, channels, kernel_size=1, padding=0) self.sigmoid = nn.Sigmoid() @staticmethod def _round_width(width, multiplier, min_width=8, divisor=8): width *= multiplier min_width = min_width or divisor width_out = max(min_width, int(width + divisor / 2) // divisor * divisor) if width_out < 0.9 * width: width_out += divisor return int(width_out) 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, 'reduction': 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 = 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) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp5 = 64.0 tmp6 = tmp4 / tmp5 tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_1(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 x0 = xindex tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask) 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 + x0, tmp4, xmask) tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_convolution_2(in_out_ptr0, in_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 = tl.load(in_out_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask) tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x0, 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 // 64 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, (16, 4, 1, 1, 1), (4, 1, 1, 1, 1)) assert_size_stride(primals_3, (16,), (1,)) assert_size_stride(primals_4, (4, 16, 1, 1, 1), (16, 1, 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, 1, 1, 1), (1, 4, 4, 4), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_mean_0[grid(4)](buf1, primals_1, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 1, 1, 1), (0, 1, 0, 0, 0), 0), primals_2, stride=(1, 1, 1), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf2, (1, 16, 1, 1, 1), (16, 1, 1, 1, 1)) buf3 = reinterpret_tensor(buf2, (16, 1, 1, 1), (1, 16, 16, 16), 0) del buf2 buf7 = empty_strided_cuda((16, 1, 1, 1), (1, 1, 1, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(16)](buf3, primals_3, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 buf4 = extern_kernels.convolution(reinterpret_tensor(buf3, (1, 16, 1, 1, 1), (0, 1, 0, 0, 0), 0), primals_4, stride=(1, 1, 1), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf4, (1, 4, 1, 1, 1), (4, 1, 1, 1, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_2[grid(4)](buf5, primals_5, 4, XBLOCK= 4, 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=128, num_warps=4, num_stages=1) return buf6, primals_1, primals_2, primals_4, reinterpret_tensor(buf1, (1, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0), reinterpret_tensor(buf3, (1, 16, 1, 1, 1), (16, 1, 1, 1, 1), 0), buf5, buf7 class SEModuleNew(nn.Module): def __init__(self, channels, reduction): super().__init__() self.avg_pool = nn.AdaptiveAvgPool3d(1) self.bottleneck = self._round_width(channels, reduction) self.fc1 = nn.Conv3d(channels, self.bottleneck, kernel_size=1, padding=0) self.relu = nn.ReLU() self.fc2 = nn.Conv3d(self.bottleneck, channels, kernel_size=1, padding=0) self.sigmoid = nn.Sigmoid() @staticmethod def _round_width(width, multiplier, min_width=8, divisor=8): width *= multiplier min_width = min_width or divisor width_out = max(min_width, int(width + divisor / 2) // divisor * divisor) if width_out < 0.9 * width: width_out += divisor return int(width_out) 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]
Viditagarwal7479/Video-Swin-Transformer
SEModule
false
18,079
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
BertSelfAttention
from _paritybench_helpers import _mock_config import math import torch from torch import nn class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( 'The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config. num_attention_heads) self.all_head_size = (self.num_attention_heads * self. attention_head_size) self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self. attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, hidden_states, attention_mask): mixed_query_layer = self.query(hidden_states) mixed_key_layer = self.key(hidden_states) mixed_value_layer = self.value(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self. attention_head_size) attention_scores = attention_scores + attention_mask attention_probs = nn.Softmax(dim=-1)(attention_scores) attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self. all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) return context_layer, attention_scores def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(hidden_size=4, num_attention_heads= 4, attention_probs_dropout_prob=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 import triton_helpers from torch._inductor.runtime.triton_helpers import 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_clone_0(in_ptr0, in_ptr1, 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') tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask) @triton.jit def triton_poi_fused_add_div_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 % 64 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp3 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp2 + tmp3 tl.store(in_out_ptr0 + x2, tmp4, 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 = 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_3(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_clone_4(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, 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), (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, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4, 4), (16, 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_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) del primals_4 buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2) del primals_6 buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del primals_2 buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf0 triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del primals_5 buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5) buf6 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf5 triton_poi_fused_add_div_1[grid(256)](buf6, primals_8, 256, XBLOCK= 128, num_warps=4, num_stages=1) del primals_8 buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256, num_warps=4, num_stages=1) buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_3[grid(256)](buf7, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf7 buf9 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf1 triton_poi_fused_clone_0[grid(16, 4)](buf2, primals_7, buf9, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1) del primals_7 buf10 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0) del buf2 extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), out=buf10) buf11 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) triton_poi_fused_clone_4[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) del buf10 return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0 ), buf6, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0 ), buf8, reinterpret_tensor(buf9, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0 ), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0) class BertSelfAttentionNew(nn.Module): def __init__(self, config): super(BertSelfAttentionNew, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( 'The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads)) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config. num_attention_heads) self.all_head_size = (self.num_attention_heads * self. attention_head_size) self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self. attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward(self, input_0, input_1): primals_1 = self.query.weight primals_2 = self.query.bias primals_4 = self.key.weight primals_5 = self.key.bias primals_6 = self.value.weight primals_7 = self.value.bias primals_3 = input_0 primals_8 = 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]
MingjieWang0606/2021-Sohu-Text-Matching-TOP2
BertSelfAttention
false
18,080
[ "MIT" ]
5
830a286cc978cb285cb63ae5a457e1d3813fa68a
https://github.com/MingjieWang0606/2021-Sohu-Text-Matching-TOP2/tree/830a286cc978cb285cb63ae5a457e1d3813fa68a
Color_MNIST_CNN
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data class Color_MNIST_CNN(nn.Module): def __init__(self): super(Color_MNIST_CNN, self).__init__() self.conv1 = nn.Conv2d(3, 64, 3, 1, padding=1) self.conv2 = nn.Conv2d(64, 128, 3, stride=2, padding=1) self.conv3 = nn.Conv2d(128, 128, 3, 1, padding=1) self.conv4 = nn.Conv2d(128, 128, 3, 1, padding=1) self.bn0 = nn.GroupNorm(8, 64) self.bn1 = nn.GroupNorm(8, 128) self.bn2 = nn.GroupNorm(8, 128) self.bn3 = nn.GroupNorm(8, 128) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.bn0(x) x = self.conv2(x) x = F.relu(x) x = self.bn1(x) x = self.conv3(x) x = F.relu(x) x = self.bn2(x) x = self.conv4(x) x = F.relu(x) x = self.bn3(x) x = self.avgpool(x) x = x.view(len(x), -1) 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._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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 192 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 % 3 y1 = yindex // 3 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (y0 + 3 * x2 + 27 * y1), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 12 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 % 3 y1 = yindex // 3 tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, 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 % 64 y1 = yindex // 64 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * 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) * 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_4(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 tl.store(in_out_ptr0 + x2, tmp2, None) @triton.jit def triton_per_fused_native_group_norm_5(in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 128 xoffset = tl.program_id(0) * XBLOCK xindex = 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) r3 = rindex x0 = xindex % 32 x1 = xindex // 32 % 64 x2 = xindex // 2048 x4 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * ((r3 + 128 * x1) % 4096) + 262144 * x2 + (r3 + 128 * x1) // 4096), None, eviction_policy= 'evict_last') tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp7 = tl.sum(tmp5, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 128, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp3 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.sum(tmp13, 1)[:, None] tl.store(out_ptr0 + x4, tmp10, None) tl.store(out_ptr1 + x4, tmp15, None) tl.store(out_ptr2 + x4, tmp9, None) @triton.jit def triton_per_fused_native_group_norm_6(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 128 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 % 32 x1 = xindex // 32 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 32 * r2 + 2048 * x1), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (x0 + 32 * r2 + 2048 * x1), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (x0 + 32 * r2 + 2048 * x1), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp15 = tmp12[:, None] tl.store(out_ptr0 + x3, tmp13, xmask) tl.store(out_ptr1 + x3, tmp14, xmask) tl.store(out_ptr2 + x3, tmp15, xmask) @triton.jit def triton_per_fused_native_group_norm_7(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 32 RBLOCK: tl.constexpr = 4 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 + 4 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 4 * x0), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (r1 + 4 * x0), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp12[:, None] tmp16 = 32768.0 tmp17 = tmp14 / tmp16 tmp18 = 1e-05 tmp19 = tmp17 + tmp18 tmp20 = libdevice.rsqrt(tmp19) tl.store(out_ptr2 + x0, tmp20, xmask) tl.store(out_ptr0 + x0, tmp13, xmask) tl.store(out_ptr1 + x0, tmp14, xmask) @triton.jit def triton_poi_fused_native_group_norm_8(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 % 64 x2 = xindex // 262144 tmp0 = tl.load(in_ptr0 + x3, None) tmp3 = tl.load(in_ptr1 + (8 * x2 + x0 // 8), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr2 + (8 * x2 + x0 // 8), None, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr3 + x0, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 - tmp3 tmp6 = 32768.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp4 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tl.store(out_ptr0 + x3, tmp15, None) @triton.jit def triton_poi_fused_convolution_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 tl.store(in_out_ptr0 + x2, tmp2, None) @triton.jit def triton_per_fused_native_group_norm_10(in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 128 xoffset = tl.program_id(0) * XBLOCK xindex = 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) r3 = rindex x0 = xindex % 16 x1 = xindex // 16 % 64 x2 = xindex // 1024 x4 = xindex tmp0 = tl.load(in_ptr0 + (8 * x0 + 128 * ((r3 + 128 * x1) % 1024) + 131072 * x2 + (r3 + 128 * x1) // 1024), None, eviction_policy= 'evict_last') tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp7 = tl.sum(tmp5, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 128, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp3 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.sum(tmp13, 1)[:, None] tl.store(out_ptr0 + x4, tmp10, None) tl.store(out_ptr1 + x4, tmp15, None) tl.store(out_ptr2 + x4, tmp9, None) @triton.jit def triton_per_fused_native_group_norm_11(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, 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 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp15 = tmp12[:, None] tl.store(out_ptr0 + x3, tmp13, xmask) tl.store(out_ptr1 + x3, tmp14, xmask) tl.store(out_ptr2 + x3, tmp15, xmask) @triton.jit def triton_per_fused_native_group_norm_12(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 32 RBLOCK: tl.constexpr = 2 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 + 2 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 2 * x0), xmask, other=0.0) tmp2 = tl.load(in_ptr2 + (r1 + 2 * x0), xmask, other=0.0) tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(xmask, tmp3, 0) tmp8 = tl.where(xmask, tmp4, 0) tmp9 = tl.where(xmask, tmp5, 0) tmp10, tmp11, tmp12 = triton_helpers.welford(tmp7, tmp8, tmp9, 1) tmp13 = tmp10[:, None] tmp14 = tmp11[:, None] tmp12[:, None] tmp16 = 16384.0 tmp17 = tmp14 / tmp16 tmp18 = 1e-05 tmp19 = tmp17 + tmp18 tmp20 = libdevice.rsqrt(tmp19) tl.store(out_ptr2 + x0, tmp20, xmask) tl.store(out_ptr0 + x0, tmp13, xmask) tl.store(out_ptr1 + x0, tmp14, xmask) @triton.jit def triton_poi_fused_native_group_norm_13(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 % 128 x2 = xindex // 131072 tmp0 = tl.load(in_ptr0 + x3, None) tmp3 = tl.load(in_ptr1 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr2 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr3 + x0, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 - tmp3 tmp6 = 16384.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp4 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tl.store(out_ptr0 + x3, tmp15, None) @triton.jit def triton_red_fused_mean_native_group_norm_14(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr): rnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rbase = tl.arange(0, RBLOCK)[None, :] x0 = xindex % 128 x4 = xindex // 128 x2 = xindex // 1024 tmp3 = tl.load(in_ptr1 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr2 + (8 * x2 + x0 // 16), None, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr3 + x0, None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') _tmp17 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) x5 = xindex for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r3 = rindex tmp0 = tl.load(in_ptr0 + (x0 + 128 * r3 + 4096 * (r3 % 32 // 32) + 16384 * x4), rmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = tmp2 - tmp3 tmp6 = 16384.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-05 tmp9 = tmp7 + tmp8 tmp10 = libdevice.rsqrt(tmp9) tmp11 = tmp4 * tmp10 tmp13 = tmp11 * tmp12 tmp15 = tmp13 + tmp14 tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK]) tmp18 = _tmp17 + tmp16 _tmp17 = tl.where(rmask, tmp18, _tmp17) tmp17 = tl.sum(_tmp17, 1)[:, None] tl.store(out_ptr0 + x5, tmp17, None) @triton.jit def triton_per_fused_mean_native_group_norm_15(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 512 RBLOCK: tl.constexpr = 8 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 % 128 x1 = xindex // 128 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 128 * r2 + 1024 * x1), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp5 = 1024.0 tmp6 = tmp4 / tmp5 tl.debug_barrier() tl.store(in_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, primals_14, primals_15, primals_16, primals_17) = args args.clear() assert_size_stride(primals_1, (64, 3, 3, 3), (27, 9, 3, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1)) assert_size_stride(primals_4, (64,), (1,)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (128, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (128,), (1,)) assert_size_stride(primals_9, (128,), (1,)) assert_size_stride(primals_10, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_11, (128,), (1,)) assert_size_stride(primals_12, (128,), (1,)) assert_size_stride(primals_13, (128,), (1,)) assert_size_stride(primals_14, (128, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_15, (128,), (1,)) assert_size_stride(primals_16, (128,), (1,)) assert_size_stride(primals_17, (128,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 3, 3, 3), (27, 1, 9, 3), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(192, 9)](primals_1, buf0, 192, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch .float32) triton_poi_fused_1[grid(12, 4096)](primals_3, buf1, 12, 4096, XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1) del primals_3 buf2 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch .float32) triton_poi_fused_2[grid(8192, 9)](primals_6, buf2, 8192, 9, XBLOCK= 16, YBLOCK=64, num_warps=4, num_stages=1) del primals_6 buf3 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_10, buf3, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_10 buf4 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(16384, 9)](primals_14, buf4, 16384, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_14 buf5 = extern_kernels.convolution(buf1, buf0, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 64, 64, 64), (262144, 1, 4096, 64)) buf6 = buf5 del buf5 triton_poi_fused_convolution_4[grid(1048576)](buf6, primals_2, 1048576, XBLOCK=1024, num_warps=4, num_stages=1) del primals_2 buf7 = empty_strided_cuda((4, 8, 1, 1, 4, 64), (2048, 4, 8192, 8192, 1, 32), torch.float32) buf8 = empty_strided_cuda((4, 8, 1, 1, 4, 64), (2048, 4, 8192, 8192, 1, 32), torch.float32) buf9 = empty_strided_cuda((4, 8, 1, 1, 4, 64), (2048, 4, 8192, 8192, 1, 32), torch.float32) triton_per_fused_native_group_norm_5[grid(8192)](buf6, buf7, buf8, buf9, 8192, 128, XBLOCK=8, num_warps=8, num_stages=1) buf10 = empty_strided_cuda((4, 8, 1, 1, 4), (32, 4, 128, 128, 1), torch.float32) buf11 = empty_strided_cuda((4, 8, 1, 1, 4), (32, 4, 128, 128, 1), torch.float32) buf12 = empty_strided_cuda((4, 8, 1, 1, 4), (32, 4, 128, 128, 1), torch.float32) triton_per_fused_native_group_norm_6[grid(128)](buf7, buf8, buf9, buf10, buf11, buf12, 128, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf7 del buf8 del buf9 buf13 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf14 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf17 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_7[grid(32)](buf10, buf11, buf12, buf13, buf14, buf17, 32, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf10 del buf11 del buf12 buf16 = empty_strided_cuda((4, 64, 64, 64), (262144, 1, 4096, 64), torch.float32) triton_poi_fused_native_group_norm_8[grid(1048576)](buf6, buf13, buf14, primals_4, primals_5, buf16, 1048576, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf18 = extern_kernels.convolution(buf16, buf2, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf18, (4, 128, 32, 32), (131072, 1, 4096, 128)) buf19 = buf18 del buf18 triton_poi_fused_convolution_9[grid(524288)](buf19, primals_7, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf20 = empty_strided_cuda((4, 8, 1, 1, 2, 64), (1024, 2, 4096, 4096, 1, 16), torch.float32) buf21 = empty_strided_cuda((4, 8, 1, 1, 2, 64), (1024, 2, 4096, 4096, 1, 16), torch.float32) buf22 = empty_strided_cuda((4, 8, 1, 1, 2, 64), (1024, 2, 4096, 4096, 1, 16), torch.float32) triton_per_fused_native_group_norm_10[grid(4096)](buf19, buf20, buf21, buf22, 4096, 128, XBLOCK=8, num_warps=8, num_stages=1) buf23 = empty_strided_cuda((4, 8, 1, 1, 2), (16, 2, 64, 64, 1), torch.float32) buf24 = empty_strided_cuda((4, 8, 1, 1, 2), (16, 2, 64, 64, 1), torch.float32) buf25 = empty_strided_cuda((4, 8, 1, 1, 2), (16, 2, 64, 64, 1), torch.float32) triton_per_fused_native_group_norm_11[grid(64)](buf20, buf21, buf22, buf23, buf24, buf25, 64, 64, XBLOCK=1, num_warps=2, num_stages=1) buf26 = buf14 del buf14 buf27 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf30 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_12[grid(32)](buf23, buf24, buf25, buf26, buf27, buf30, 32, 2, XBLOCK=1, num_warps=2, num_stages=1) buf29 = empty_strided_cuda((4, 128, 32, 32), (131072, 1, 4096, 128), torch.float32) triton_poi_fused_native_group_norm_13[grid(524288)](buf19, buf26, buf27, primals_8, primals_9, buf29, 524288, XBLOCK=512, num_warps=8, num_stages=1) del primals_9 buf31 = extern_kernels.convolution(buf29, buf3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf31, (4, 128, 32, 32), (131072, 1, 4096, 128)) buf32 = buf31 del buf31 triton_poi_fused_convolution_9[grid(524288)](buf32, primals_11, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_11 buf33 = buf22 del buf22 buf34 = buf21 del buf21 buf35 = buf20 del buf20 triton_per_fused_native_group_norm_10[grid(4096)](buf32, buf33, buf34, buf35, 4096, 128, XBLOCK=8, num_warps=8, num_stages=1) buf36 = buf25 del buf25 buf37 = buf24 del buf24 buf38 = buf23 del buf23 triton_per_fused_native_group_norm_11[grid(64)](buf33, buf34, buf35, buf36, buf37, buf38, 64, 64, XBLOCK=1, num_warps=2, num_stages=1) buf39 = buf27 del buf27 buf40 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf43 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_12[grid(32)](buf36, buf37, buf38, buf39, buf40, buf43, 32, 2, XBLOCK=1, num_warps=2, num_stages=1) buf42 = empty_strided_cuda((4, 128, 32, 32), (131072, 1, 4096, 128), torch.float32) triton_poi_fused_native_group_norm_13[grid(524288)](buf32, buf39, buf40, primals_12, primals_13, buf42, 524288, XBLOCK=512, num_warps=8, num_stages=1) del primals_13 buf44 = extern_kernels.convolution(buf42, buf4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf44, (4, 128, 32, 32), (131072, 1, 4096, 128)) buf45 = buf44 del buf44 triton_poi_fused_convolution_9[grid(524288)](buf45, primals_15, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_15 buf46 = buf35 del buf35 buf47 = buf34 del buf34 buf48 = buf33 del buf33 triton_per_fused_native_group_norm_10[grid(4096)](buf45, buf46, buf47, buf48, 4096, 128, XBLOCK=8, num_warps=8, num_stages=1) buf49 = buf38 del buf38 buf50 = buf37 del buf37 buf51 = buf36 del buf36 triton_per_fused_native_group_norm_11[grid(64)](buf46, buf47, buf48, buf49, buf50, buf51, 64, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf46 del buf47 buf52 = buf40 del buf40 buf53 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) buf55 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 32, 32), torch.float32) triton_per_fused_native_group_norm_12[grid(32)](buf49, buf50, buf51, buf52, buf53, buf55, 32, 2, XBLOCK=1, num_warps=2, num_stages=1) del buf49 del buf50 del buf51 buf56 = reinterpret_tensor(buf48, (4, 128, 1, 1, 8), (1024, 1, 4096, 4096, 128), 0) del buf48 triton_red_fused_mean_native_group_norm_14[grid(4096)](buf45, buf52, buf53, primals_16, primals_17, buf56, 4096, 128, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1) del buf53 del primals_17 buf57 = empty_strided_cuda((4, 128, 1, 1), (128, 1, 512, 512), torch.float32) buf58 = buf57 del buf57 triton_per_fused_mean_native_group_norm_15[grid(512)](buf58, buf56, 512, 8, XBLOCK=64, num_warps=4, num_stages=1) del buf56 return (reinterpret_tensor(buf58, (4, 128), (128, 1), 0), buf0, buf1, primals_4, buf2, primals_8, buf3, primals_12, buf4, primals_16, buf6, buf16, reinterpret_tensor(buf13, (4, 8), (8, 1), 0), reinterpret_tensor(buf17, (4, 8), (8, 1), 0), buf19, buf29, reinterpret_tensor(buf26, (4, 8), (8, 1), 0), reinterpret_tensor( buf30, (4, 8), (8, 1), 0), buf32, buf42, reinterpret_tensor(buf39, (4, 8), (8, 1), 0), reinterpret_tensor(buf43, (4, 8), (8, 1), 0), buf45, reinterpret_tensor(buf52, (4, 8), (8, 1), 0), reinterpret_tensor(buf55, (4, 8), (8, 1), 0)) class Color_MNIST_CNNNew(nn.Module): def __init__(self): super(Color_MNIST_CNNNew, self).__init__() self.conv1 = nn.Conv2d(3, 64, 3, 1, padding=1) self.conv2 = nn.Conv2d(64, 128, 3, stride=2, padding=1) self.conv3 = nn.Conv2d(128, 128, 3, 1, padding=1) self.conv4 = nn.Conv2d(128, 128, 3, 1, padding=1) self.bn0 = nn.GroupNorm(8, 64) self.bn1 = nn.GroupNorm(8, 128) self.bn2 = nn.GroupNorm(8, 128) self.bn3 = nn.GroupNorm(8, 128) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_6 = self.conv2.weight primals_7 = self.conv2.bias primals_10 = self.conv3.weight primals_8 = self.conv3.bias primals_14 = self.conv4.weight primals_9 = self.conv4.bias primals_4 = self.bn0.weight primals_5 = self.bn0.bias primals_11 = self.bn1.weight primals_12 = self.bn1.bias primals_13 = self.bn2.weight primals_15 = self.bn2.bias primals_16 = self.bn3.weight primals_17 = self.bn3.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]
VinAIResearch/mDSDI
Color_MNIST_CNN
false
18,081
[ "Apache-2.0" ]
9
8ec49085d8389ab490ec633c3ae4bf66be085366
https://github.com/VinAIResearch/mDSDI/tree/8ec49085d8389ab490ec633c3ae4bf66be085366
AngularMarginLoss
import torch import torch.nn.functional as F import torch.nn as nn class MetricLearningLoss(nn.Module): """ Generic loss function to be used in a metric learning setting """ def __init__(self, embedding_size, n_classes, device='cpu', *args, **kwargs ): super(MetricLearningLoss, self).__init__() self.embedding_size = embedding_size self.n_classes = n_classes self.device = device def forward(self, inputs, targets): raise NotImplementedError() class AngularMarginLoss(MetricLearningLoss): """ Generic angular margin loss definition (see https://github.com/cvqluu/Angular-Penalty-Softmax-Losses-Pytorch) "ElasticFace: Elastic Margin Loss for Deep Face Recognition", Boutros et al., https://arxiv.org/abs/2109.09416v2 """ def __init__(self, embedding_size, n_classes, device='cpu', scale=None, m1=1, m2=0, m3=0, eps=1e-06): super(AngularMarginLoss, self).__init__(embedding_size, n_classes, device=device) self.fc = nn.Linear(embedding_size, n_classes, bias=False) self.scale = scale self.m1 = m1 self.m2 = m2 self.m3 = m3 self.eps = eps def forward(self, inputs, targets): """ Compute ArcFace loss for inputs of shape [B, E] and targets of size [B] B: batch size E: embedding size """ self.fc.weight.data = F.normalize(self.fc.weight.data, p=2, dim=1) inputs_norms = torch.norm(inputs, p=2, dim=1) normalized_inputs = inputs / inputs_norms.unsqueeze(-1).repeat(1, inputs.size(1)) scales = torch.tensor([self.scale], device=inputs.device).repeat(inputs .size(0)) if self.scale is not None else inputs_norms cosines = self.fc(normalized_inputs).clamp(-1, 1) preds = torch.argmax(cosines, dim=1) angles = torch.arccos(cosines) numerator = scales.unsqueeze(-1) * (torch.cos(self.m1 * angles + self.m2) - self.m3) numerator = torch.diagonal(numerator.transpose(0, 1)[targets]) excluded = torch.cat([(scales[i] * torch.cat((cosines[i, :y], cosines[i, y + 1:])).unsqueeze(0)) for i, y in enumerate( targets)], dim=0) denominator = torch.exp(numerator) + torch.sum(torch.exp(excluded), dim=1) loss = -torch.mean(numerator - torch.log(denominator + self.eps)) return normalized_inputs, preds, loss def get_inputs(): return [torch.rand([4, 4]), torch.ones([4], dtype=torch.int64)] def get_init_inputs(): return [[], {'embedding_size': 4, 'n_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 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_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp2 = tmp1 * tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 + tmp4 tmp7 = tmp6 * tmp6 tmp8 = tmp5 + tmp7 tmp10 = tmp9 * tmp9 tmp11 = tmp8 + tmp10 tmp12 = libdevice.sqrt(tmp11) tmp13 = 1e-12 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = tmp0 / tmp14 tl.store(out_ptr0 + x2, tmp15, xmask) @triton.jit def triton_poi_fused_linalg_vector_norm_1(in_ptr0, 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 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp1 = tmp0 * tmp0 tmp3 = tmp2 * tmp2 tmp4 = tmp1 + tmp3 tmp6 = tmp5 * tmp5 tmp7 = tmp4 + tmp6 tmp9 = tmp8 * tmp8 tmp10 = tmp7 + tmp9 tmp11 = libdevice.sqrt(tmp10) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused_div_repeat_2(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 x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 / tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_clamp_ge_le_logical_and_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.load(in_ptr0 + x0, xmask) tmp1 = -1.0 tmp2 = triton_helpers.maximum(tmp0, tmp1) tmp3 = 1.0 tmp4 = triton_helpers.minimum(tmp2, tmp3) tmp5 = tmp0 >= tmp1 tmp6 = tmp0 <= tmp3 tmp7 = tmp5 & tmp6 tl.store(out_ptr0 + x0, tmp4, xmask) tl.store(out_ptr1 + x0, tmp7, xmask) @triton.jit def triton_poi_fused_argmax_4(in_ptr0, 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 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp17 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp32 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 > tmp1 tmp3 = tmp0 == tmp1 tmp4 = tmp0 != tmp0 tmp5 = tmp1 != tmp1 tmp6 = tmp4 > tmp5 tmp7 = tmp2 | tmp6 tmp8 = tmp4 & tmp5 tmp9 = tmp3 | tmp8 tmp10 = tl.full([1], 0, tl.int64) tmp11 = tl.full([1], 1, tl.int64) tmp12 = tmp10 < tmp11 tmp13 = tmp9 & tmp12 tmp14 = tmp7 | tmp13 tmp15 = tl.where(tmp14, tmp0, tmp1) tmp16 = tl.where(tmp14, tmp10, tmp11) tmp18 = tmp15 > tmp17 tmp19 = tmp15 == tmp17 tmp20 = tmp15 != tmp15 tmp21 = tmp17 != tmp17 tmp22 = tmp20 > tmp21 tmp23 = tmp18 | tmp22 tmp24 = tmp20 & tmp21 tmp25 = tmp19 | tmp24 tmp26 = tl.full([1], 2, tl.int64) tmp27 = tmp16 < tmp26 tmp28 = tmp25 & tmp27 tmp29 = tmp23 | tmp28 tmp30 = tl.where(tmp29, tmp15, tmp17) tmp31 = tl.where(tmp29, tmp16, tmp26) tmp33 = tmp30 > tmp32 tmp34 = tmp30 == tmp32 tmp35 = tmp30 != tmp30 tmp36 = tmp32 != tmp32 tmp37 = tmp35 > tmp36 tmp38 = tmp33 | tmp37 tmp39 = tmp35 & tmp36 tmp40 = tmp34 | tmp39 tmp41 = tl.full([1], 3, tl.int64) tmp42 = tmp31 < tmp41 tmp43 = tmp40 & tmp42 tmp44 = tmp38 | tmp43 tl.where(tmp44, tmp30, tmp32) tmp46 = tl.where(tmp44, tmp31, tmp41) tl.store(out_ptr0 + x0, tmp46, xmask) @triton.jit def triton_poi_fused_index_5(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 x0 = xindex % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp1 = tl.full([XBLOCK], 4, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask, 'index out of bounds: 0 <= tmp4 < 4') tmp7 = tl.load(in_ptr2 + (tmp4 + 4 * x0), xmask, eviction_policy= 'evict_last') tmp8 = libdevice.acos(tmp7) tmp9 = 1.0 tmp10 = tmp8 * tmp9 tmp11 = 0.0 tmp12 = tmp10 + tmp11 tmp13 = tl_math.cos(tmp12) tmp14 = tmp13 - tmp11 tmp15 = tmp6 * tmp14 tl.store(out_ptr0 + x2, tmp15, 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, 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, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_0[grid(16)](primals_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused_linalg_vector_norm_1[grid(4)](primals_2, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_div_repeat_2[grid(16)](primals_2, buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_2 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(buf0, (4, 4), (1, 4), 0), out=buf3) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf7 = empty_strided_cuda((4, 4), (4, 1), torch.bool) triton_poi_fused_clamp_ge_le_logical_and_3[grid(16)](buf3, buf4, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((4,), (1,), torch.int64) triton_poi_fused_argmax_4[grid(4)](buf4, buf5, 4, XBLOCK=4, num_warps=1, num_stages=1) buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_index_5[grid(16)](primals_3, buf1, buf4, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1) buf8 = torch.ops.aten.set_.source_Tensor(primals_1, buf0) assert_size_stride(buf8, (4, 4), (4, 1)) del buf3 del primals_1 return reinterpret_tensor(buf6, (4,), (5,), 0 ), buf5, buf4, buf1, buf2, primals_3, buf1, buf2, buf4, buf7 class MetricLearningLoss(nn.Module): """ Generic loss function to be used in a metric learning setting """ def __init__(self, embedding_size, n_classes, device='cpu', *args, **kwargs ): super(MetricLearningLoss, self).__init__() self.embedding_size = embedding_size self.n_classes = n_classes self.device = device def forward(self, inputs, targets): raise NotImplementedError() class AngularMarginLossNew(MetricLearningLoss): """ Generic angular margin loss definition (see https://github.com/cvqluu/Angular-Penalty-Softmax-Losses-Pytorch) "ElasticFace: Elastic Margin Loss for Deep Face Recognition", Boutros et al., https://arxiv.org/abs/2109.09416v2 """ def __init__(self, embedding_size, n_classes, device='cpu', scale=None, m1=1, m2=0, m3=0, eps=1e-06): super(AngularMarginLossNew, self).__init__(embedding_size, n_classes, device=device) self.fc = nn.Linear(embedding_size, n_classes, bias=False) self.scale = scale self.m1 = m1 self.m2 = m2 self.m3 = m3 self.eps = eps def forward(self, input_0, input_1): primals_1 = self.fc.weight primals_2 = input_0 primals_3 = input_1 output = call([primals_1, primals_2, primals_3]) return output[0], output[1], output[2]
Wadaboa/titanet
AngularMarginLoss
false
18,082
[ "MIT" ]
4
b07e3074e79ea8c1129fb0adb8315e06bb4943ea
https://github.com/Wadaboa/titanet/tree/b07e3074e79ea8c1129fb0adb8315e06bb4943ea
GatedTanh
import torch import torch.nn as nn class GatedTanh(nn.Module): """ From: https://arxiv.org/pdf/1707.07998.pdf nonlinear_layer (f_a) : x\\in R^m => y \\in R^n ilda{y} = tanh(Wx + b) g = sigmoid(W'x + b') y = ilda(y) \\circ g input: (N, *, in_dim) output: (N, *, out_dim) """ def __init__(self, in_dim, out_dim): super(GatedTanh, self).__init__() self.fc = nn.Linear(in_dim, out_dim) self.gate_fc = nn.Linear(in_dim, out_dim) def forward(self, x): y_tilda = torch.tanh(self.fc(x)) gated = torch.sigmoid(self.gate_fc(x)) y = y_tilda * gated return y 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.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_mul_sigmoid_tanh_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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp2 = tl.load(in_ptr1 + x0, xmask) tmp1 = libdevice.tanh(tmp0) tmp3 = tl.sigmoid(tmp2) tmp4 = tmp1 * tmp3 tl.store(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, (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_mul_sigmoid_tanh_0[grid(256)](buf0, buf1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0, buf1 class GatedTanhNew(nn.Module): """ From: https://arxiv.org/pdf/1707.07998.pdf nonlinear_layer (f_a) : x\\in R^m => y \\in R^n ilda{y} = tanh(Wx + b) g = sigmoid(W'x + b') y = ilda(y) \\circ g input: (N, *, in_dim) output: (N, *, out_dim) """ def __init__(self, in_dim, out_dim): super(GatedTanhNew, self).__init__() self.fc = nn.Linear(in_dim, out_dim) self.gate_fc = nn.Linear(in_dim, out_dim) def forward(self, input_0): primals_1 = self.fc.weight primals_2 = self.fc.bias primals_4 = self.gate_fc.weight primals_5 = self.gate_fc.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
VisualJoyce/ChengyuBERT
GatedTanh
false
18,083
[ "MIT" ]
8
605db3a4b3241dd4d02baa41a68bf23b5b00b36d
https://github.com/VisualJoyce/ChengyuBERT/tree/605db3a4b3241dd4d02baa41a68bf23b5b00b36d
CELoss
import torch import torch.nn.functional as F import torch.nn as nn class MetricLearningLoss(nn.Module): """ Generic loss function to be used in a metric learning setting """ def __init__(self, embedding_size, n_classes, device='cpu', *args, **kwargs ): super(MetricLearningLoss, self).__init__() self.embedding_size = embedding_size self.n_classes = n_classes self.device = device def forward(self, inputs, targets): raise NotImplementedError() class CELoss(MetricLearningLoss): """ Cross-entropy loss with the addition of a linear layer to map inputs to the target number of classes """ def __init__(self, embedding_size, n_classes, device='cpu'): super(CELoss, self).__init__(embedding_size, n_classes, device=device) self.fc = nn.Linear(embedding_size, n_classes) def forward(self, inputs, targets): """ Compute cross-entropy loss for inputs of shape [B, E] and targets of size [B] B: batch size E: embedding size """ logits = self.fc(inputs) preds = torch.argmax(logits, dim=1) loss = F.cross_entropy(logits, targets) inputs = F.normalize(inputs, p=2, dim=1) return inputs, preds, loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'embedding_size': 4, 'n_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 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_argmax_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 % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp17 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp32 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp2 = tmp0 > tmp1 tmp3 = tmp0 == tmp1 tmp4 = tmp0 != tmp0 tmp5 = tmp1 != tmp1 tmp6 = tmp4 > tmp5 tmp7 = tmp2 | tmp6 tmp8 = tmp4 & tmp5 tmp9 = tmp3 | tmp8 tmp10 = tl.full([1], 0, tl.int64) tmp11 = tl.full([1], 1, tl.int64) tmp12 = tmp10 < tmp11 tmp13 = tmp9 & tmp12 tmp14 = tmp7 | tmp13 tmp15 = tl.where(tmp14, tmp0, tmp1) tmp16 = tl.where(tmp14, tmp10, tmp11) tmp18 = tmp15 > tmp17 tmp19 = tmp15 == tmp17 tmp20 = tmp15 != tmp15 tmp21 = tmp17 != tmp17 tmp22 = tmp20 > tmp21 tmp23 = tmp18 | tmp22 tmp24 = tmp20 & tmp21 tmp25 = tmp19 | tmp24 tmp26 = tl.full([1], 2, tl.int64) tmp27 = tmp16 < tmp26 tmp28 = tmp25 & tmp27 tmp29 = tmp23 | tmp28 tmp30 = tl.where(tmp29, tmp15, tmp17) tmp31 = tl.where(tmp29, tmp16, tmp26) tmp33 = tmp30 > tmp32 tmp34 = tmp30 == tmp32 tmp35 = tmp30 != tmp30 tmp36 = tmp32 != tmp32 tmp37 = tmp35 > tmp36 tmp38 = tmp33 | tmp37 tmp39 = tmp35 & tmp36 tmp40 = tmp34 | tmp39 tmp41 = tl.full([1], 3, tl.int64) tmp42 = tmp31 < tmp41 tmp43 = tmp40 & tmp42 tmp44 = tmp38 | tmp43 tl.where(tmp44, tmp30, tmp32) tmp46 = tl.where(tmp44, tmp31, tmp41) tl.store(out_ptr0 + x2, tmp46, xmask) @triton.jit def triton_poi_fused__log_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 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_div_mul_neg_sum_2(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) r3 = rindex r0 = rindex % 16 r2 = rindex // 64 tmp0 = tl.load(in_ptr0 + r3, None) tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp14 = tl.load(in_ptr1 + r3, None) tmp2 = tl_math.exp(tmp1) tmp4 = tl_math.exp(tmp3) tmp5 = tmp2 + tmp4 tmp7 = tl_math.exp(tmp6) tmp8 = tmp5 + tmp7 tmp10 = tl_math.exp(tmp9) tmp11 = tmp8 + tmp10 tmp12 = tl_math.log(tmp11) tmp13 = tmp0 - tmp12 tmp15 = tmp13 * tmp14 tmp16 = tl.broadcast_to(tmp15, [RBLOCK]) tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0)) tmp19 = -tmp18 tmp20 = 0.015625 tmp21 = tmp19 * tmp20 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, None) @triton.jit def triton_poi_fused_div_3(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') 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') 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 + x3, tmp15, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = 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, 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((4, 4, 4), (16, 4, 1), torch.int64) get_raw_stream(0) triton_poi_fused_argmax_0[grid(64)](buf0, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__log_softmax_1[grid(256)](buf0, buf2, 256, XBLOCK= 128, num_warps=4, num_stages=1) buf3 = empty_strided_cuda((), (), torch.float32) buf5 = buf3 del buf3 triton_per_fused__log_softmax_div_mul_neg_sum_2[grid(1)](buf5, buf2, primals_4, 1, 256, num_warps=2, num_stages=1) buf4 = buf2 del buf2 triton_poi_fused_div_3[grid(256)](primals_3, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf4, buf1, buf5, primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0 class MetricLearningLoss(nn.Module): """ Generic loss function to be used in a metric learning setting """ def __init__(self, embedding_size, n_classes, device='cpu', *args, **kwargs ): super(MetricLearningLoss, self).__init__() self.embedding_size = embedding_size self.n_classes = n_classes self.device = device def forward(self, inputs, targets): raise NotImplementedError() class CELossNew(MetricLearningLoss): """ Cross-entropy loss with the addition of a linear layer to map inputs to the target number of classes """ def __init__(self, embedding_size, n_classes, device='cpu'): super(CELossNew, self).__init__(embedding_size, n_classes, device= device) self.fc = nn.Linear(embedding_size, n_classes) def forward(self, input_0, input_1): primals_1 = self.fc.weight primals_2 = self.fc.bias primals_3 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0], output[1], output[2]
Wadaboa/titanet
CELoss
false
18,084
[ "MIT" ]
4
b07e3074e79ea8c1129fb0adb8315e06bb4943ea
https://github.com/Wadaboa/titanet/tree/b07e3074e79ea8c1129fb0adb8315e06bb4943ea
CrossEntropyLoss
import torch import torch.utils.data import torch import torch.nn as nn class CrossEntropyLoss(nn.Module): def __init__(self, label_nc): super(CrossEntropyLoss, self).__init__() self.softmax = nn.LogSoftmax(dim=1) self.criterion = nn.NLLLoss2d() def forward(self, output, label): label = label.long().max(1)[1] output = self.softmax(output) return self.criterion(output, label) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'label_nc': 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.utils.data import torch 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__to_copy_max_nll_loss2d_forward_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) tmp13 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp23 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp42 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp44 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp47 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp50 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp1 = tmp0.to(tl.int64) tmp3 = tmp2.to(tl.int64) tmp4 = tmp1 > tmp3 tmp5 = tmp1 == tmp3 tmp6 = tl.full([1, 1], 0, tl.int64) tmp7 = tl.full([1, 1], 1, tl.int64) tmp8 = tmp6 < tmp7 tmp9 = tmp5 & tmp8 tmp10 = tmp4 | tmp9 tmp11 = tl.where(tmp10, tmp1, tmp3) tmp12 = tl.where(tmp10, tmp6, tmp7) tmp14 = tmp13.to(tl.int64) tmp15 = tmp11 > tmp14 tmp16 = tmp11 == tmp14 tmp17 = tl.full([1, 1], 2, tl.int64) tmp18 = tmp12 < tmp17 tmp19 = tmp16 & tmp18 tmp20 = tmp15 | tmp19 tmp21 = tl.where(tmp20, tmp11, tmp14) tmp22 = tl.where(tmp20, tmp12, tmp17) tmp24 = tmp23.to(tl.int64) tmp25 = tmp21 > tmp24 tmp26 = tmp21 == tmp24 tmp27 = tl.full([1, 1], 3, tl.int64) tmp28 = tmp22 < tmp27 tmp29 = tmp26 & tmp28 tmp30 = tmp25 | tmp29 tl.where(tmp30, tmp21, tmp24) tmp32 = tl.where(tmp30, tmp22, tmp27) tmp33 = tl.full([1, 1], -100, tl.int64) tmp34 = tmp32 != tmp33 tmp35 = tl.where(tmp34, tmp32, tmp6) tmp36 = tl.full([XBLOCK, RBLOCK], 4, tl.int32) tmp37 = tmp35 + tmp36 tmp38 = tmp35 < 0 tmp39 = tl.where(tmp38, tmp37, tmp35) tl.device_assert((0 <= tmp39) & (tmp39 < 4), 'index out of bounds: 0 <= tmp39 < 4') tmp41 = tl.load(in_ptr1 + (r0 + 16 * tmp39 + 64 * r1), None) tmp43 = tl_math.exp(tmp42) tmp45 = tl_math.exp(tmp44) tmp46 = tmp43 + tmp45 tmp48 = tl_math.exp(tmp47) tmp49 = tmp46 + tmp48 tmp51 = tl_math.exp(tmp50) tmp52 = tmp49 + tmp51 tmp53 = tl_math.log(tmp52) tmp54 = tmp41 - tmp53 tmp55 = -tmp54 tmp56 = 0.0 tmp57 = tl.where(tmp34, tmp55, tmp56) tmp58 = tl.broadcast_to(tmp57, [XBLOCK, RBLOCK]) tmp60 = tl.sum(tmp58, 1)[:, None] tmp61 = tmp34.to(tl.int64) tmp62 = tl.broadcast_to(tmp61, [XBLOCK, RBLOCK]) tmp64 = tl.sum(tmp62, 1)[:, None] tmp65 = tmp64.to(tl.float32) tmp66 = tmp60 / tmp65 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp66, 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) buf1 = 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, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf2 = empty_strided_cuda((), (), torch.float32) buf4 = buf2 del buf2 triton_per_fused__to_copy_max_nll_loss2d_forward_1[grid(1)](buf4, arg0_1, buf1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del buf1 return buf4, class CrossEntropyLossNew(nn.Module): def __init__(self, label_nc): super(CrossEntropyLossNew, self).__init__() self.softmax = nn.LogSoftmax(dim=1) self.criterion = nn.NLLLoss2d() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
WeisiX/ITAS3D
CrossEntropyLoss
false
18,085
[ "MIT" ]
4
fc861e0cb2d4516905bfadab5e5e880c2b021832
https://github.com/WeisiX/ITAS3D/tree/fc861e0cb2d4516905bfadab5e5e880c2b021832
Mask_BN
import torch import torch.nn as nn class Mask_BN(nn.Module): def __init__(self): super(Mask_BN, self).__init__() def forward(self, x): x_mask = x != 0 x_centralization = x - x_mask * x[:, 0, :, :].unsqueeze(1) none_zero_n = x_mask.sum(axis=3).sum(axis=2).sum(axis=1).unsqueeze(1) none_zero_sum = x_centralization.sum(axis=2).sum(axis=1) x_mean = none_zero_sum / (none_zero_n * 0.5) mu = x_mean.unsqueeze(1).unsqueeze(2) * x_mask var = (((x_centralization - mu) ** 2).sum(axis=2).sum(axis=1) / none_zero_n).unsqueeze(1).unsqueeze(2) bn_x = (x_centralization - mu) / var ** 0.5 return bn_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.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 @triton.jit def triton_poi_fused_ne_sum_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') tmp4 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp8 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp16 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp27 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp32 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp35 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp39 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp43 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp48 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp51 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp55 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp59 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp1 = 0.0 tmp2 = tmp0 != tmp1 tmp3 = tmp2.to(tl.int64) tmp5 = tmp4 != tmp1 tmp6 = tmp5.to(tl.int64) tmp7 = tmp3 + tmp6 tmp9 = tmp8 != tmp1 tmp10 = tmp9.to(tl.int64) tmp11 = tmp7 + tmp10 tmp13 = tmp12 != tmp1 tmp14 = tmp13.to(tl.int64) tmp15 = tmp11 + tmp14 tmp17 = tmp16 != tmp1 tmp18 = tmp17.to(tl.int64) tmp20 = tmp19 != tmp1 tmp21 = tmp20.to(tl.int64) tmp22 = tmp18 + tmp21 tmp24 = tmp23 != tmp1 tmp25 = tmp24.to(tl.int64) tmp26 = tmp22 + tmp25 tmp28 = tmp27 != tmp1 tmp29 = tmp28.to(tl.int64) tmp30 = tmp26 + tmp29 tmp31 = tmp15 + tmp30 tmp33 = tmp32 != tmp1 tmp34 = tmp33.to(tl.int64) tmp36 = tmp35 != tmp1 tmp37 = tmp36.to(tl.int64) tmp38 = tmp34 + tmp37 tmp40 = tmp39 != tmp1 tmp41 = tmp40.to(tl.int64) tmp42 = tmp38 + tmp41 tmp44 = tmp43 != tmp1 tmp45 = tmp44.to(tl.int64) tmp46 = tmp42 + tmp45 tmp47 = tmp31 + tmp46 tmp49 = tmp48 != tmp1 tmp50 = tmp49.to(tl.int64) tmp52 = tmp51 != tmp1 tmp53 = tmp52.to(tl.int64) tmp54 = tmp50 + tmp53 tmp56 = tmp55 != tmp1 tmp57 = tmp56.to(tl.int64) tmp58 = tmp54 + tmp57 tmp60 = tmp59 != tmp1 tmp61 = tmp60.to(tl.int64) tmp62 = tmp58 + tmp61 tmp63 = tmp47 + tmp62 tl.store(out_ptr0 + x0, tmp63, xmask) @triton.jit def triton_poi_fused_div_mul_ne_sub_sum_1(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 x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp6 = tl.load(in_ptr0 + (4 + x0 + 64 * x1), xmask) tmp12 = tl.load(in_ptr0 + (8 + x0 + 64 * x1), xmask) tmp18 = tl.load(in_ptr0 + (12 + x0 + 64 * x1), xmask) tmp24 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp29 = tl.load(in_ptr0 + (20 + x0 + 64 * x1), xmask) tmp35 = tl.load(in_ptr0 + (24 + x0 + 64 * x1), xmask) tmp41 = tl.load(in_ptr0 + (28 + x0 + 64 * x1), xmask) tmp48 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp53 = tl.load(in_ptr0 + (36 + x0 + 64 * x1), xmask) tmp59 = tl.load(in_ptr0 + (40 + x0 + 64 * x1), xmask) tmp65 = tl.load(in_ptr0 + (44 + x0 + 64 * x1), xmask) tmp72 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp77 = tl.load(in_ptr0 + (52 + x0 + 64 * x1), xmask) tmp83 = tl.load(in_ptr0 + (56 + x0 + 64 * x1), xmask) tmp89 = tl.load(in_ptr0 + (60 + x0 + 64 * x1), xmask) tmp96 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp97 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp99 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp101 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy= 'evict_last') tmp1 = 0.0 tmp2 = tmp0 != tmp1 tmp3 = tmp2.to(tl.float32) tmp4 = tmp3 * tmp0 tmp5 = tmp0 - tmp4 tmp7 = tmp6 != tmp1 tmp8 = tmp7.to(tl.float32) tmp9 = tmp8 * tmp6 tmp10 = tmp6 - tmp9 tmp11 = tmp5 + tmp10 tmp13 = tmp12 != tmp1 tmp14 = tmp13.to(tl.float32) tmp15 = tmp14 * tmp12 tmp16 = tmp12 - tmp15 tmp17 = tmp11 + tmp16 tmp19 = tmp18 != tmp1 tmp20 = tmp19.to(tl.float32) tmp21 = tmp20 * tmp18 tmp22 = tmp18 - tmp21 tmp23 = tmp17 + tmp22 tmp25 = tmp24 != tmp1 tmp26 = tmp25.to(tl.float32) tmp27 = tmp26 * tmp0 tmp28 = tmp24 - tmp27 tmp30 = tmp29 != tmp1 tmp31 = tmp30.to(tl.float32) tmp32 = tmp31 * tmp6 tmp33 = tmp29 - tmp32 tmp34 = tmp28 + tmp33 tmp36 = tmp35 != tmp1 tmp37 = tmp36.to(tl.float32) tmp38 = tmp37 * tmp12 tmp39 = tmp35 - tmp38 tmp40 = tmp34 + tmp39 tmp42 = tmp41 != tmp1 tmp43 = tmp42.to(tl.float32) tmp44 = tmp43 * tmp18 tmp45 = tmp41 - tmp44 tmp46 = tmp40 + tmp45 tmp47 = tmp23 + tmp46 tmp49 = tmp48 != tmp1 tmp50 = tmp49.to(tl.float32) tmp51 = tmp50 * tmp0 tmp52 = tmp48 - tmp51 tmp54 = tmp53 != tmp1 tmp55 = tmp54.to(tl.float32) tmp56 = tmp55 * tmp6 tmp57 = tmp53 - tmp56 tmp58 = tmp52 + tmp57 tmp60 = tmp59 != tmp1 tmp61 = tmp60.to(tl.float32) tmp62 = tmp61 * tmp12 tmp63 = tmp59 - tmp62 tmp64 = tmp58 + tmp63 tmp66 = tmp65 != tmp1 tmp67 = tmp66.to(tl.float32) tmp68 = tmp67 * tmp18 tmp69 = tmp65 - tmp68 tmp70 = tmp64 + tmp69 tmp71 = tmp47 + tmp70 tmp73 = tmp72 != tmp1 tmp74 = tmp73.to(tl.float32) tmp75 = tmp74 * tmp0 tmp76 = tmp72 - tmp75 tmp78 = tmp77 != tmp1 tmp79 = tmp78.to(tl.float32) tmp80 = tmp79 * tmp6 tmp81 = tmp77 - tmp80 tmp82 = tmp76 + tmp81 tmp84 = tmp83 != tmp1 tmp85 = tmp84.to(tl.float32) tmp86 = tmp85 * tmp12 tmp87 = tmp83 - tmp86 tmp88 = tmp82 + tmp87 tmp90 = tmp89 != tmp1 tmp91 = tmp90.to(tl.float32) tmp92 = tmp91 * tmp18 tmp93 = tmp89 - tmp92 tmp94 = tmp88 + tmp93 tmp95 = tmp71 + tmp94 tmp98 = tmp96 + tmp97 tmp100 = tmp98 + tmp99 tmp102 = tmp100 + tmp101 tmp103 = tmp102.to(tl.float32) tmp104 = 0.5 tmp105 = tmp103 * tmp104 tmp106 = tmp95 / tmp105 tl.store(in_out_ptr0 + x2, tmp106, xmask) @triton.jit def triton_poi_fused_mul_ne_pow_sub_sum_2(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 x3 = xindex // 4 x2 = xindex // 16 x4 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x3), xmask) tmp4 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp7 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp11 = tl.load(in_ptr0 + (4 + x0 + 16 * x3), xmask) tmp14 = tl.load(in_ptr0 + (4 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp21 = tl.load(in_ptr0 + (8 + x0 + 16 * x3), xmask) tmp24 = tl.load(in_ptr0 + (8 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp31 = tl.load(in_ptr0 + (12 + x0 + 16 * x3), xmask) tmp34 = tl.load(in_ptr0 + (12 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp1 = 0.0 tmp2 = tmp0 != tmp1 tmp3 = tmp2.to(tl.float32) tmp5 = tmp3 * tmp4 tmp6 = tmp0 - tmp5 tmp8 = tmp7 * tmp3 tmp9 = tmp6 - tmp8 tmp10 = tmp9 * tmp9 tmp12 = tmp11 != tmp1 tmp13 = tmp12.to(tl.float32) tmp15 = tmp13 * tmp14 tmp16 = tmp11 - tmp15 tmp17 = tmp7 * tmp13 tmp18 = tmp16 - tmp17 tmp19 = tmp18 * tmp18 tmp20 = tmp10 + tmp19 tmp22 = tmp21 != tmp1 tmp23 = tmp22.to(tl.float32) tmp25 = tmp23 * tmp24 tmp26 = tmp21 - tmp25 tmp27 = tmp7 * tmp23 tmp28 = tmp26 - tmp27 tmp29 = tmp28 * tmp28 tmp30 = tmp20 + tmp29 tmp32 = tmp31 != tmp1 tmp33 = tmp32.to(tl.float32) tmp35 = tmp33 * tmp34 tmp36 = tmp31 - tmp35 tmp37 = tmp7 * tmp33 tmp38 = tmp36 - tmp37 tmp39 = tmp38 * tmp38 tmp40 = tmp30 + tmp39 tl.store(out_ptr0 + x4, tmp40, xmask) @triton.jit def triton_poi_fused_pow_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 % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask) tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask) tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask) tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask) tmp7 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp9 = tmp7 + tmp8 tmp11 = tmp9 + tmp10 tmp13 = tmp11 + tmp12 tmp14 = tmp13.to(tl.float32) tmp15 = tmp6 / tmp14 tmp16 = libdevice.sqrt(tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_div_mul_ne_pow_sub_4(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 x4 = xindex x3 = xindex // 64 x5 = xindex % 16 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x4, xmask) tmp4 = tl.load(in_ptr0 + (x5 + 64 * x3), xmask, eviction_policy= 'evict_last') tmp7 = tl.load(in_ptr1 + (x0 + 4 * x3), xmask, eviction_policy='evict_last' ) tmp10 = tl.load(in_ptr2 + (x0 + 4 * x3), xmask, eviction_policy= 'evict_last') tmp1 = 0.0 tmp2 = tmp0 != tmp1 tmp3 = tmp2.to(tl.float32) tmp5 = tmp3 * tmp4 tmp6 = tmp0 - tmp5 tmp8 = tmp7 * tmp3 tmp9 = tmp6 - tmp8 tmp11 = tmp9 / tmp10 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) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.int64) get_raw_stream(0) triton_poi_fused_ne_sum_0[grid(16)](arg0_1, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf2 = buf0 del buf0 triton_poi_fused_div_mul_ne_sub_sum_1[grid(16)](buf2, arg0_1, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_mul_ne_pow_sub_sum_2[grid(64)](arg0_1, buf2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((4, 1, 1, 4), (4, 16, 16, 1), torch.float32) triton_poi_fused_pow_3[grid(16)](buf3, buf1, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf1 del buf3 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_div_mul_ne_pow_sub_4[grid(256)](arg0_1, buf2, buf4, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del buf2 del buf4 return buf5, class Mask_BNNew(nn.Module): def __init__(self): super(Mask_BNNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
XIAOYEJIAYOU/GSAN
Mask_BN
false
18,086
[ "MIT" ]
6
8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
https://github.com/XIAOYEJIAYOU/GSAN/tree/8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
OffsetNet
import torch import torch.nn as nn class OffsetNet(nn.Module): """OffsetNet in Temporal interlace module. The OffsetNet consists of one convolution layer and two fc layers with a relu activation following with a sigmoid function. Following the convolution layer, two fc layers and relu are applied to the output. Then, apply the sigmoid function with a multiply factor and a minus 0.5 to transform the output to (-4, 4). Args: in_channels (int): Channel num of input features. groups (int): Number of groups for fc layer outputs. num_segments (int): Number of frame segments. """ def __init__(self, in_channels, groups, num_segments): super().__init__() self.sigmoid = nn.Sigmoid() kernel_size = 3 padding = 1 self.conv = nn.Conv1d(in_channels, 1, kernel_size, padding=padding) self.fc1 = nn.Linear(num_segments, num_segments) self.relu = nn.ReLU() self.fc2 = nn.Linear(num_segments, groups) self.init_weights() def init_weights(self): """Initiate the parameters either from existing checkpoint or from scratch.""" self.fc2.bias.data[...] = 0.5108 def forward(self, x): """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: torch.Tensor: The output of the module. """ n, _, t = x.shape x = self.conv(x) x = x.view(n, t) x = self.relu(self.fc1(x)) x = self.fc2(x) x = x.view(n, 1, -1) x = 4 * (self.sigmoid(x) - 0.5) return x def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'groups': 1, 'num_segments': 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_convolution_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 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_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_sub_2(in_ptr0, 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 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.sigmoid(tmp0) tmp2 = 0.5 tmp3 = tmp1 - tmp2 tmp4 = 4.0 tmp5 = tmp3 * tmp4 tl.store(out_ptr0 + x0, tmp5, 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), (16, 4, 1)) assert_size_stride(primals_2, (1, 4, 3), (12, 3, 1)) assert_size_stride(primals_3, (1,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (1, 4), (4, 1)) assert_size_stride(primals_7, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf0, (4, 1, 4), (4, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(16)](buf1, primals_3, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (4, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2) buf3 = buf2 del buf2 triton_poi_fused_relu_1[grid(16)](buf3, primals_5, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_7, buf3, reinterpret_tensor(primals_6, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf5) del primals_7 buf6 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32) triton_poi_fused_mul_sigmoid_sub_2[grid(4)](buf5, buf6, 4, XBLOCK=4, num_warps=1, num_stages=1) return buf6, primals_1, primals_2, reinterpret_tensor(buf1, (4, 4), (4, 1), 0), buf3, buf5, primals_6, primals_4 class OffsetNetNew(nn.Module): """OffsetNet in Temporal interlace module. The OffsetNet consists of one convolution layer and two fc layers with a relu activation following with a sigmoid function. Following the convolution layer, two fc layers and relu are applied to the output. Then, apply the sigmoid function with a multiply factor and a minus 0.5 to transform the output to (-4, 4). Args: in_channels (int): Channel num of input features. groups (int): Number of groups for fc layer outputs. num_segments (int): Number of frame segments. """ def __init__(self, in_channels, groups, num_segments): super().__init__() self.sigmoid = nn.Sigmoid() kernel_size = 3 padding = 1 self.conv = nn.Conv1d(in_channels, 1, kernel_size, padding=padding) self.fc1 = nn.Linear(num_segments, num_segments) self.relu = nn.ReLU() self.fc2 = nn.Linear(num_segments, groups) self.init_weights() def init_weights(self): """Initiate the parameters either from existing checkpoint or from scratch.""" self.fc2.bias.data[...] = 0.5108 def forward(self, input_0): primals_2 = self.conv.weight primals_3 = self.conv.bias primals_4 = self.fc1.weight primals_5 = self.fc1.bias primals_6 = self.fc2.weight primals_7 = self.fc2.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
Viditagarwal7479/Video-Swin-Transformer
OffsetNet
false
18,087
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
BinaryLogisticRegressionLoss
import torch import torch.nn as nn def binary_logistic_regression_loss(reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-05): """Binary Logistic Regression Loss.""" label = label.view(-1) reg_score = reg_score.contiguous().view(-1) pmask = (label > threshold).float() num_positive = max(torch.sum(pmask), 1) num_entries = len(label) ratio = num_entries / num_positive ratio = min(max(ratio, ratio_range[0]), ratio_range[1]) coef_0 = 0.5 * ratio / (ratio - 1) coef_1 = 0.5 * ratio loss = coef_1 * pmask * torch.log(reg_score + eps) + coef_0 * (1.0 - pmask ) * torch.log(1.0 - reg_score + eps) loss = -torch.mean(loss) return loss class BinaryLogisticRegressionLoss(nn.Module): """Binary Logistic Regression Loss. It will calculate binary logistic regression loss given reg_score and label. """ def forward(self, reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-05): """Calculate Binary Logistic Regression Loss. Args: reg_score (torch.Tensor): Predicted score by model. label (torch.Tensor): Groundtruth labels. threshold (float): Threshold for positive instances. Default: 0.5. ratio_range (tuple): Lower bound and upper bound for ratio. Default: (1.05, 21) eps (float): Epsilon for small value. Default: 1e-5. Returns: torch.Tensor: Returned binary logistic loss. """ return binary_logistic_regression_loss(reg_score, label, threshold, ratio_range, eps) 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_per_fused__to_copy_add_clamp_div_gt_log_mean_mul_neg_reciprocal_rsub_sub_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) tmp19 = tl.load(in_ptr1 + r0, None) tmp1 = 0.5 tmp2 = tmp0 > tmp1 tmp3 = tmp2.to(tl.float32) tmp4 = tl.broadcast_to(tmp3, [RBLOCK]) tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0)) tmp7 = 1.0 tmp8 = triton_helpers.maximum(tmp6, tmp7) tmp9 = tl.full([1], 1, tl.int32) tmp10 = tmp9 / tmp8 tmp11 = 256.0 tmp12 = tmp10 * tmp11 tmp13 = 1.05 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = 21.0 tmp16 = triton_helpers.minimum(tmp14, tmp15) tmp17 = tmp16 * tmp1 tmp18 = tmp17 * tmp3 tmp20 = 1e-05 tmp21 = tmp19 + tmp20 tmp22 = tl_math.log(tmp21) tmp23 = tmp18 * tmp22 tmp24 = tmp16 - tmp7 tmp25 = tmp17 / tmp24 tmp26 = tmp7 - tmp3 tmp27 = tmp25 * tmp26 tmp28 = tmp7 - tmp19 tmp29 = tmp28 + tmp20 tmp30 = tl_math.log(tmp29) tmp31 = tmp27 * tmp30 tmp32 = tmp23 + tmp31 tmp33 = tl.broadcast_to(tmp32, [RBLOCK]) tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0)) tmp36 = tmp35 / tmp11 tmp37 = -tmp36 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([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) buf2 = empty_strided_cuda((), (), torch.float32) buf3 = buf2 del buf2 get_raw_stream(0) triton_per_fused__to_copy_add_clamp_div_gt_log_mean_mul_neg_reciprocal_rsub_sub_sum_0[ grid(1)](buf3, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf3, def binary_logistic_regression_loss(reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-05): """Binary Logistic Regression Loss.""" label = label.view(-1) reg_score = reg_score.contiguous().view(-1) pmask = (label > threshold).float() num_positive = max(torch.sum(pmask), 1) num_entries = len(label) ratio = num_entries / num_positive ratio = min(max(ratio, ratio_range[0]), ratio_range[1]) coef_0 = 0.5 * ratio / (ratio - 1) coef_1 = 0.5 * ratio loss = coef_1 * pmask * torch.log(reg_score + eps) + coef_0 * (1.0 - pmask ) * torch.log(1.0 - reg_score + eps) loss = -torch.mean(loss) return loss class BinaryLogisticRegressionLossNew(nn.Module): """Binary Logistic Regression Loss. It will calculate binary logistic regression loss given reg_score and label. """ def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
Viditagarwal7479/Video-Swin-Transformer
BinaryLogisticRegressionLoss
false
18,088
[ "Apache-2.0" ]
9
37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
https://github.com/Viditagarwal7479/Video-Swin-Transformer/tree/37910ef3141c7b2eef76544f9ec8bdf26ec94c7d
CharbonnierLoss
import functools import torch import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import nn as nn from torch.nn import init as init from torchvision.models import vgg as vgg from torch import autograd as autograd def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are 'none', 'mean' and 'sum'. Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() else: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean'): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are 'none', 'mean' and 'sum'. Default: 'mean'. Returns: Tensor: Loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) > 1: weight = weight.sum() else: weight = weight.sum() * loss.size(1) loss = loss.sum() / weight return loss 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', **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.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', **kwargs): loss = loss_func(pred, target, **kwargs) loss = weight_reduce_loss(loss, weight, reduction) return loss return wrapper @weighted_loss def charbonnier_loss(pred, target, eps=1e-12): return torch.sqrt((pred - target) ** 2 + eps) class CharbonnierLoss(nn.Module): """Charbonnier loss (one variant of Robust L1Loss, a differentiable variant of L1Loss). Described in "Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution". Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', eps=1e-12): super(CharbonnierLoss, self).__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.eps = eps def forward(self, pred, target, weight=None, **kwargs): """ Args: pred (Tensor): of shape (N, C, H, W). Predicted tensor. target (Tensor): of shape (N, C, H, W). Ground truth tensor. weight (Tensor, optional): of shape (N, C, H, W). Element-wise weights. Default: None. """ return self.loss_weight * charbonnier_loss(pred, target, weight, eps=self.eps, reduction=self.reduction) 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 functools import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import 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 @triton.jit def triton_per_fused_add_mean_mul_pow_sqrt_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) tmp1 = tl.load(in_ptr1 + r0, None) tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp4 = 1e-12 tmp5 = tmp3 + tmp4 tmp6 = libdevice.sqrt(tmp5) tmp7 = tl.broadcast_to(tmp6, [RBLOCK]) tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0)) tmp10 = 256.0 tmp11 = tmp9 / tmp10 tmp12 = 1.0 tmp13 = tmp11 * tmp12 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp13, 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_add_mean_mul_pow_sqrt_sub_0[grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are 'none', 'mean' and 'sum'. Returns: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() else: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean'): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in losses of PyTorch. Options are 'none', 'mean' and 'sum'. Default: 'mean'. Returns: Tensor: Loss values. """ if weight is not None: assert weight.dim() == loss.dim() assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if weight is None or reduction == 'sum': loss = reduce_loss(loss, reduction) elif reduction == 'mean': if weight.size(1) > 1: weight = weight.sum() else: weight = weight.sum() * loss.size(1) loss = loss.sum() / weight return loss 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', **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.5000) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, reduction='sum') tensor(3.) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', **kwargs): loss = loss_func(pred, target, **kwargs) loss = weight_reduce_loss(loss, weight, reduction) return loss return wrapper @weighted_loss def charbonnier_loss(pred, target, eps=1e-12): return torch.sqrt((pred - target) ** 2 + eps) class CharbonnierLossNew(nn.Module): """Charbonnier loss (one variant of Robust L1Loss, a differentiable variant of L1Loss). Described in "Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution". Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', eps=1e-12): super(CharbonnierLossNew, self).__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError( f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}' ) self.loss_weight = loss_weight self.reduction = reduction self.eps = eps def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
WoojunePark/BasicSR
CharbonnierLoss
false
18,089
[ "Apache-2.0" ]
9
e0910b022b924bb913045fc412a5470dc2242cf0
https://github.com/WoojunePark/BasicSR/tree/e0910b022b924bb913045fc412a5470dc2242cf0
Decoder
from _paritybench_helpers import _mock_config import torch import torch.nn as nn class Decoder(nn.Module): def __init__(self, config): super(Decoder, self).__init__() self.linear = nn.Linear(config.hidden_size, 2) def forward(self, x, encoder_output): y = self.linear(encoder_output) return y + x def get_inputs(): return [torch.rand([4, 4, 4, 2]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(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 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_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 128 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') tmp3 = tl.load(in_ptr1 + x2, xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (2, 4), (4, 1)) assert_size_stride(primals_2, (2,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4, 4, 2), (32, 8, 2, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 2), (2, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 2), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 2), (32, 8, 2, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_add_0[grid(128)](buf1, primals_2, primals_4, 128, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 del primals_4 return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0) class DecoderNew(nn.Module): def __init__(self, config): super(DecoderNew, self).__init__() self.linear = nn.Linear(config.hidden_size, 2) def forward(self, input_0, input_1): primals_1 = self.linear.weight primals_2 = self.linear.bias primals_4 = input_0 primals_3 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
XIAOYEJIAYOU/GSAN
Decoder
false
18,090
[ "MIT" ]
6
8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
https://github.com/XIAOYEJIAYOU/GSAN/tree/8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
MaxPool1d
import torch import torch.nn as nn class MaxPool1d(nn.Module): def __init__(self, win=2, stride=None, pad=0): super().__init__() self.pooling = nn.MaxPool1d(kernel_size=win, stride=stride, padding=pad ) def forward(self, x): """ Args: x: shape=(batch_size, max_seq_len, dim) """ x = x.permute(0, 2, 1) x = self.pooling(x).permute(0, 2, 1) return x 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 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_max_pool2d_with_indices_0(in_ptr0, 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 % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 8 * x1), xmask) tmp1 = tl.load(in_ptr0 + (4 + x0 + 8 * x1), xmask) tmp2 = triton_helpers.maximum(tmp1, tmp0) tl.store(out_ptr0 + x2, tmp2, 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, 2), (8, 1, 32, 4), torch.float32) get_raw_stream(0) triton_poi_fused_max_pool2d_with_indices_0[grid(32)](arg0_1, buf0, 32, XBLOCK=32, num_warps=1, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 2, 4), (8, 4, 1), 0), class MaxPool1dNew(nn.Module): def __init__(self, win=2, stride=None, pad=0): super().__init__() self.pooling = nn.MaxPool1d(kernel_size=win, stride=stride, padding=pad ) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
WiseDoge/Text-Classification-PyTorch
MaxPool1d
false
18,091
[ "MIT" ]
6
9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
https://github.com/WiseDoge/Text-Classification-PyTorch/tree/9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
SelfExpression
import torch import torch.nn as nn class SelfExpression(nn.Module): def __init__(self, n): super(SelfExpression, self).__init__() self.Coefficient = nn.Parameter(1e-08 * torch.ones(n, n, dtype= torch.float32), requires_grad=True) def forward(self, x): y = torch.matmul(self.Coefficient, x) return y def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'n': 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_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 64 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 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (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_clone_0[grid(64, 4)](primals_2, buf0, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf1) del primals_1 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_clone_0[grid(64, 4)](buf1, buf2, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del buf1 return buf2, reinterpret_tensor(buf0, (64, 4), (4, 1), 0) class SelfExpressionNew(nn.Module): def __init__(self, n): super(SelfExpressionNew, self).__init__() self.Coefficient = nn.Parameter(1e-08 * torch.ones(n, n, dtype= torch.float32), requires_grad=True) def forward(self, input_0): primals_1 = self.Coefficient primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
Xanadu12138/DSCN-superpixels
SelfExpression
false
18,092
[ "MIT" ]
4
babe16edde9c61699ef203effbfc9f03246765f3
https://github.com/Xanadu12138/DSCN-superpixels/tree/babe16edde9c61699ef203effbfc9f03246765f3
ConvAE
import math import torch import torch.nn as nn import torch.nn.functional as F class Conv2dSamePad(nn.Module): """ Implement Tensorflow's 'SAME' padding mode in Conv2d. When an odd number, say `m`, of pixels are need to pad, Tensorflow will pad one more column at right or one more row at bottom. But Pytorch will pad `m+1` pixels, i.e., Pytorch always pads in both sides. So we can pad the tensor in the way of Tensorflow before call the Conv2d module. """ def __init__(self, kernel_size, stride): super(Conv2dSamePad, self).__init__() self.kernel_size = kernel_size if type(kernel_size) in [list, tuple ] else [kernel_size, kernel_size] self.stride = stride if type(stride) in [list, tuple] else [stride, stride] def forward(self, x): in_height = x.size(2) in_width = x.size(3) out_height = math.ceil(float(in_height) / float(self.stride[0])) out_width = math.ceil(float(in_width) / float(self.stride[1])) pad_along_height = (out_height - 1) * self.stride[0 ] + self.kernel_size[0] - in_height pad_along_width = (out_width - 1) * self.stride[1] + self.kernel_size[1 ] - in_width pad_top = math.floor(pad_along_height / 2) pad_left = math.floor(pad_along_width / 2) pad_bottom = pad_along_height - pad_top pad_right = pad_along_width - pad_left return F.pad(x, [pad_left, pad_right, pad_top, pad_bottom], 'constant', 0) class ConvTranspose2dSamePad(nn.Module): """ This module implements the "SAME" padding mode for ConvTranspose2d as in Tensorflow. A tensor with width w_in, feed it to ConvTranspose2d(ci, co, kernel, stride), the width of output tensor T_nopad: w_nopad = (w_in - 1) * stride + kernel If we use padding, i.e., ConvTranspose2d(ci, co, kernel, stride, padding, output_padding), the width of T_pad: w_pad = (w_in - 1) * stride + kernel - (2*padding - output_padding) = w_nopad - (2*padding - output_padding) Yes, in ConvTranspose2d, more padding, the resulting tensor is smaller, i.e., the padding is actually deleting row/col. If `pad`=(2*padding - output_padding) is odd, Pytorch deletes more columns in the left, i.e., the first ceil(pad/2) and last `pad - ceil(pad/2)` columns of T_nopad are deleted to get T_pad. In contrast, Tensorflow deletes more columns in the right, i.e., the first floor(pad/2) and last `pad - floor(pad/2)` columns are deleted. For the height, Pytorch deletes more rows at top, while Tensorflow at bottom. In practice, we usually want `w_pad = w_in * stride`, i.e., the "SAME" padding mode in Tensorflow, so the number of columns to delete: pad = 2*padding - output_padding = kernel - stride We can solve the above equation and get: padding = ceil((kernel - stride)/2), and output_padding = 2*padding - (kernel - stride) which is either 1 or 0. But to get the same result with Tensorflow, we should delete values by ourselves instead of using padding and output_padding in ConvTranspose2d. To get there, we check the following conditions: If pad = kernel - stride is even, we can directly set padding=pad/2 and output_padding=0 in ConvTranspose2d. If pad = kernel - stride is odd, we can use ConvTranspose2d to get T_nopad, and then delete `pad` rows/columns by ourselves; or we can use ConvTranspose2d to delete `pad - 1` by setting `padding=(pad - 1) / 2` and `ouput_padding=0` and then delete the last row/column of the resulting tensor by ourselves. Here we implement the former case. This module should be called after the ConvTranspose2d module with shared kernel_size and stride values. And this module can only output a tensor with shape `stride * size_input`. A more flexible module can be found in `yaleb.py` which can output arbitrary size as specified. """ def __init__(self, kernel_size, stride): super(ConvTranspose2dSamePad, self).__init__() self.kernel_size = kernel_size if type(kernel_size) in [list, tuple ] else [kernel_size, kernel_size] self.stride = stride if type(stride) in [list, tuple] else [stride, stride] def forward(self, x): in_height = x.size(2) in_width = x.size(3) pad_height = self.kernel_size[0] - self.stride[0] pad_width = self.kernel_size[1] - self.stride[1] pad_top = pad_height // 2 pad_bottom = pad_height - pad_top pad_left = pad_width // 2 pad_right = pad_width - pad_left return x[:, :, pad_top:in_height - pad_bottom, pad_left:in_width - pad_right] class ConvAE(nn.Module): def __init__(self, channels, kernels): """ param: channels: a list containing all channels in the network. kernels: a list containing all kernels in the network. """ super(ConvAE, self).__init__() self.encoder = nn.Sequential() for i in range(len(channels) - 1): self.encoder.add_module('pad%d' % (i + 1), Conv2dSamePad( kernels[i], 2)) self.encoder.add_module('conv%d' % (i + 1), nn.Conv2d(channels[ i], channels[i + 1], kernel_size=kernels[i], stride=2)) self.encoder.add_module('relu%d' % (i + 1), nn.ReLU(True)) channels = list(reversed(channels)) kernels = list(reversed(kernels)) self.decoder = nn.Sequential() for i in range(len(channels) - 1): self.decoder.add_module('deconv%d' % (i + 1), nn. ConvTranspose2d(channels[i], channels[i + 1], kernel_size= kernels[i], stride=2)) self.decoder.add_module('pad%d' % i, ConvTranspose2dSamePad( kernels[i], 2)) self.decoder.add_module('relu%d' % i, nn.ReLU(True)) def forward(self, x): hidden = self.encoder(x) y = self.decoder(hidden) return y def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'channels': [4, 4], 'kernels': [4, 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 math import torch.nn as nn import torch.nn.functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 576 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 6 % 6 x0 = xindex % 6 x2 = xindex // 36 x4 = xindex tmp0 = -1 + x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = -1 + x0 tmp6 = tmp5 >= tmp1 tmp7 = tmp5 < tmp3 tmp8 = tmp2 & tmp4 tmp9 = tmp8 & tmp6 tmp10 = tmp9 & tmp7 tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask, other=0.0) tl.store(out_ptr0 + x4, tmp11, xmask) @triton.jit def triton_poi_fused_convolution_relu_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 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_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 576 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 6 % 6 x0 = xindex % 6 x4 = xindex x2 = xindex // 36 % 4 tmp24 = tl.load(in_out_ptr0 + x4, xmask) tmp25 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last') tmp0 = x1 tmp1 = tl.full([1], 1, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 5, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = x0 tmp7 = tmp6 >= tmp1 tmp8 = tmp6 < tmp3 tmp9 = tmp7 & tmp8 tmp10 = tmp9 & tmp5 tmp11 = tl.load(in_out_ptr0 + x4, tmp10 & xmask, other=0.0) tmp12 = tl.load(in_ptr0 + x2, tmp10 & xmask, eviction_policy= 'evict_last', other=0.0) tmp13 = tmp11 + tmp12 tmp14 = tl.full([1], 0, tl.int32) tmp15 = triton_helpers.maximum(tmp14, tmp13) tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype) tmp17 = tl.where(tmp10, tmp15, tmp16) tmp18 = tl.load(in_out_ptr0 + x4, tmp5 & xmask, other=0.0) tmp19 = tl.load(in_ptr0 + x2, tmp5 & xmask, eviction_policy= 'evict_last', other=0.0) tmp20 = tmp18 + tmp19 tmp21 = tl.where(tmp9, tmp17, tmp20) tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype) tmp23 = tl.where(tmp5, tmp21, tmp22) tmp26 = tmp24 + tmp25 tmp27 = tl.where(tmp5, tmp23, tmp26) tl.store(in_out_ptr0 + x4, tmp27, xmask) @triton.jit def triton_poi_fused_threshold_backward_3(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 x1 = xindex // 4 % 4 x2 = xindex // 16 x3 = xindex tmp0 = tl.load(in_ptr0 + (7 + x0 + 6 * x1 + 36 * x2), xmask) tmp1 = 0.0 tmp2 = tmp0 <= tmp1 tl.store(out_ptr0 + x3, tmp2, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 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, 6, 6), (144, 36, 6, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(576)](primals_1, buf0, 576, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(buf0, primals_2, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 4, 2, 2), (16, 4, 2, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_relu_1[grid(64)](buf2, primals_3, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 buf3 = extern_kernels.convolution(buf2, primals_4, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 4, 6, 6), (144, 36, 6, 1)) buf4 = buf3 del buf3 triton_poi_fused_convolution_relu_2[grid(576)](buf4, primals_5, 576, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_threshold_backward_3[grid(256)](buf4, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1) return reinterpret_tensor(buf4, (4, 4, 4, 4), (144, 36, 6, 1), 7 ), primals_2, primals_4, buf0, buf2, buf5 class Conv2dSamePad(nn.Module): """ Implement Tensorflow's 'SAME' padding mode in Conv2d. When an odd number, say `m`, of pixels are need to pad, Tensorflow will pad one more column at right or one more row at bottom. But Pytorch will pad `m+1` pixels, i.e., Pytorch always pads in both sides. So we can pad the tensor in the way of Tensorflow before call the Conv2d module. """ def __init__(self, kernel_size, stride): super(Conv2dSamePad, self).__init__() self.kernel_size = kernel_size if type(kernel_size) in [list, tuple ] else [kernel_size, kernel_size] self.stride = stride if type(stride) in [list, tuple] else [stride, stride] def forward(self, x): in_height = x.size(2) in_width = x.size(3) out_height = math.ceil(float(in_height) / float(self.stride[0])) out_width = math.ceil(float(in_width) / float(self.stride[1])) pad_along_height = (out_height - 1) * self.stride[0 ] + self.kernel_size[0] - in_height pad_along_width = (out_width - 1) * self.stride[1] + self.kernel_size[1 ] - in_width pad_top = math.floor(pad_along_height / 2) pad_left = math.floor(pad_along_width / 2) pad_bottom = pad_along_height - pad_top pad_right = pad_along_width - pad_left return F.pad(x, [pad_left, pad_right, pad_top, pad_bottom], 'constant', 0) class ConvTranspose2dSamePad(nn.Module): """ This module implements the "SAME" padding mode for ConvTranspose2d as in Tensorflow. A tensor with width w_in, feed it to ConvTranspose2d(ci, co, kernel, stride), the width of output tensor T_nopad: w_nopad = (w_in - 1) * stride + kernel If we use padding, i.e., ConvTranspose2d(ci, co, kernel, stride, padding, output_padding), the width of T_pad: w_pad = (w_in - 1) * stride + kernel - (2*padding - output_padding) = w_nopad - (2*padding - output_padding) Yes, in ConvTranspose2d, more padding, the resulting tensor is smaller, i.e., the padding is actually deleting row/col. If `pad`=(2*padding - output_padding) is odd, Pytorch deletes more columns in the left, i.e., the first ceil(pad/2) and last `pad - ceil(pad/2)` columns of T_nopad are deleted to get T_pad. In contrast, Tensorflow deletes more columns in the right, i.e., the first floor(pad/2) and last `pad - floor(pad/2)` columns are deleted. For the height, Pytorch deletes more rows at top, while Tensorflow at bottom. In practice, we usually want `w_pad = w_in * stride`, i.e., the "SAME" padding mode in Tensorflow, so the number of columns to delete: pad = 2*padding - output_padding = kernel - stride We can solve the above equation and get: padding = ceil((kernel - stride)/2), and output_padding = 2*padding - (kernel - stride) which is either 1 or 0. But to get the same result with Tensorflow, we should delete values by ourselves instead of using padding and output_padding in ConvTranspose2d. To get there, we check the following conditions: If pad = kernel - stride is even, we can directly set padding=pad/2 and output_padding=0 in ConvTranspose2d. If pad = kernel - stride is odd, we can use ConvTranspose2d to get T_nopad, and then delete `pad` rows/columns by ourselves; or we can use ConvTranspose2d to delete `pad - 1` by setting `padding=(pad - 1) / 2` and `ouput_padding=0` and then delete the last row/column of the resulting tensor by ourselves. Here we implement the former case. This module should be called after the ConvTranspose2d module with shared kernel_size and stride values. And this module can only output a tensor with shape `stride * size_input`. A more flexible module can be found in `yaleb.py` which can output arbitrary size as specified. """ def __init__(self, kernel_size, stride): super(ConvTranspose2dSamePad, self).__init__() self.kernel_size = kernel_size if type(kernel_size) in [list, tuple ] else [kernel_size, kernel_size] self.stride = stride if type(stride) in [list, tuple] else [stride, stride] def forward(self, x): in_height = x.size(2) in_width = x.size(3) pad_height = self.kernel_size[0] - self.stride[0] pad_width = self.kernel_size[1] - self.stride[1] pad_top = pad_height // 2 pad_bottom = pad_height - pad_top pad_left = pad_width // 2 pad_right = pad_width - pad_left return x[:, :, pad_top:in_height - pad_bottom, pad_left:in_width - pad_right] class ConvAENew(nn.Module): def __init__(self, channels, kernels): """ param: channels: a list containing all channels in the network. kernels: a list containing all kernels in the network. """ super(ConvAENew, self).__init__() self.encoder = nn.Sequential() for i in range(len(channels) - 1): self.encoder.add_module('pad%d' % (i + 1), Conv2dSamePad( kernels[i], 2)) self.encoder.add_module('conv%d' % (i + 1), nn.Conv2d(channels[ i], channels[i + 1], kernel_size=kernels[i], stride=2)) self.encoder.add_module('relu%d' % (i + 1), nn.ReLU(True)) channels = list(reversed(channels)) kernels = list(reversed(kernels)) self.decoder = nn.Sequential() for i in range(len(channels) - 1): self.decoder.add_module('deconv%d' % (i + 1), nn. ConvTranspose2d(channels[i], channels[i + 1], kernel_size= kernels[i], stride=2)) self.decoder.add_module('pad%d' % i, ConvTranspose2dSamePad( kernels[i], 2)) self.decoder.add_module('relu%d' % i, nn.ReLU(True)) def forward(self, input_0): primals_1 = self.encoder.conv1.weight primals_3 = self.encoder.conv1.bias primals_2 = self.decoder.deconv1.weight primals_5 = self.decoder.deconv1.bias primals_4 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
Xanadu12138/DSCN-superpixels
ConvAE
false
18,093
[ "MIT" ]
4
babe16edde9c61699ef203effbfc9f03246765f3
https://github.com/Xanadu12138/DSCN-superpixels/tree/babe16edde9c61699ef203effbfc9f03246765f3
FeedForward
import torch import torch.nn as nn import torch.cuda class FeedForward(nn.Module): def __init__(self, hidden_size, inner_size, dropout): super(FeedForward, self).__init__() self.linear_in = nn.Linear(hidden_size, inner_size, bias=False) self.linear_out = nn.Linear(inner_size, hidden_size, bias=False) self.relu = nn.ReLU() self.dropout = nn.Dropout(dropout) self.reset_parameters() def reset_parameters(self): nn.init.xavier_uniform_(self.linear_in.weight) nn.init.xavier_uniform_(self.linear_out.weight) def forward(self, x): y = self.linear_in(x) y = self.relu(y) y = self.dropout(y) y = self.linear_out(y) return y def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'hidden_size': 4, 'inner_size': 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 import triton_helpers import torch.nn as nn import torch.cuda 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, 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.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp3 = 0.0 tmp4 = tmp2 <= tmp3 tl.store(in_out_ptr0 + x0, tmp2, xmask) 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, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4, 4), (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_2, (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 buf3 = 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, buf3, 256, XBLOCK=128, 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_3, (4, 4), (1, 4), 0), out=buf2) return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_2, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), primals_3, buf3 class FeedForwardNew(nn.Module): def __init__(self, hidden_size, inner_size, dropout): super(FeedForwardNew, self).__init__() self.linear_in = nn.Linear(hidden_size, inner_size, bias=False) self.linear_out = nn.Linear(inner_size, hidden_size, bias=False) self.relu = nn.ReLU() self.dropout = nn.Dropout(dropout) self.reset_parameters() def reset_parameters(self): nn.init.xavier_uniform_(self.linear_in.weight) nn.init.xavier_uniform_(self.linear_out.weight) def forward(self, input_0): primals_1 = self.linear_in.weight primals_3 = self.linear_out.weight primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
XL2248/VHM
FeedForward
false
18,094
[ "MIT" ]
8
d6c21938f7cf095590b35e6ae7e0ef2b27d430f8
https://github.com/XL2248/VHM/tree/d6c21938f7cf095590b35e6ae7e0ef2b27d430f8
CNNLayer
import torch import torch.nn as nn class CNNLayer(nn.Module): """Conv1d layer. nn.Conv1d layer require the input shape is (batch_size, in_channels, length), however, our input shape is (batch_size, length, in_channels), so we need to transpose our input data into (B, C, L_in) and send it to conv layer, and then transpose the conv output into (B, L_out, C). """ def __init__(self, in_dim, out_dim, win=3, pad=1): super().__init__() self.conv = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=win, padding=pad) def forward(self, x): """ Args: x: shape=(batch_size, max_seq_len, input_dim) """ x = x.permute(0, 2, 1) out = self.conv(x).permute(0, 2, 1) return out def get_inputs(): return [torch.rand([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 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_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_convolution_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 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) 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, 3), (12, 3, 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_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf1, (4, 4, 4), (16, 4, 1)) del buf0 buf2 = buf1 del buf1 triton_poi_fused_convolution_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 ), primals_2, reinterpret_tensor(primals_1, (4, 4, 4), (16, 1, 4), 0) class CNNLayerNew(nn.Module): """Conv1d layer. nn.Conv1d layer require the input shape is (batch_size, in_channels, length), however, our input shape is (batch_size, length, in_channels), so we need to transpose our input data into (B, C, L_in) and send it to conv layer, and then transpose the conv output into (B, L_out, C). """ def __init__(self, in_dim, out_dim, win=3, pad=1): super().__init__() self.conv = nn.Conv1d(in_channels=in_dim, out_channels=out_dim, kernel_size=win, padding=pad) 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]
WiseDoge/Text-Classification-PyTorch
CNNLayer
false
18,095
[ "MIT" ]
6
9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
https://github.com/WiseDoge/Text-Classification-PyTorch/tree/9371eeed6bd7ecf1d529c8f2a6c997fcde67a559
AttentiveStatsPooling
import torch import torch.nn as nn class AttentiveStatsPooling(nn.Module): """ The attentive statistics pooling layer uses an attention mechanism to give different weights to different frames and generates not only weighted means but also weighted variances, to form utterance-level features from frame-level features "Attentive Statistics Pooling for Deep Speaker Embedding", Okabe et al., https://arxiv.org/abs/1803.10963 """ def __init__(self, input_size, hidden_size, eps=1e-06): super(AttentiveStatsPooling, self).__init__() self.eps = eps self.in_linear = nn.Linear(input_size, hidden_size) self.out_linear = nn.Linear(hidden_size, input_size) def forward(self, encodings): """ Given encoder outputs of shape [B, DE, T], return pooled outputs of shape [B, DE * 2] B: batch size T: maximum number of time steps (frames) DE: encoding output size """ energies = self.out_linear(torch.tanh(self.in_linear(encodings. transpose(1, 2)))).transpose(1, 2) alphas = torch.softmax(energies, dim=2) means = torch.sum(alphas * encodings, dim=2) residuals = torch.sum(alphas * encodings ** 2, dim=2) - means ** 2 stds = torch.sqrt(residuals.clamp(min=self.eps)) return torch.cat([means, stds], dim=1) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_size': 4, '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 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_clone_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 % 4 x1 = xindex // 4 % 4 x2 = xindex // 16 % 4 x3 = xindex // 64 x4 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask) tl.store(out_ptr0 + x4, tmp0, xmask) @triton.jit def triton_poi_fused_add_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) @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 = 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_3(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) @triton.jit def triton_poi_fused_clamp_mul_pow_sqrt_sub_sum_4(in_ptr0, in_ptr1, out_ptr0, out_ptr2, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex // 16 x3 = xindex % 16 x0 = xindex % 4 x4 = xindex // 4 tmp0 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask) tmp1 = tl.load(in_ptr1 + (x0 + 16 * x4), xmask) tmp3 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask) tmp4 = tl.load(in_ptr1 + (4 + x0 + 16 * x4), xmask) tmp7 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask) tmp8 = tl.load(in_ptr1 + (8 + x0 + 16 * x4), xmask) tmp11 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask) tmp12 = tl.load(in_ptr1 + (12 + x0 + 16 * x4), xmask) tmp2 = tmp0 * tmp1 tmp5 = tmp3 * tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 * tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 * tmp12 tmp14 = tmp10 + tmp13 tmp15 = tmp1 * tmp1 tmp16 = tmp0 * tmp15 tmp17 = tmp4 * tmp4 tmp18 = tmp3 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp8 * tmp8 tmp21 = tmp7 * tmp20 tmp22 = tmp19 + tmp21 tmp23 = tmp12 * tmp12 tmp24 = tmp11 * tmp23 tmp25 = tmp22 + tmp24 tmp26 = tmp14 * tmp14 tmp27 = tmp25 - tmp26 tmp28 = 1e-06 tmp29 = triton_helpers.maximum(tmp27, tmp28) tmp30 = libdevice.sqrt(tmp29) tl.store(out_ptr0 + (x3 + 32 * x2), tmp14, xmask) tl.store(out_ptr2 + (x3 + 32 * x2), tmp30, 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((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(256)](primals_1, buf0, 256, XBLOCK= 256, num_warps=4, num_stages=1) buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (64, 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, 4), (64, 16, 4, 1), 0) del buf1 triton_poi_fused_add_tanh_1[grid(256)](buf2, primals_3, 256, XBLOCK =128, num_warps=4, num_stages=1) del primals_3 buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_5 buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 4, 16, 1), torch.float32) triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=128, num_warps=4, num_stages=1) buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 4, 16, 1), torch.float32) triton_poi_fused__softmax_3[grid(256)](buf4, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf4 buf9 = empty_strided_cuda((4, 8, 4), (32, 4, 1), torch.float32) buf6 = reinterpret_tensor(buf9, (4, 4, 4), (32, 4, 1), 0) buf8 = reinterpret_tensor(buf9, (4, 4, 4), (32, 4, 1), 16) triton_poi_fused_clamp_mul_pow_sqrt_sub_sum_4[grid(64)](buf5, primals_1, buf6, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf5 return buf9, primals_1, reinterpret_tensor(buf0, (64, 4), (4, 1), 0 ), buf2, buf3, primals_4 class AttentiveStatsPoolingNew(nn.Module): """ The attentive statistics pooling layer uses an attention mechanism to give different weights to different frames and generates not only weighted means but also weighted variances, to form utterance-level features from frame-level features "Attentive Statistics Pooling for Deep Speaker Embedding", Okabe et al., https://arxiv.org/abs/1803.10963 """ def __init__(self, input_size, hidden_size, eps=1e-06): super(AttentiveStatsPoolingNew, self).__init__() self.eps = eps self.in_linear = nn.Linear(input_size, hidden_size) self.out_linear = nn.Linear(hidden_size, input_size) def forward(self, input_0): primals_2 = self.in_linear.weight primals_3 = self.in_linear.bias primals_4 = self.out_linear.weight primals_5 = self.out_linear.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
Wadaboa/titanet
AttentiveStatsPooling
false
18,096
[ "MIT" ]
4
b07e3074e79ea8c1129fb0adb8315e06bb4943ea
https://github.com/Wadaboa/titanet/tree/b07e3074e79ea8c1129fb0adb8315e06bb4943ea
AutoEncoder
import torch import torch.nn as nn class AutoEncoder(nn.Module): def __init__(self, channels): """ param: channels: a list containing all channels in the network. """ super(AutoEncoder, self).__init__() self.encoder = nn.Sequential() for i in range(len(channels) - 1): self.encoder.add_module('fc%d' % (i + 1), nn.Linear(channels[i], channels[i + 1])) self.encoder.add_module('relu%d' % (i + 1), nn.ReLU(True)) channels = list(reversed(channels)) self.decoder = nn.Sequential() for i in range(len(channels) - 1): self.decoder.add_module('deconv%d' % (i + 1), nn.Linear( channels[i], channels[i + 1])) self.decoder.add_module('relu%d' % i, nn.ReLU(True)) def forward(self, x): hidden = self.encoder(x) y = self.decoder(hidden) return y def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'channels': [4, 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): 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 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, xmask) tl.store(out_ptr0 + x4, tmp6, xmask) @triton.jit def triton_poi_fused_view_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 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * (x1 % 4 // 4) + 64 * ((4 * (x1 // 4 % 4) + x1 % 4) // 16)), xmask) tl.store(out_ptr0 + x2, tmp0, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_view_2(in_out_ptr0, 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 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 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(out_ptr0 + x4, tmp4, xmask) tl.store(out_ptr1 + x4, tmp6, 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.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 buf7 = 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, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) triton_poi_fused_view_1[grid(256)](buf1, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1) buf3 = reinterpret_tensor(buf1, (64, 4), (4, 1), 0) del buf1 extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4 ), 0), out=buf3) buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf3 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_view_2[grid(256)](buf4, primals_5, buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf4 del primals_5 return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf2, buf6, primals_4, buf7 class AutoEncoderNew(nn.Module): def __init__(self, channels): """ param: channels: a list containing all channels in the network. """ super(AutoEncoderNew, self).__init__() self.encoder = nn.Sequential() for i in range(len(channels) - 1): self.encoder.add_module('fc%d' % (i + 1), nn.Linear(channels[i], channels[i + 1])) self.encoder.add_module('relu%d' % (i + 1), nn.ReLU(True)) channels = list(reversed(channels)) self.decoder = nn.Sequential() for i in range(len(channels) - 1): self.decoder.add_module('deconv%d' % (i + 1), nn.Linear( channels[i], channels[i + 1])) self.decoder.add_module('relu%d' % i, nn.ReLU(True)) def forward(self, input_0): primals_1 = self.encoder.fc1.weight primals_2 = self.encoder.fc1.bias primals_4 = self.decoder.deconv1.weight primals_5 = self.decoder.deconv1.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
Xanadu12138/DSCN-superpixels
AutoEncoder
false
18,097
[ "MIT" ]
4
babe16edde9c61699ef203effbfc9f03246765f3
https://github.com/Xanadu12138/DSCN-superpixels/tree/babe16edde9c61699ef203effbfc9f03246765f3
SAM_Loss
import torch import torch.nn as nn class SAM_Loss(nn.Module): def __init__(self): super(SAM_Loss, self).__init__() def forward(self, output, label): ratio = torch.sum((output + 1e-08).mul(label + 1e-08), dim=1 ) / torch.sqrt(torch.sum((output + 1e-08).mul(output + 1e-08), dim=1) * torch.sum((label + 1e-08).mul(label + 1e-08), dim=1)) angle = torch.acos(ratio) return torch.mean(angle) 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.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 @triton.jit def triton_per_fused_acos_add_div_mean_mul_sqrt_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 % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp12 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp16 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp19 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp23 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp27 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp1 = 1e-08 tmp2 = tmp0 + tmp1 tmp3 = tmp2 * tmp2 tmp5 = tmp4 + tmp1 tmp6 = tmp5 * tmp5 tmp7 = tmp3 + tmp6 tmp9 = tmp8 + tmp1 tmp10 = tmp9 * tmp9 tmp11 = tmp7 + tmp10 tmp13 = tmp12 + tmp1 tmp14 = tmp13 * tmp13 tmp15 = tmp11 + tmp14 tmp17 = tmp16 + tmp1 tmp18 = tmp17 * tmp17 tmp20 = tmp19 + tmp1 tmp21 = tmp20 * tmp20 tmp22 = tmp18 + tmp21 tmp24 = tmp23 + tmp1 tmp25 = tmp24 * tmp24 tmp26 = tmp22 + tmp25 tmp28 = tmp27 + tmp1 tmp29 = tmp28 * tmp28 tmp30 = tmp26 + tmp29 tmp31 = tmp15 * tmp30 tmp32 = tmp2 * tmp17 tmp33 = tmp5 * tmp20 tmp34 = tmp32 + tmp33 tmp35 = tmp9 * tmp24 tmp36 = tmp34 + tmp35 tmp37 = tmp13 * tmp28 tmp38 = tmp36 + tmp37 tmp39 = libdevice.sqrt(tmp31) tmp40 = tmp38 / tmp39 tmp41 = libdevice.acos(tmp40) tmp42 = tl.broadcast_to(tmp41, [XBLOCK, RBLOCK]) tmp44 = tl.sum(tmp42, 1)[:, None] tmp45 = 64.0 tmp46 = tmp44 / tmp45 tl.debug_barrier() tl.store(in_out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp46, 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) buf2 = empty_strided_cuda((), (), torch.float32) buf3 = buf2 del buf2 get_raw_stream(0) triton_per_fused_acos_add_div_mean_mul_sqrt_sum_0[grid(1)](buf3, arg0_1, arg1_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf3, class SAM_LossNew(nn.Module): def __init__(self): super(SAM_LossNew, self).__init__() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
XiuhengWang/Sylvester_TSFN_MDC_HSI_superresolution
SAM_Loss
false
18,098
[ "MIT" ]
5
f70799c931d44d5d6cac635ef539a38bc573c7d9
https://github.com/XiuhengWang/Sylvester_TSFN_MDC_HSI_superresolution/tree/f70799c931d44d5d6cac635ef539a38bc573c7d9
LinearRegression
import torch import torch.nn as nn class LinearRegression(nn.Module): def __init__(self, hidden_size): super(LinearRegression, self).__init__() self.linear1 = nn.Linear(hidden_size, 3) def forward(self, x, mask): y = self.linear1(x) y = y * mask return y.view(-1, 3) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 3])] 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 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_mul_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 3 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + x2, xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (3, 4), (4, 1)) assert_size_stride(primals_2, (3,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4, 4, 3), (48, 12, 3, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 3), (3, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 3), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 3), (48, 12, 3, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_mul_0[grid(192)](buf1, primals_2, primals_4, 192, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 return reinterpret_tensor(buf1, (64, 3), (3, 1), 0 ), primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0) class LinearRegressionNew(nn.Module): def __init__(self, hidden_size): super(LinearRegressionNew, self).__init__() self.linear1 = nn.Linear(hidden_size, 3) def forward(self, input_0, input_1): primals_1 = self.linear1.weight primals_2 = self.linear1.bias primals_3 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
XIAOYEJIAYOU/GSAN
LinearRegression
false
18,099
[ "MIT" ]
6
8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
https://github.com/XIAOYEJIAYOU/GSAN/tree/8ca4fdf4c3d615af9cc10e1f9f22ceb7e27fe196
Q_Critic
import torch import torch.nn as nn import torch.nn.functional as F class Q_Critic(nn.Module): def __init__(self, state_dim, action_dim, net_width): super(Q_Critic, self).__init__() self.l1 = nn.Linear(state_dim + action_dim, net_width) self.l2 = nn.Linear(net_width, net_width) self.l3 = nn.Linear(net_width, 1) self.l4 = nn.Linear(state_dim + action_dim, net_width) self.l5 = nn.Linear(net_width, net_width) self.l6 = nn.Linear(net_width, 1) def forward(self, state, action): sa = torch.cat([state, action], 1) q1 = F.relu(self.l1(sa)) q1 = F.relu(self.l2(q1)) q1 = self.l3(q1) q2 = F.relu(self.l4(sa)) q2 = F.relu(self.l5(q2)) q2 = self.l6(q2) return q1, q2 def Q1(self, state, action): sa = torch.cat([state, action], 1) q1 = F.relu(self.l1(sa)) q1 = F.relu(self.l2(q1)) q1 = self.l3(q1) return q1 def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'state_dim': 4, 'action_dim': 4, 'net_width': 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 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) 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, 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, (1, 4), (4, 1)) assert_size_stride(primals_8, (1,), (1,)) assert_size_stride(primals_9, (4, 8), (8, 1)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (4, 4), (4, 1)) assert_size_stride(primals_12, (4,), (1,)) assert_size_stride(primals_13, (1, 4), (4, 1)) assert_size_stride(primals_14, (1,), (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) del primals_1 del primals_2 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.mm(buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4 ), 0), out=buf3) buf4 = buf3 del buf3 triton_poi_fused_relu_1[grid(16)](buf4, primals_6, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_6 buf6 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_8, buf4, reinterpret_tensor(primals_7, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf6) del primals_8 buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_9, (8, 4), (1, 8 ), 0), out=buf7) del primals_9 buf8 = buf7 del buf7 triton_poi_fused_relu_1[grid(16)](buf8, primals_10, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_10 buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf8, reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf9) buf10 = buf9 del buf9 triton_poi_fused_relu_1[grid(16)](buf10, primals_12, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_12 buf12 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_14, buf10, reinterpret_tensor( primals_13, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf12) del primals_14 return (buf6, buf12, buf0, buf2, buf4, buf8, buf10, primals_13, primals_11, primals_7, primals_5) class Q_CriticNew(nn.Module): def __init__(self, state_dim, action_dim, net_width): super(Q_CriticNew, self).__init__() self.l1 = nn.Linear(state_dim + action_dim, net_width) self.l2 = nn.Linear(net_width, net_width) self.l3 = nn.Linear(net_width, 1) self.l4 = nn.Linear(state_dim + action_dim, net_width) self.l5 = nn.Linear(net_width, net_width) self.l6 = nn.Linear(net_width, 1) def Q1(self, state, action): sa = torch.cat([state, action], 1) q1 = F.relu(self.l1(sa)) q1 = F.relu(self.l2(q1)) q1 = self.l3(q1) return q1 def forward(self, input_0, input_1): primals_3 = self.l1.weight primals_4 = self.l1.bias primals_1 = self.l2.weight primals_6 = self.l2.bias primals_7 = self.l3.weight primals_8 = self.l3.bias primals_9 = self.l4.weight primals_10 = self.l4.bias primals_2 = self.l5.weight primals_12 = self.l5.bias primals_13 = self.l6.weight primals_14 = self.l6.bias primals_5 = input_0 primals_11 = 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], output[1]
XinJingHao/RL
Q_Critic
false
18,100
[ "MIT" ]
6
eed54d6602b173e45ede722b0fcf82b5a203f14a
https://github.com/XinJingHao/RL/tree/eed54d6602b173e45ede722b0fcf82b5a203f14a
Actor
import torch import torch.nn as nn class Actor(nn.Module): def __init__(self, state_dim, action_dim, net_width, maxaction): super(Actor, self).__init__() self.l1 = nn.Linear(state_dim, net_width) self.l2 = nn.Linear(net_width, net_width) self.l3 = nn.Linear(net_width, action_dim) self.maxaction = maxaction def forward(self, state): a = torch.tanh(self.l1(state)) a = torch.tanh(self.l2(a)) a = torch.tanh(self.l3(a)) * self.maxaction return a def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'state_dim': 4, 'action_dim': 4, 'net_width': 4, 'maxaction': 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 ): 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) @triton.jit def triton_poi_fused_mul_tanh_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 tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = libdevice.tanh(tmp0) tmp2 = 4.0 tmp3 = tmp1 * 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) = 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, 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_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 get_raw_stream(0) triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, 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, 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 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_tanh_1[grid(256)](buf4, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf1, buf3, buf4, primals_6, primals_4 class ActorNew(nn.Module): def __init__(self, state_dim, action_dim, net_width, maxaction): super(ActorNew, self).__init__() self.l1 = nn.Linear(state_dim, net_width) self.l2 = nn.Linear(net_width, net_width) self.l3 = nn.Linear(net_width, action_dim) self.maxaction = maxaction def forward(self, input_0): primals_1 = self.l1.weight primals_2 = self.l1.bias primals_4 = self.l2.weight primals_5 = self.l2.bias primals_6 = self.l3.weight primals_7 = self.l3.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
XinJingHao/RL
Actor
false
18,101
[ "MIT" ]
6
eed54d6602b173e45ede722b0fcf82b5a203f14a
https://github.com/XinJingHao/RL/tree/eed54d6602b173e45ede722b0fcf82b5a203f14a
MaxMinGroup
import torch import torch.nn as nn import torch.utils.data def process_maxmin_groupsize(x, group_size, axis=-1): size = list(x.size()) num_channels = size[axis] if num_channels % group_size: raise ValueError( 'number of features({}) is not a multiple of group_size({})'. format(num_channels, num_channels)) size[axis] = -1 if axis == -1: size += [group_size] else: size.insert(axis + 1, group_size) return size def maxout_by_group(x, group_size, axis=-1): size = process_maxmin_groupsize(x, group_size, axis) sort_dim = axis if axis == -1 else axis + 1 return torch.max(x.view(*size), sort_dim)[0] def minout_by_group(x, group_size, axis=-1): size = process_maxmin_groupsize(x, group_size, axis) sort_dim = axis if axis == -1 else axis + 1 return torch.min(x.view(*size), sort_dim)[0] class MaxMinGroup(nn.Module): def __init__(self, group_size, axis=-1): super(MaxMinGroup, self).__init__() self.group_size = group_size self.axis = axis def forward(self, x): maxes = maxout_by_group(x, self.group_size, self.axis) mins = minout_by_group(x, self.group_size, self.axis) maxmin = torch.cat((maxes, mins), dim=1) return maxmin def extra_repr(self): return 'group_size: {}'.format(self.group_size) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'group_size': 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 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_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 8 x0 = xindex % 4 x2 = xindex // 32 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 + (4 * x0 + 16 * x1 + 64 * x2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * x1 + 64 * x2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * x1 + 64 * x2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp9 = triton_helpers.maximum(tmp7, tmp8) tmp10 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * x1 + 64 * x2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = triton_helpers.maximum(tmp9, tmp10) tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype) tmp13 = tl.where(tmp4, tmp11, tmp12) tmp14 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp17 = tl.load(in_ptr0 + (4 * x0 + 16 * (-4 + x1) + 64 * x2), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp18 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * (-4 + x1) + 64 * x2), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp19 = triton_helpers.minimum(tmp17, tmp18) tmp20 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * (-4 + x1) + 64 * x2), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp21 = triton_helpers.minimum(tmp19, tmp20) tmp22 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * (-4 + x1) + 64 * x2), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp23 = triton_helpers.minimum(tmp21, tmp22) tmp24 = tl.full(tmp23.shape, 0.0, tmp23.dtype) tmp25 = tl.where(tmp14, tmp23, tmp24) tmp26 = tl.where(tmp4, tmp13, tmp25) tl.store(out_ptr0 + x3, 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) buf0 = empty_strided_cuda((4, 8, 4, 1), (32, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(128)](arg0_1, buf0, 128, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, def process_maxmin_groupsize(x, group_size, axis=-1): size = list(x.size()) num_channels = size[axis] if num_channels % group_size: raise ValueError( 'number of features({}) is not a multiple of group_size({})'. format(num_channels, num_channels)) size[axis] = -1 if axis == -1: size += [group_size] else: size.insert(axis + 1, group_size) return size def maxout_by_group(x, group_size, axis=-1): size = process_maxmin_groupsize(x, group_size, axis) sort_dim = axis if axis == -1 else axis + 1 return torch.max(x.view(*size), sort_dim)[0] def minout_by_group(x, group_size, axis=-1): size = process_maxmin_groupsize(x, group_size, axis) sort_dim = axis if axis == -1 else axis + 1 return torch.min(x.view(*size), sort_dim)[0] class MaxMinGroupNew(nn.Module): def __init__(self, group_size, axis=-1): super(MaxMinGroupNew, self).__init__() self.group_size = group_size self.axis = axis def extra_repr(self): return 'group_size: {}'.format(self.group_size) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
XinZhang525/fGAIL
MaxMinGroup
false
18,102
[ "MIT" ]
4
682d70286685612558e072d9a1668779b8ae325b
https://github.com/XinZhang525/fGAIL/tree/682d70286685612558e072d9a1668779b8ae325b
MaskedL1Loss
import torch import torch.utils.data import torch import torch.nn as nn class MaskedL1Loss(nn.Module): def __init__(self): super(MaskedL1Loss, self).__init__() self.criterion = nn.L1Loss() def forward(self, input, target, mask): mask = mask.expand(-1, input.size()[1], -1, -1) loss = self.criterion(input * mask, target * mask) return loss def get_inputs(): return [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 import torch.utils.data import torch 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_abs_mean_mul_sub_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, 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) tmp3 = tl.load(in_ptr2 + r0, None) tmp2 = tmp0 * tmp1 tmp4 = tmp3 * tmp1 tmp5 = tmp2 - tmp4 tmp6 = tl_math.abs(tmp5) tmp7 = tl.broadcast_to(tmp6, [RBLOCK]) tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0)) tmp10 = 256.0 tmp11 = tmp9 / tmp10 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp11, None) def call(args): arg0_1, arg1_1, arg2_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)) 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_mean_mul_sub_0[grid(1)](buf1, arg1_1, arg0_1, arg2_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 return buf1, class MaskedL1LossNew(nn.Module): def __init__(self): super(MaskedL1LossNew, self).__init__() self.criterion = nn.L1Loss() def forward(self, input_0, input_1, input_2): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
WeisiX/ITAS3D
MaskedL1Loss
false
18,103
[ "MIT" ]
4
fc861e0cb2d4516905bfadab5e5e880c2b021832
https://github.com/WeisiX/ITAS3D/tree/fc861e0cb2d4516905bfadab5e5e880c2b021832
squeeze
import torch import torch.nn as nn import torch.utils.data class squeeze(nn.Module): def __init__(self, block_size): super(squeeze, self).__init__() self.block_size = block_size self.block_size_sq = block_size * block_size def inverse(self, input): output = input.permute(0, 2, 3, 1) batch_size, d_height, d_width, d_depth = output.size() s_depth = int(d_depth / self.block_size_sq) s_width = int(d_width * self.block_size) s_height = int(d_height * self.block_size) t_1 = output.contiguous().view(batch_size, d_height, d_width, self. block_size_sq, s_depth) spl = t_1.split(self.block_size, 3) stack = [t_t.contiguous().view(batch_size, d_height, s_width, s_depth) for t_t in spl] output = torch.stack(stack, 0).transpose(0, 1).permute(0, 2, 1, 3, 4 ).contiguous().view(batch_size, s_height, s_width, s_depth) output = output.permute(0, 3, 1, 2) return output.contiguous() def forward(self, input): output = input.permute(0, 2, 3, 1) batch_size, s_height, _s_width, s_depth = output.size() d_depth = s_depth * self.block_size_sq d_height = int(s_height / self.block_size) t_1 = output.split(self.block_size, 2) stack = [t_t.contiguous().view(batch_size, d_height, d_depth) for t_t in t_1] output = torch.stack(stack, 1) output = output.permute(0, 2, 1, 3) output = output.permute(0, 3, 1, 2) return output.contiguous() def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'block_size': 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 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_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 64 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 % 16 y1 = yindex // 16 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) 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_clone_0[grid(64, 4)](arg0_1, buf0, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 64, 1, 1), (64, 1, 64, 64), 0), class squeezeNew(nn.Module): def __init__(self, block_size): super(squeezeNew, self).__init__() self.block_size = block_size self.block_size_sq = block_size * block_size def inverse(self, input): output = input.permute(0, 2, 3, 1) batch_size, d_height, d_width, d_depth = output.size() s_depth = int(d_depth / self.block_size_sq) s_width = int(d_width * self.block_size) s_height = int(d_height * self.block_size) t_1 = output.contiguous().view(batch_size, d_height, d_width, self. block_size_sq, s_depth) spl = t_1.split(self.block_size, 3) stack = [t_t.contiguous().view(batch_size, d_height, s_width, s_depth) for t_t in spl] output = torch.stack(stack, 0).transpose(0, 1).permute(0, 2, 1, 3, 4 ).contiguous().view(batch_size, s_height, s_width, s_depth) output = output.permute(0, 3, 1, 2) return output.contiguous() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
XinZhang525/fGAIL
squeeze
false
18,104
[ "MIT" ]
4
682d70286685612558e072d9a1668779b8ae325b
https://github.com/XinZhang525/fGAIL/tree/682d70286685612558e072d9a1668779b8ae325b
ModulatedConv2d
from torch.autograd import Function import math import torch import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import nn as nn from torch.nn import init as init from torchvision.models import vgg as vgg from torch import autograd as autograd def make_resample_kernel(k): """Make resampling kernel for UpFirDn. Args: k (list[int]): A list indicating the 1D resample kernel magnitude. Returns: Tensor: 2D resampled kernel. """ k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape(-1, in_h, in_w, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(- pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :] out = out.permute(0, 3, 1, 2) out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1) out = out.permute(0, 2, 3, 1) out = out[:, ::down_y, ::down_x, :] out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 return out.view(-1, channel, out_h, out_w) def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): if input.device.type == 'cpu': out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) else: out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0 ], pad[1], pad[0], pad[1])) return out def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size): up_x, up_y = up down_x, down_y = down g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) grad_input = upfirdn2d_ext.upfirdn2d(grad_output, grad_kernel, down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) ctx.save_for_backward(kernel) pad_x0, pad_x1, pad_y0, pad_y1 = pad ctx.up_x = up_x ctx.up_y = up_y ctx.down_x = down_x ctx.down_y = down_y ctx.pad_x0 = pad_x0 ctx.pad_x1 = pad_x1 ctx.pad_y0 = pad_y0 ctx.pad_y1 = pad_y1 ctx.in_size = in_size ctx.out_size = out_size return grad_input @staticmethod def backward(ctx, gradgrad_input): kernel, = ctx.saved_tensors gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx. in_size[3], 1) gradgrad_out = upfirdn2d_ext.upfirdn2d(gradgrad_input, kernel, ctx. up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1, ctx.pad_y0, ctx.pad_y1) gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]) return gradgrad_out, None, None, None, None, None, None, None, None class UpFirDn2d(Function): @staticmethod def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape _batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = out_h, out_w ctx.up = up_x, up_y ctx.down = down_x, down_y ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1 g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 out = upfirdn2d_ext.upfirdn2d(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1) out = out.view(-1, channel, out_h, out_w) return out @staticmethod def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply(grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size) return grad_input, None, None, None, None class UpFirDnSmooth(nn.Module): """Upsample, FIR filter, and downsample (smooth version). Args: resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. upsample_factor (int): Upsampling scale factor. Default: 1. downsample_factor (int): Downsampling scale factor. Default: 1. kernel_size (int): Kernel size: Deafult: 1. """ def __init__(self, resample_kernel, upsample_factor=1, downsample_factor=1, kernel_size=1): super(UpFirDnSmooth, self).__init__() self.upsample_factor = upsample_factor self.downsample_factor = downsample_factor self.kernel = make_resample_kernel(resample_kernel) if upsample_factor > 1: self.kernel = self.kernel * upsample_factor ** 2 if upsample_factor > 1: pad = self.kernel.shape[0] - upsample_factor - (kernel_size - 1) self.pad = (pad + 1) // 2 + upsample_factor - 1, pad // 2 + 1 elif downsample_factor > 1: pad = self.kernel.shape[0] - downsample_factor + (kernel_size - 1) self.pad = (pad + 1) // 2, pad // 2 else: raise NotImplementedError def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=1, down=1, pad=self.pad) return out def __repr__(self): return ( f'{self.__class__.__name__}(upsample_factor={self.upsample_factor}, downsample_factor={self.downsample_factor})' ) class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) dim = [0] if grad_input.ndim > 2: dim += list(range(2, grad_input.ndim)) grad_bias = grad_input.sum(dim).detach() return grad_input, grad_bias @staticmethod def backward(ctx, gradgrad_input, gradgrad_bias): out, = ctx.saved_tensors gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale) return gradgrad_out, None, None, None class FusedLeakyReLUFunction(Function): @staticmethod def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out @staticmethod def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale) return grad_input, grad_bias, None, None class EqualLinear(nn.Module): """Equalized Linear as StyleGAN2. Args: in_channels (int): Size of each sample. out_channels (int): Size of each output sample. bias (bool): If set to ``False``, the layer will not learn an additive bias. Default: ``True``. bias_init_val (float): Bias initialized value. Default: 0. lr_mul (float): Learning rate multiplier. Default: 1. activation (None | str): The activation after ``linear`` operation. Supported: 'fused_lrelu', None. Default: None. """ def __init__(self, in_channels, out_channels, bias=True, bias_init_val= 0, lr_mul=1, activation=None): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ['fused_lrelu', None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}Supported ones are: ['fused_lrelu', None]." ) self.scale = 1 / math.sqrt(in_channels) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels). div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_( bias_init_val)) else: self.register_parameter('bias', None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == 'fused_lrelu': out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, bias={self.bias is not None})' ) class ModulatedConv2d(nn.Module): """Modulated Conv2d used in StyleGAN2. There is no bias in ModulatedConv2d. Args: in_channels (int): Channel number of the input. out_channels (int): Channel number of the output. kernel_size (int): Size of the convolving kernel. num_style_feat (int): Channel number of style features. demodulate (bool): Whether to demodulate in the conv layer. Default: True. sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None. resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. Default: (1, 3, 3, 1). eps (float): A value added to the denominator for numerical stability. Default: 1e-8. """ def __init__(self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, resample_kernel= (1, 3, 3, 1), eps=1e-08): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps if self.sample_mode == 'upsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=2, downsample_factor=1, kernel_size=kernel_size) elif self.sample_mode == 'downsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=1, downsample_factor=2, kernel_size=kernel_size) elif self.sample_mode is None: pass else: raise ValueError( f"Wrong sample mode {self.sample_mode}, supported ones are ['upsample', 'downsample', None]." ) self.scale = 1 / math.sqrt(in_channels * kernel_size ** 2) self.modulation = EqualLinear(num_style_feat, in_channels, bias= True, bias_init_val=1, lr_mul=1, activation=None) self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size)) self.padding = kernel_size // 2 def forward(self, x, style): """Forward function. Args: x (Tensor): Tensor with shape (b, c, h, w). style (Tensor): Tensor with shape (b, num_style_feat). Returns: Tensor: Modulated tensor after convolution. """ b, c, h, w = x.shape style = self.modulation(style).view(b, 1, c, 1, 1) weight = self.scale * self.weight * style if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(b, self.out_channels, 1, 1, 1) weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size) if self.sample_mode == 'upsample': x = x.view(1, b * c, h, w) weight = weight.view(b, self.out_channels, c, self.kernel_size, self.kernel_size) weight = weight.transpose(1, 2).reshape(b * c, self. out_channels, self.kernel_size, self.kernel_size) out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) out = self.smooth(out) elif self.sample_mode == 'downsample': x = self.smooth(x) x = x.view(1, b * c, *x.shape[2:4]) out = F.conv2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) else: x = x.view(1, b * c, h, w) out = F.conv2d(x, weight, padding=self.padding, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, kernel_size={self.kernel_size}, demodulate={self.demodulate}, sample_mode={self.sample_mode})' ) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4, 'num_style_feat': 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.autograd import Function import math import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import 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_mul_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 = 0.5 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused_mul_1(in_ptr0, 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 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_per_fused_add_mul_pow_rsqrt_sum_2(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 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) r5 = rindex x0 = xindex % 4 r3 = rindex // 16 x1 = xindex // 4 x4 = xindex tmp0 = tl.load(in_ptr0 + (r5 + 64 * x0), xmask, eviction_policy= 'evict_last', other=0.0) tmp3 = tl.load(in_ptr1 + (r3 + 4 * x1), xmask, eviction_policy= 'evict_last', other=0.0) tmp1 = 0.125 tmp2 = tmp0 * tmp1 tmp4 = tmp2 * tmp3 tmp5 = tmp4 * tmp4 tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tmp8 = tl.where(xmask, tmp6, 0) tmp9 = tl.sum(tmp8, 1)[:, None] tmp10 = 1e-08 tmp11 = tmp9 + tmp10 tmp12 = libdevice.rsqrt(tmp11) tmp13 = tmp4 * tmp12 tl.debug_barrier() tl.store(in_out_ptr0 + x4, tmp12, xmask) tl.store(out_ptr0 + (r5 + 64 * x4), tmp13, 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, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (1, 4, 4, 4, 4), (256, 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_mul_0[grid(16)](primals_3, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 buf1 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused_mul_1[grid(4)](primals_2, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) del primals_2 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(buf1, primals_4, reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del buf1 buf3 = buf0 del buf0 buf4 = buf3 del buf3 buf5 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_per_fused_add_mul_pow_rsqrt_sum_2[grid(16)](buf4, primals_5, buf2, buf5, 16, 64, XBLOCK=8, num_warps=4, num_stages=1) buf6 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf5, (16, 4, 4, 4), (64, 16, 4, 1), 0), stride=(1, 1), padding=(2, 2), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None) assert_size_stride(buf6, (1, 16, 5, 5), (400, 25, 5, 1)) return reinterpret_tensor(buf6, (4, 4, 5, 5), (100, 25, 5, 1), 0 ), primals_4, primals_5, buf2, buf4, reinterpret_tensor(buf5, (16, 4, 4, 4), (64, 16, 4, 1), 0), reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4, 1), 0) def make_resample_kernel(k): """Make resampling kernel for UpFirDn. Args: k (list[int]): A list indicating the 1D resample kernel magnitude. Returns: Tensor: 2D resampled kernel. """ k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape(-1, in_h, in_w, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(- pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :] out = out.permute(0, 3, 1, 2) out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1) out = out.permute(0, 2, 3, 1) out = out[:, ::down_y, ::down_x, :] out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 return out.view(-1, channel, out_h, out_w) def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): if input.device.type == 'cpu': out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) else: out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0 ], pad[1], pad[0], pad[1])) return out def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size): up_x, up_y = up down_x, down_y = down g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) grad_input = upfirdn2d_ext.upfirdn2d(grad_output, grad_kernel, down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) ctx.save_for_backward(kernel) pad_x0, pad_x1, pad_y0, pad_y1 = pad ctx.up_x = up_x ctx.up_y = up_y ctx.down_x = down_x ctx.down_y = down_y ctx.pad_x0 = pad_x0 ctx.pad_x1 = pad_x1 ctx.pad_y0 = pad_y0 ctx.pad_y1 = pad_y1 ctx.in_size = in_size ctx.out_size = out_size return grad_input @staticmethod def backward(ctx, gradgrad_input): kernel, = ctx.saved_tensors gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx. in_size[3], 1) gradgrad_out = upfirdn2d_ext.upfirdn2d(gradgrad_input, kernel, ctx. up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1, ctx.pad_y0, ctx.pad_y1) gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]) return gradgrad_out, None, None, None, None, None, None, None, None class UpFirDn2d(Function): @staticmethod def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape _batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = out_h, out_w ctx.up = up_x, up_y ctx.down = down_x, down_y ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1 g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 out = upfirdn2d_ext.upfirdn2d(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1) out = out.view(-1, channel, out_h, out_w) return out @staticmethod def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply(grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size) return grad_input, None, None, None, None class UpFirDnSmooth(nn.Module): """Upsample, FIR filter, and downsample (smooth version). Args: resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. upsample_factor (int): Upsampling scale factor. Default: 1. downsample_factor (int): Downsampling scale factor. Default: 1. kernel_size (int): Kernel size: Deafult: 1. """ def __init__(self, resample_kernel, upsample_factor=1, downsample_factor=1, kernel_size=1): super(UpFirDnSmooth, self).__init__() self.upsample_factor = upsample_factor self.downsample_factor = downsample_factor self.kernel = make_resample_kernel(resample_kernel) if upsample_factor > 1: self.kernel = self.kernel * upsample_factor ** 2 if upsample_factor > 1: pad = self.kernel.shape[0] - upsample_factor - (kernel_size - 1) self.pad = (pad + 1) // 2 + upsample_factor - 1, pad // 2 + 1 elif downsample_factor > 1: pad = self.kernel.shape[0] - downsample_factor + (kernel_size - 1) self.pad = (pad + 1) // 2, pad // 2 else: raise NotImplementedError def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=1, down=1, pad=self.pad) return out def __repr__(self): return ( f'{self.__class__.__name__}(upsample_factor={self.upsample_factor}, downsample_factor={self.downsample_factor})' ) class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) dim = [0] if grad_input.ndim > 2: dim += list(range(2, grad_input.ndim)) grad_bias = grad_input.sum(dim).detach() return grad_input, grad_bias @staticmethod def backward(ctx, gradgrad_input, gradgrad_bias): out, = ctx.saved_tensors gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale) return gradgrad_out, None, None, None class FusedLeakyReLUFunction(Function): @staticmethod def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out @staticmethod def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale) return grad_input, grad_bias, None, None class EqualLinear(nn.Module): """Equalized Linear as StyleGAN2. Args: in_channels (int): Size of each sample. out_channels (int): Size of each output sample. bias (bool): If set to ``False``, the layer will not learn an additive bias. Default: ``True``. bias_init_val (float): Bias initialized value. Default: 0. lr_mul (float): Learning rate multiplier. Default: 1. activation (None | str): The activation after ``linear`` operation. Supported: 'fused_lrelu', None. Default: None. """ def __init__(self, in_channels, out_channels, bias=True, bias_init_val= 0, lr_mul=1, activation=None): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ['fused_lrelu', None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}Supported ones are: ['fused_lrelu', None]." ) self.scale = 1 / math.sqrt(in_channels) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels). div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_( bias_init_val)) else: self.register_parameter('bias', None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == 'fused_lrelu': out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, bias={self.bias is not None})' ) class ModulatedConv2dNew(nn.Module): """Modulated Conv2d used in StyleGAN2. There is no bias in ModulatedConv2d. Args: in_channels (int): Channel number of the input. out_channels (int): Channel number of the output. kernel_size (int): Size of the convolving kernel. num_style_feat (int): Channel number of style features. demodulate (bool): Whether to demodulate in the conv layer. Default: True. sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None. resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. Default: (1, 3, 3, 1). eps (float): A value added to the denominator for numerical stability. Default: 1e-8. """ def __init__(self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, resample_kernel= (1, 3, 3, 1), eps=1e-08): super(ModulatedConv2dNew, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps if self.sample_mode == 'upsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=2, downsample_factor=1, kernel_size=kernel_size) elif self.sample_mode == 'downsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=1, downsample_factor=2, kernel_size=kernel_size) elif self.sample_mode is None: pass else: raise ValueError( f"Wrong sample mode {self.sample_mode}, supported ones are ['upsample', 'downsample', None]." ) self.scale = 1 / math.sqrt(in_channels * kernel_size ** 2) self.modulation = EqualLinear(num_style_feat, in_channels, bias= True, bias_init_val=1, lr_mul=1, activation=None) self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size)) self.padding = kernel_size // 2 def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, kernel_size={self.kernel_size}, demodulate={self.demodulate}, sample_mode={self.sample_mode})' ) def forward(self, input_0, input_1): primals_5 = self.weight primals_3 = self.modulation.weight primals_2 = self.modulation.bias primals_1 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
WoojunePark/BasicSR
ModulatedConv2d
false
18,105
[ "Apache-2.0" ]
9
e0910b022b924bb913045fc412a5470dc2242cf0
https://github.com/WoojunePark/BasicSR/tree/e0910b022b924bb913045fc412a5470dc2242cf0
Split
import torch import torch.nn as nn import torch.utils.data class Split(nn.Module): def __init__(self): super(Split, self).__init__() def forward(self, x): n = int(x.size(1) / 2) x1 = x[:, :n, :, :].contiguous() x2 = x[:, n:, :, :].contiguous() return x1, x2 def inverse(self, x1, x2): return torch.cat((x1, x2), 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 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_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 32 x1 = xindex // 32 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tl.store(out_ptr0 + x2, tmp0, xmask) @triton.jit def triton_poi_fused_clone_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 32 x1 = xindex // 32 x2 = xindex tmp0 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tl.store(out_ptr0 + x2, tmp0, 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, 2, 4, 4), (32, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(128)](arg0_1, buf0, 128, XBLOCK=128, num_warps=4, num_stages=1) buf1 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32) triton_poi_fused_clone_1[grid(128)](arg0_1, buf1, 128, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, buf1 class SplitNew(nn.Module): def __init__(self): super(SplitNew, self).__init__() def inverse(self, x1, x2): return torch.cat((x1, x2), 1) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0], output[1]
XinZhang525/fGAIL
Split
false
18,106
[ "MIT" ]
4
682d70286685612558e072d9a1668779b8ae325b
https://github.com/XinZhang525/fGAIL/tree/682d70286685612558e072d9a1668779b8ae325b
MaskUpdate
import torch import torch.nn as nn import torch.multiprocessing class MaskUpdate(nn.Module): def __init__(self, alpha): super(MaskUpdate, self).__init__() self.func = nn.ReLU(True) self.alpha = alpha def forward(self, input_masks): return torch.pow(self.func(input_masks), self.alpha) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'alpha': 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 as nn import torch.multiprocessing 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_pow_relu_0(in_ptr0, out_ptr0, out_ptr2, 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) tmp3 = tmp2 * tmp2 tmp4 = tmp3 * tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) tl.store(out_ptr2 + x0, tmp2, 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_pow_relu_0[grid(256)](arg0_1, buf0, arg0_1, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class MaskUpdateNew(nn.Module): def __init__(self, alpha): super(MaskUpdateNew, self).__init__() self.func = nn.ReLU(True) self.alpha = alpha def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
Xiefan-Guo/LBAM
MaskUpdate
false
18,107
[ "MIT" ]
4
9795e2af4677a9f5e8e13b5d89fc6d50534c006a
https://github.com/Xiefan-Guo/LBAM/tree/9795e2af4677a9f5e8e13b5d89fc6d50534c006a
L1
import torch import torch.utils.data import torch import torch.nn as nn class L1(nn.Module): def __init__(self): super(L1, self).__init__() def forward(self, output, target): lossvalue = torch.abs(output - target).mean() return lossvalue 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.utils.data import torch 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_abs_mean_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) 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 = 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_abs_mean_sub_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 L1New(nn.Module): def __init__(self): super(L1New, self).__init__() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
WeisiX/ITAS3D
L1
false
18,108
[ "MIT" ]
4
fc861e0cb2d4516905bfadab5e5e880c2b021832
https://github.com/WeisiX/ITAS3D/tree/fc861e0cb2d4516905bfadab5e5e880c2b021832
GaussianActivation
import torch import torch.nn as nn from torch.nn.parameter import Parameter import torch.multiprocessing class GaussianActivation(nn.Module): def __init__(self, a, mu, gamma_l, gamma_r): super(GaussianActivation, self).__init__() self.a = Parameter(torch.tensor(a, dtype=torch.float32)) self.mu = Parameter(torch.tensor(mu, dtype=torch.float32)) self.gamma_l = Parameter(torch.tensor(gamma_l, dtype=torch.float32)) self.gamma_r = Parameter(torch.tensor(gamma_r, dtype=torch.float32)) def forward(self, input_features): self.a.data = torch.clamp(self.a.data, 1.01, 6.0) self.mu.data = torch.clamp(self.mu.data, 0.1, 3.0) self.gamma_l.data = torch.clamp(self.gamma_l.data, 0.5, 2.0) self.gamma_r.data = torch.clamp(self.gamma_r.data, 0.5, 2.0) left = input_features < self.mu right = input_features >= self.mu g_A_left = self.a * torch.exp(-self.gamma_l * (input_features - self.mu) ** 2) g_A_left.masked_fill_(right, 0.0) g_A_right = 1 + (self.a - 1) * torch.exp(-self.gamma_r * ( input_features - self.mu) ** 2) g_A_right.masked_fill_(left, 0.0) g_A = g_A_left + g_A_right return g_A def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'a': 4, 'mu': 4, 'gamma_l': 4, 'gamma_r': 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 torch.nn.parameter import Parameter import torch.multiprocessing 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_0(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]) tmp2 = 1.01 tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp4 = 6.0 tmp5 = triton_helpers.minimum(tmp3, tmp4) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None) @triton.jit def triton_poi_fused_clamp_1(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]) tmp2 = 0.1 tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp4 = 3.0 tmp5 = triton_helpers.minimum(tmp3, tmp4) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None) @triton.jit def triton_poi_fused_clamp_2(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]) tmp2 = 0.5 tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp4 = 2.0 tmp5 = triton_helpers.minimum(tmp3, tmp4) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None) @triton.jit def triton_poi_fused_add_exp_ge_lt_masked_fill_mul_neg_pow_sub_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp5 = tl.load(in_ptr2 + 0) tmp6 = tl.broadcast_to(tmp5, [XBLOCK]) tmp7 = tl.load(in_ptr3 + 0) tmp8 = tl.broadcast_to(tmp7, [XBLOCK]) tmp19 = tl.load(in_ptr4 + 0) tmp20 = tl.broadcast_to(tmp19, [XBLOCK]) tmp3 = tmp0 < tmp2 tmp4 = tmp0 >= tmp2 tmp9 = -tmp8 tmp10 = tmp0 - tmp2 tmp11 = tmp10 * tmp10 tmp12 = tmp9 * tmp11 tmp13 = tl_math.exp(tmp12) tmp14 = tmp6 * tmp13 tmp15 = 0.0 tmp16 = tl.where(tmp4, tmp15, tmp14) tmp17 = 1.0 tmp18 = tmp6 - tmp17 tmp21 = -tmp20 tmp22 = tmp21 * tmp11 tmp23 = tl_math.exp(tmp22) tmp24 = tmp18 * tmp23 tmp25 = tmp24 + tmp17 tmp26 = tl.where(tmp3, tmp15, tmp25) tmp27 = tmp16 + tmp26 tl.store(out_ptr0 + x0, tmp3, xmask) tl.store(out_ptr1 + x0, tmp4, xmask) tl.store(out_ptr2 + x0, tmp27, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (), ()) assert_size_stride(primals_2, (), ()) assert_size_stride(primals_3, (), ()) assert_size_stride(primals_4, (), ()) assert_size_stride(primals_5, (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_poi_fused_clamp_0[grid(1)](primals_1, buf0, 1, XBLOCK=1, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((), (), torch.float32) triton_poi_fused_clamp_1[grid(1)](primals_2, buf1, 1, XBLOCK=1, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((), (), torch.float32) triton_poi_fused_clamp_2[grid(1)](primals_3, buf2, 1, XBLOCK=1, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((), (), torch.float32) triton_poi_fused_clamp_2[grid(1)](primals_4, buf3, 1, XBLOCK=1, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_exp_ge_lt_masked_fill_mul_neg_pow_sub_3[grid(256) ](primals_5, buf1, buf0, buf2, buf3, buf4, buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1) buf7 = torch.ops.aten.set_.source_Tensor(primals_1, buf0) assert_size_stride(buf7, (), ()) del primals_1 buf17 = torch.ops.aten.set_.source_Tensor(primals_2, buf1) assert_size_stride(buf17, (), ()) del primals_2 buf27 = torch.ops.aten.set_.source_Tensor(primals_3, buf2) assert_size_stride(buf27, (), ()) del primals_3 buf32 = torch.ops.aten.set_.source_Tensor(primals_4, buf3) assert_size_stride(buf32, (), ()) del primals_4 return buf6, primals_5, buf0, buf1, buf2, buf3, buf4, buf5 class GaussianActivationNew(nn.Module): def __init__(self, a, mu, gamma_l, gamma_r): super(GaussianActivationNew, self).__init__() self.a = Parameter(torch.tensor(a, dtype=torch.float32)) self.mu = Parameter(torch.tensor(mu, dtype=torch.float32)) self.gamma_l = Parameter(torch.tensor(gamma_l, dtype=torch.float32)) self.gamma_r = Parameter(torch.tensor(gamma_r, dtype=torch.float32)) def forward(self, input_0): primals_1 = self.a primals_2 = self.mu primals_3 = self.gamma_l primals_4 = self.gamma_r primals_5 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
Xiefan-Guo/LBAM
GaussianActivation
false
18,109
[ "MIT" ]
4
9795e2af4677a9f5e8e13b5d89fc6d50534c006a
https://github.com/Xiefan-Guo/LBAM/tree/9795e2af4677a9f5e8e13b5d89fc6d50534c006a
BertIntermediate
from _paritybench_helpers import _mock_config import torch from torch import nn class BertIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) self.intermediate_act_fn = nn.functional.gelu def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(hidden_size=4, intermediate_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 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_gelu_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.5 tmp2 = tmp0 * tmp1 tmp3 = 0.7071067811865476 tmp4 = tmp0 * tmp3 tmp5 = libdevice.erf(tmp4) tmp6 = 1.0 tmp7 = tmp5 + tmp6 tmp8 = tmp2 * tmp7 tl.store(out_ptr0 + x0, tmp8, 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((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_gelu_0[grid(256)](buf0, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0 class BertIntermediateNew(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) self.intermediate_act_fn = nn.functional.gelu def forward(self, input_0): primals_1 = self.dense.weight primals_2 = self.dense.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
RyanWangZf/SurvTRACE
BertIntermediate
false
18,110
[ "MIT" ]
8
d55299a28629d233f49ad1feaea7ed00835f0dd0
https://github.com/RyanWangZf/SurvTRACE/tree/d55299a28629d233f49ad1feaea7ed00835f0dd0
L2
import torch import torch.utils.data import torch import torch.nn as nn class L2(nn.Module): def __init__(self): super(L2, self).__init__() def forward(self, output, target): lossvalue = torch.norm(output - target, p=2, dim=1).mean() return lossvalue 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.triton_helpers import libdevice import torch.utils.data import torch 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_linalg_vector_norm_mean_sub_0(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) tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp10 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp15 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp6 = tmp4 - tmp5 tmp7 = tmp6 * tmp6 tmp8 = tmp3 + tmp7 tmp11 = tmp9 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tmp8 + tmp12 tmp16 = tmp14 - tmp15 tmp17 = tmp16 * tmp16 tmp18 = tmp13 + tmp17 tmp19 = libdevice.sqrt(tmp18) tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK]) tmp22 = tl.sum(tmp20, 1)[:, None] tmp23 = 64.0 tmp24 = tmp22 / tmp23 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp24, 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_linalg_vector_norm_mean_sub_0[grid(1)](buf1, arg0_1, arg1_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, class L2New(nn.Module): def __init__(self): super(L2New, self).__init__() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
WeisiX/ITAS3D
L2
false
18,111
[ "MIT" ]
4
fc861e0cb2d4516905bfadab5e5e880c2b021832
https://github.com/WeisiX/ITAS3D/tree/fc861e0cb2d4516905bfadab5e5e880c2b021832
Inception_Temporal_Layer
import torch import torch.nn as nn class CausalConv1d(nn.Conv1d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True): self.padding = (kernel_size - 1) * dilation super(CausalConv1d, self).__init__(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=self.padding, dilation=dilation, groups=groups, bias=bias) def forward(self, inputs): results = super(CausalConv1d, self).forward(inputs) padding = self.padding[0] if padding != 0: return results[:, :, :-padding] return results class Inception_Temporal_Layer(nn.Module): def __init__(self, num_stations, In_channels, Hid_channels, Out_channels): super(Inception_Temporal_Layer, self).__init__() self.temporal_conv1 = CausalConv1d(In_channels, Hid_channels, 3, dilation=1, groups=1) self.temporal_conv2 = CausalConv1d(Hid_channels, Hid_channels, 2, dilation=2, groups=1) self.temporal_conv3 = CausalConv1d(Hid_channels, Hid_channels, 2, dilation=4, groups=1) self.conv1_1 = CausalConv1d(3 * Hid_channels, Out_channels, 1) self.num_stations = num_stations self.act = nn.LeakyReLU(inplace=True) def forward(self, inputs): output_1 = torch.cat([self.temporal_conv1(inputs[:, s_i].transpose( 1, 2)).transpose(1, 2).unsqueeze(1) for s_i in range(self. num_stations)], dim=1) output_1 = self.act(output_1) output_2 = torch.cat([self.temporal_conv2(output_1[:, s_i]. transpose(1, 2)).transpose(1, 2).unsqueeze(1) for s_i in range( self.num_stations)], dim=1) output_2 = self.act(output_2) output_3 = torch.cat([self.temporal_conv3(output_2[:, s_i]. transpose(1, 2)).transpose(1, 2).unsqueeze(1) for s_i in range( self.num_stations)], dim=1) output_3 = self.act(output_3) outputs = torch.cat([output_1, output_2, output_3], dim=-1) outputs = torch.cat([self.conv1_1(outputs[:, s_i].transpose(1, 2)). transpose(1, 2).unsqueeze(1) for s_i in range(self.num_stations )], dim=1) return outputs def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_stations': 4, 'In_channels': 4, 'Hid_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 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_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 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_1(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 + (16 + y0 + 4 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_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 + (32 + y0 + 4 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_3(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 + (48 + y0 + 4 * x2 + 64 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_cat_leaky_relu_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl. constexpr): ynumel = 64 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 y1 = yindex // 4 % 4 x3 = xindex y0 = yindex % 4 y2 = yindex // 16 y4 = yindex // 4 tmp0 = y1 tl.full([1, 1], 0, tl.int64) tmp3 = tl.full([1, 1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x3 + 6 * y0 + 24 * y2), tmp4 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp4 & xmask & ymask, 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 tmp11 = tl.full([1, 1], 2, tl.int64) tmp12 = tmp0 < tmp11 tmp13 = tmp10 & tmp12 tmp14 = tl.load(in_ptr2 + (x3 + 6 * y0 + 24 * y2), tmp13 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp15 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp13 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp16 = tmp14 + tmp15 tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype) tmp18 = tl.where(tmp13, tmp16, tmp17) tmp19 = tmp0 >= tmp11 tmp20 = tl.full([1, 1], 3, tl.int64) tmp21 = tmp0 < tmp20 tmp22 = tmp19 & tmp21 tmp23 = tl.load(in_ptr3 + (x3 + 6 * y0 + 24 * y2), tmp22 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp24 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp22 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp25 = tmp23 + tmp24 tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype) tmp27 = tl.where(tmp22, tmp25, tmp26) tmp28 = tmp0 >= tmp20 tl.full([1, 1], 4, tl.int64) tmp31 = tl.load(in_ptr4 + (x3 + 6 * y0 + 24 * y2), tmp28 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp32 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp28 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp33 = tmp31 + tmp32 tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype) tmp35 = tl.where(tmp28, tmp33, tmp34) tmp36 = tl.where(tmp22, tmp27, tmp35) tmp37 = tl.where(tmp13, tmp18, tmp36) tmp38 = tl.where(tmp4, tmp9, tmp37) tmp39 = 0.0 tmp40 = tmp38 > tmp39 tmp41 = 0.01 tmp42 = tmp38 * tmp41 tmp43 = tl.where(tmp40, tmp38, tmp42) tl.store(out_ptr1 + (y0 + 4 * x3 + 16 * y4), tmp43, xmask & ymask) @triton.jit def triton_poi_fused_cat_leaky_relu_leaky_relu_backward_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 64 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 y1 = yindex // 4 % 4 x3 = xindex y0 = yindex % 4 y2 = yindex // 16 y5 = yindex y4 = yindex // 4 tmp0 = y1 tl.full([1, 1], 0, tl.int64) tmp3 = tl.full([1, 1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x3 + 8 * y0 + 32 * y2), tmp4 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp4 & xmask & ymask, 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 tmp11 = tl.full([1, 1], 2, tl.int64) tmp12 = tmp0 < tmp11 tmp13 = tmp10 & tmp12 tmp14 = tl.load(in_ptr2 + (x3 + 8 * y0 + 32 * y2), tmp13 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp15 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp13 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp16 = tmp14 + tmp15 tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype) tmp18 = tl.where(tmp13, tmp16, tmp17) tmp19 = tmp0 >= tmp11 tmp20 = tl.full([1, 1], 3, tl.int64) tmp21 = tmp0 < tmp20 tmp22 = tmp19 & tmp21 tmp23 = tl.load(in_ptr3 + (x3 + 8 * y0 + 32 * y2), tmp22 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp24 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp22 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp25 = tmp23 + tmp24 tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype) tmp27 = tl.where(tmp22, tmp25, tmp26) tmp28 = tmp0 >= tmp20 tl.full([1, 1], 4, tl.int64) tmp31 = tl.load(in_ptr4 + (x3 + 8 * y0 + 32 * y2), tmp28 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp32 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp28 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp33 = tmp31 + tmp32 tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype) tmp35 = tl.where(tmp28, tmp33, tmp34) tmp36 = tl.where(tmp22, tmp27, tmp35) tmp37 = tl.where(tmp13, tmp18, tmp36) tmp38 = tl.where(tmp4, tmp9, tmp37) tmp39 = 0.0 tmp40 = tmp38 > tmp39 tmp41 = 0.01 tmp42 = tmp38 * tmp41 tmp43 = tl.where(tmp40, tmp38, tmp42) tmp44 = tmp43 > tmp39 tl.store(out_ptr0 + (x3 + 4 * y5), tmp38, xmask & ymask) tl.store(out_ptr1 + (y0 + 4 * x3 + 16 * y4), tmp44, xmask & ymask) @triton.jit def triton_poi_fused_cat_6(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 768 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 12 x3 = xindex // 12 x1 = xindex // 12 % 4 x2 = xindex // 48 x4 = 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 * x3 + 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 * x3 + (-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 + (x1 + 4 * (-8 + x0) + 16 * x2), tmp11 & xmask, eviction_policy='evict_last', other=0.0) tmp15 = 0.0 tmp16 = tmp14 > tmp15 tmp17 = 0.01 tmp18 = tmp14 * tmp17 tmp19 = tl.where(tmp16, tmp14, tmp18) tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype) tmp21 = tl.where(tmp11, tmp19, tmp20) tmp22 = tl.where(tmp9, tmp10, tmp21) tmp23 = tl.where(tmp4, tmp5, tmp22) tl.store(out_ptr0 + x4, tmp23, xmask) @triton.jit def triton_poi_fused_convolution_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 48 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 % 12 y1 = yindex // 12 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 12 * x2 + 192 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_8(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 48 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 % 12 y1 = yindex // 12 y3 = yindex tmp0 = tl.load(in_ptr0 + (48 + y0 + 12 * x2 + 192 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_9(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 48 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 % 12 y1 = yindex // 12 y3 = yindex tmp0 = tl.load(in_ptr0 + (96 + y0 + 12 * x2 + 192 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_10(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 48 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 % 12 y1 = yindex // 12 y3 = yindex tmp0 = tl.load(in_ptr0 + (144 + y0 + 12 * x2 + 192 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_cat_11(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 64 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 y1 = yindex // 4 % 4 x3 = xindex y0 = yindex % 4 y2 = yindex // 16 y4 = yindex // 4 tmp0 = y1 tl.full([1, 1], 0, tl.int64) tmp3 = tl.full([1, 1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x3 + 4 * y0 + 16 * y2), tmp4 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp4 & xmask & ymask, 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 tmp11 = tl.full([1, 1], 2, tl.int64) tmp12 = tmp0 < tmp11 tmp13 = tmp10 & tmp12 tmp14 = tl.load(in_ptr2 + (x3 + 4 * y0 + 16 * y2), tmp13 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp15 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp13 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp16 = tmp14 + tmp15 tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype) tmp18 = tl.where(tmp13, tmp16, tmp17) tmp19 = tmp0 >= tmp11 tmp20 = tl.full([1, 1], 3, tl.int64) tmp21 = tmp0 < tmp20 tmp22 = tmp19 & tmp21 tmp23 = tl.load(in_ptr3 + (x3 + 4 * y0 + 16 * y2), tmp22 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp24 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp22 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp25 = tmp23 + tmp24 tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype) tmp27 = tl.where(tmp22, tmp25, tmp26) tmp28 = tmp0 >= tmp20 tl.full([1, 1], 4, tl.int64) tmp31 = tl.load(in_ptr4 + (x3 + 4 * y0 + 16 * y2), tmp28 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp32 = tl.load(in_ptr1 + tl.broadcast_to(y0, [XBLOCK, YBLOCK]), tmp28 & xmask & ymask, eviction_policy='evict_last', other=0.0) tmp33 = tmp31 + tmp32 tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype) tmp35 = tl.where(tmp28, tmp33, tmp34) tmp36 = tl.where(tmp22, tmp27, tmp35) tmp37 = tl.where(tmp13, tmp18, tmp36) tmp38 = tl.where(tmp4, tmp9, tmp37) tl.store(out_ptr0 + (y0 + 4 * x3 + 16 * y4), tmp38, xmask & ymask) @triton.jit def triton_poi_fused_leaky_relu_backward_12(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 = tmp0 > tmp1 tl.store(out_ptr0 + x0, tmp2, 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, 4, 3), (12, 3, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4, 2), (8, 2, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 2), (8, 2, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 12, 1), (12, 1, 1)) assert_size_stride(primals_9, (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_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,), padding=(2,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf1, (4, 4, 6), (24, 6, 1)) buf2 = buf0 del buf0 triton_poi_fused_convolution_1[grid(16, 4)](primals_1, buf2, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf3 = extern_kernels.convolution(buf2, primals_2, stride=(1,), padding=(2,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf3, (4, 4, 6), (24, 6, 1)) buf4 = buf2 del buf2 triton_poi_fused_convolution_2[grid(16, 4)](primals_1, buf4, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf5 = extern_kernels.convolution(buf4, primals_2, stride=(1,), padding=(2,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf5, (4, 4, 6), (24, 6, 1)) buf6 = buf4 del buf4 triton_poi_fused_convolution_3[grid(16, 4)](primals_1, buf6, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf7 = extern_kernels.convolution(buf6, primals_2, stride=(1,), padding=(2,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf7, (4, 4, 6), (24, 6, 1)) buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_cat_leaky_relu_4[grid(64, 4)](buf1, primals_3, buf3, buf5, buf7, buf9, 64, 4, XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1) del buf1 del buf3 del buf5 del buf7 del primals_3 buf10 = buf6 del buf6 triton_poi_fused_convolution_0[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf11 = extern_kernels.convolution(buf10, primals_4, stride=(1,), padding=(2,), dilation=(2,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf11, (4, 4, 6), (24, 6, 1)) buf12 = buf10 del buf10 triton_poi_fused_convolution_1[grid(16, 4)](buf9, buf12, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf13 = extern_kernels.convolution(buf12, primals_4, stride=(1,), padding=(2,), dilation=(2,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf13, (4, 4, 6), (24, 6, 1)) buf14 = buf12 del buf12 triton_poi_fused_convolution_2[grid(16, 4)](buf9, buf14, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf15 = extern_kernels.convolution(buf14, primals_4, stride=(1,), padding=(2,), dilation=(2,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf15, (4, 4, 6), (24, 6, 1)) buf16 = buf14 del buf14 triton_poi_fused_convolution_3[grid(16, 4)](buf9, buf16, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf17 = extern_kernels.convolution(buf16, primals_4, stride=(1,), padding=(2,), dilation=(2,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf17, (4, 4, 6), (24, 6, 1)) buf19 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_cat_leaky_relu_4[grid(64, 4)](buf11, primals_5, buf13, buf15, buf17, buf19, 64, 4, XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1) del buf11 del buf13 del buf15 del buf17 del primals_5 buf20 = buf16 del buf16 triton_poi_fused_convolution_0[grid(16, 4)](buf19, buf20, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf21 = extern_kernels.convolution(buf20, primals_6, stride=(1,), padding=(4,), dilation=(4,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf21, (4, 4, 8), (32, 8, 1)) buf22 = buf20 del buf20 triton_poi_fused_convolution_1[grid(16, 4)](buf19, buf22, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf23 = extern_kernels.convolution(buf22, primals_6, stride=(1,), padding=(4,), dilation=(4,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf23, (4, 4, 8), (32, 8, 1)) buf24 = buf22 del buf22 triton_poi_fused_convolution_2[grid(16, 4)](buf19, buf24, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf25 = extern_kernels.convolution(buf24, primals_6, stride=(1,), padding=(4,), dilation=(4,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf25, (4, 4, 8), (32, 8, 1)) buf26 = buf24 del buf24 triton_poi_fused_convolution_3[grid(16, 4)](buf19, buf26, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf27 = extern_kernels.convolution(buf26, primals_6, stride=(1,), padding=(4,), dilation=(4,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf27, (4, 4, 8), (32, 8, 1)) del buf26 buf28 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 1, 4), torch.float32) buf39 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_cat_leaky_relu_leaky_relu_backward_5[grid(64, 4)]( buf21, primals_7, buf23, buf25, buf27, buf28, buf39, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del buf21 del buf23 del buf25 del buf27 del primals_7 buf29 = empty_strided_cuda((4, 4, 4, 12), (192, 48, 12, 1), torch. float32) triton_poi_fused_cat_6[grid(768)](buf9, buf19, buf28, buf29, 768, XBLOCK=256, num_warps=4, num_stages=1) buf30 = empty_strided_cuda((4, 12, 4), (48, 4, 1), torch.float32) triton_poi_fused_convolution_7[grid(48, 4)](buf29, buf30, 48, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf31 = extern_kernels.convolution(buf30, primals_8, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf31, (4, 4, 4), (16, 4, 1)) buf32 = buf30 del buf30 triton_poi_fused_convolution_8[grid(48, 4)](buf29, buf32, 48, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf33 = extern_kernels.convolution(buf32, primals_8, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf33, (4, 4, 4), (16, 4, 1)) buf34 = buf32 del buf32 triton_poi_fused_convolution_9[grid(48, 4)](buf29, buf34, 48, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf35 = extern_kernels.convolution(buf34, primals_8, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf35, (4, 4, 4), (16, 4, 1)) buf36 = buf34 del buf34 triton_poi_fused_convolution_10[grid(48, 4)](buf29, buf36, 48, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf37 = extern_kernels.convolution(buf36, primals_8, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf37, (4, 4, 4), (16, 4, 1)) del buf36 buf38 = reinterpret_tensor(buf28, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf28 triton_poi_fused_cat_11[grid(64, 4)](buf31, primals_9, buf33, buf35, buf37, buf38, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1 ) del buf31 del buf33 del buf35 del buf37 del primals_9 buf40 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_leaky_relu_backward_12[grid(256)](buf19, buf40, 256, XBLOCK=128, num_warps=4, num_stages=1) buf41 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_leaky_relu_backward_12[grid(256)](buf9, buf41, 256, XBLOCK=128, num_warps=4, num_stages=1) return (buf38, primals_2, primals_4, primals_6, primals_8, reinterpret_tensor(primals_1, (4, 4, 4), (64, 1, 4), 0), reinterpret_tensor(primals_1, (4, 4, 4), (64, 1, 4), 16), reinterpret_tensor(primals_1, (4, 4, 4), (64, 1, 4), 32), reinterpret_tensor(primals_1, (4, 4, 4), (64, 1, 4), 48), reinterpret_tensor(buf9, (4, 4, 4), (64, 1, 4), 0), reinterpret_tensor(buf9, (4, 4, 4), (64, 1, 4), 16), reinterpret_tensor(buf9, (4, 4, 4), (64, 1, 4), 32), reinterpret_tensor(buf9, (4, 4, 4), (64, 1, 4), 48), reinterpret_tensor(buf19, (4, 4, 4), (64, 1, 4), 0), reinterpret_tensor(buf19, (4, 4, 4), (64, 1, 4), 16), reinterpret_tensor(buf19, (4, 4, 4), (64, 1, 4), 32), reinterpret_tensor(buf19, (4, 4, 4), (64, 1, 4), 48), reinterpret_tensor(buf29, (4, 12, 4), (192, 1, 12), 0), reinterpret_tensor(buf29, (4, 12, 4), (192, 1, 12), 48), reinterpret_tensor(buf29, (4, 12, 4), (192, 1, 12), 96), reinterpret_tensor(buf29, (4, 12, 4), (192, 1, 12), 144), buf39, buf40, buf41) class CausalConv1d(nn.Conv1d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True): self.padding = (kernel_size - 1) * dilation super(CausalConv1d, self).__init__(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=self.padding, dilation=dilation, groups=groups, bias=bias) def forward(self, inputs): results = super(CausalConv1d, self).forward(inputs) padding = self.padding[0] if padding != 0: return results[:, :, :-padding] return results class Inception_Temporal_LayerNew(nn.Module): def __init__(self, num_stations, In_channels, Hid_channels, Out_channels): super(Inception_Temporal_LayerNew, self).__init__() self.temporal_conv1 = CausalConv1d(In_channels, Hid_channels, 3, dilation=1, groups=1) self.temporal_conv2 = CausalConv1d(Hid_channels, Hid_channels, 2, dilation=2, groups=1) self.temporal_conv3 = CausalConv1d(Hid_channels, Hid_channels, 2, dilation=4, groups=1) self.conv1_1 = CausalConv1d(3 * Hid_channels, Out_channels, 1) self.num_stations = num_stations self.act = nn.LeakyReLU(inplace=True) def forward(self, input_0): primals_2 = self.temporal_conv1.weight primals_3 = self.temporal_conv1.bias primals_4 = self.temporal_conv2.weight primals_5 = self.temporal_conv2.bias primals_6 = self.temporal_conv3.weight primals_7 = self.temporal_conv3.bias primals_8 = self.conv1_1.weight primals_9 = self.conv1_1.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]) return output[0]
WoodSugar/GSTNet
Inception_Temporal_Layer
false
18,112
[ "MIT" ]
8
3c21cfc8a873d61336f257030a28fdee12dcee2f
https://github.com/WoodSugar/GSTNet/tree/3c21cfc8a873d61336f257030a28fdee12dcee2f
EqualLinear
from torch.autograd import Function import math import torch import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import nn as nn from torch.nn import init as init from torchvision.models import vgg as vgg from torch import autograd as autograd def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) dim = [0] if grad_input.ndim > 2: dim += list(range(2, grad_input.ndim)) grad_bias = grad_input.sum(dim).detach() return grad_input, grad_bias @staticmethod def backward(ctx, gradgrad_input, gradgrad_bias): out, = ctx.saved_tensors gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale) return gradgrad_out, None, None, None class FusedLeakyReLUFunction(Function): @staticmethod def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out @staticmethod def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale) return grad_input, grad_bias, None, None class EqualLinear(nn.Module): """Equalized Linear as StyleGAN2. Args: in_channels (int): Size of each sample. out_channels (int): Size of each output sample. bias (bool): If set to ``False``, the layer will not learn an additive bias. Default: ``True``. bias_init_val (float): Bias initialized value. Default: 0. lr_mul (float): Learning rate multiplier. Default: 1. activation (None | str): The activation after ``linear`` operation. Supported: 'fused_lrelu', None. Default: None. """ def __init__(self, in_channels, out_channels, bias=True, bias_init_val= 0, lr_mul=1, activation=None): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ['fused_lrelu', None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}Supported ones are: ['fused_lrelu', None]." ) self.scale = 1 / math.sqrt(in_channels) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels). div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_( bias_init_val)) else: self.register_parameter('bias', None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == 'fused_lrelu': out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, bias={self.bias is not None})' ) 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.autograd import Function import math import torch.utils.data from torch.utils import data as data from torch import 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_mul_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 = 0.5 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused_mul_1(in_ptr0, 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 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4,), (1,)) assert_size_stride(primals_2, (4, 4), (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_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_2 buf1 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused_mul_1[grid(4)](primals_1, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) del primals_1 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(buf1, reinterpret_tensor(primals_3, (64, 4), ( 4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del buf0 del buf1 return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0) def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) dim = [0] if grad_input.ndim > 2: dim += list(range(2, grad_input.ndim)) grad_bias = grad_input.sum(dim).detach() return grad_input, grad_bias @staticmethod def backward(ctx, gradgrad_input, gradgrad_bias): out, = ctx.saved_tensors gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale) return gradgrad_out, None, None, None class FusedLeakyReLUFunction(Function): @staticmethod def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out @staticmethod def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale) return grad_input, grad_bias, None, None class EqualLinearNew(nn.Module): """Equalized Linear as StyleGAN2. Args: in_channels (int): Size of each sample. out_channels (int): Size of each output sample. bias (bool): If set to ``False``, the layer will not learn an additive bias. Default: ``True``. bias_init_val (float): Bias initialized value. Default: 0. lr_mul (float): Learning rate multiplier. Default: 1. activation (None | str): The activation after ``linear`` operation. Supported: 'fused_lrelu', None. Default: None. """ def __init__(self, in_channels, out_channels, bias=True, bias_init_val= 0, lr_mul=1, activation=None): super(EqualLinearNew, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ['fused_lrelu', None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}Supported ones are: ['fused_lrelu', None]." ) self.scale = 1 / math.sqrt(in_channels) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels). div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_( bias_init_val)) else: self.register_parameter('bias', None) def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, bias={self.bias is not None})' ) def forward(self, input_0): primals_2 = self.weight primals_1 = self.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
WoojunePark/BasicSR
EqualLinear
false
18,113
[ "Apache-2.0" ]
9
e0910b022b924bb913045fc412a5470dc2242cf0
https://github.com/WoojunePark/BasicSR/tree/e0910b022b924bb913045fc412a5470dc2242cf0
RegLoss
import torch import torch.nn as nn from itertools import product as product from math import sqrt as sqrt import torch.utils.data def _reg_loss(regr, gt_regr, mask): """ L1 regression loss Arguments: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects) """ num = mask.float().sum() mask = mask.unsqueeze(2).expand_as(gt_regr).float() regr = regr * mask gt_regr = gt_regr * mask regr_loss = nn.functional.smooth_l1_loss(regr, gt_regr, size_average=False) regr_loss = regr_loss / (num + 0.0001) return regr_loss def _gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat def _transpose_and_gather_feat(feat, ind): feat = feat.permute(0, 2, 3, 1).contiguous() feat = feat.view(feat.size(0), -1, feat.size(3)) feat = _gather_feat(feat, ind) return feat class RegLoss(nn.Module): """Regression loss for an output tensor Arguments: output (batch x dim x h x w) mask (batch x max_objects) ind (batch x max_objects) target (batch x max_objects x dim) """ def __init__(self): super(RegLoss, self).__init__() def forward(self, output, mask, ind, target): pred = _transpose_and_gather_feat(output, ind) loss = _reg_loss(pred, target, mask) return loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4]), torch.ones([4, 4], dtype=torch.int64), 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 from itertools import product as product from math import sqrt as sqrt 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_gather_mul_smooth_l1_loss_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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) r4 = rindex // 4 % 16 r0 = rindex % 4 r2 = rindex // 16 % 4 r5 = rindex // 16 r6 = rindex tmp0 = tl.load(in_ptr0 + r4, None, eviction_policy='evict_last') tmp7 = tl.load(in_ptr2 + (r0 + 4 * r5), None, eviction_policy='evict_last') tmp9 = tl.load(in_ptr3 + r6, None) tmp1 = tl.full([RBLOCK], 16, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 16), 'index out of bounds: 0 <= tmp4 < 16') tmp6 = tl.load(in_ptr1 + (16 * r0 + 64 * r2 + tmp4 % 16), None, eviction_policy='evict_last') tmp8 = tmp6 * tmp7 tmp10 = tmp9 * tmp7 tmp11 = tmp8 - tmp10 tmp12 = tl_math.abs(tmp11) tmp13 = 1.0 tmp14 = tmp12 < tmp13 tmp15 = tmp12 * tmp12 tmp16 = 0.5 tmp17 = tmp15 * tmp16 tmp18 = tmp17 * tmp13 tmp19 = tmp12 - tmp16 tmp20 = tl.where(tmp14, tmp18, tmp19) tmp21 = tl.broadcast_to(tmp20, [RBLOCK]) tmp23 = triton_helpers.promote_to_tensor(tl.sum(tmp21, 0)) tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp23, None) @triton.jit def triton_per_fused_add_div_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 tmp0 = tl.load(in_ptr0 + r0, None) tmp4 = tl.load(in_out_ptr0 + 0) tmp5 = tl.broadcast_to(tmp4, [XBLOCK, 1]) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.sum(tmp1, 1)[:, None] tmp6 = 0.0001 tmp7 = tmp3 + tmp6 tmp8 = tmp5 / tmp7 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_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, 1)) assert_size_stride(arg2_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(arg3_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_gather_mul_smooth_l1_loss_0[grid(1)](arg1_1, arg0_1, arg2_1, arg3_1, buf0, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg3_1 buf2 = buf0 del buf0 triton_per_fused_add_div_sum_1[grid(1)](buf2, arg2_1, 1, 64, XBLOCK =1, num_warps=2, num_stages=1) del arg2_1 return buf2, def _reg_loss(regr, gt_regr, mask): """ L1 regression loss Arguments: regr (batch x max_objects x dim) gt_regr (batch x max_objects x dim) mask (batch x max_objects) """ num = mask.float().sum() mask = mask.unsqueeze(2).expand_as(gt_regr).float() regr = regr * mask gt_regr = gt_regr * mask regr_loss = nn.functional.smooth_l1_loss(regr, gt_regr, size_average=False) regr_loss = regr_loss / (num + 0.0001) return regr_loss def _gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat def _transpose_and_gather_feat(feat, ind): feat = feat.permute(0, 2, 3, 1).contiguous() feat = feat.view(feat.size(0), -1, feat.size(3)) feat = _gather_feat(feat, ind) return feat class RegLossNew(nn.Module): """Regression loss for an output tensor Arguments: output (batch x dim x h x w) mask (batch x max_objects) ind (batch x max_objects) target (batch x max_objects x dim) """ def __init__(self): super(RegLossNew, self).__init__() def forward(self, input_0, input_1, input_2, input_3): arg0_1 = input_0 arg2_1 = input_1 arg1_1 = input_2 arg3_1 = input_3 output = call([arg0_1, arg1_1, arg2_1, arg3_1]) return output[0]
XiangLiK/cv_course
RegLoss
false
18,114
[ "MIT" ]
8
da7c2318fd4128bbdab96db26ddbb2524f37d0a0
https://github.com/XiangLiK/cv_course/tree/da7c2318fd4128bbdab96db26ddbb2524f37d0a0
RegWeightedL1Loss
import torch import torch.nn as nn import torch.nn.functional as F from itertools import product as product from math import sqrt as sqrt import torch.utils.data def _gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat def _transpose_and_gather_feat(feat, ind): feat = feat.permute(0, 2, 3, 1).contiguous() feat = feat.view(feat.size(0), -1, feat.size(3)) feat = _gather_feat(feat, ind) return feat class RegWeightedL1Loss(nn.Module): def __init__(self): super(RegWeightedL1Loss, self).__init__() def forward(self, output, mask, ind, target): pred = _transpose_and_gather_feat(output, ind) mask = mask.float() loss = F.l1_loss(pred * mask, target * mask, size_average=False) loss = loss / (mask.sum() + 0.0001) return loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.ones( [4, 4], dtype=torch.int64), 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 from itertools import product as product from math import sqrt as sqrt 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_add_div_gather_mul_sub_sum_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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) r5 = rindex // 4 % 16 r0 = rindex % 4 r2 = rindex // 16 % 4 r4 = rindex tmp0 = tl.load(in_ptr0 + r5, None, eviction_policy='evict_last') tmp7 = tl.load(in_ptr2 + r4, None) tmp9 = tl.load(in_ptr3 + r4, None) tmp1 = tl.full([RBLOCK], 16, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 16), 'index out of bounds: 0 <= tmp4 < 16') tmp6 = tl.load(in_ptr1 + (16 * r0 + 64 * r2 + tmp4 % 16), None, eviction_policy='evict_last') tmp8 = tmp6 * tmp7 tmp10 = tmp9 * tmp7 tmp11 = tmp8 - tmp10 tmp12 = tl_math.abs(tmp11) tmp13 = tl.broadcast_to(tmp12, [RBLOCK]) tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0)) tmp16 = tl.broadcast_to(tmp7, [RBLOCK]) tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0)) tmp19 = 0.0001 tmp20 = tmp18 + tmp19 tmp21 = tmp15 / tmp20 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_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, 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)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_abs_add_div_gather_mul_sub_sum_0[grid(1)](buf2, arg1_1, arg0_1, arg2_1, arg3_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 return buf2, def _gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat def _transpose_and_gather_feat(feat, ind): feat = feat.permute(0, 2, 3, 1).contiguous() feat = feat.view(feat.size(0), -1, feat.size(3)) feat = _gather_feat(feat, ind) return feat class RegWeightedL1LossNew(nn.Module): def __init__(self): super(RegWeightedL1LossNew, self).__init__() def forward(self, input_0, input_1, input_2, input_3): arg0_1 = input_0 arg2_1 = input_1 arg1_1 = input_2 arg3_1 = input_3 output = call([arg0_1, arg1_1, arg2_1, arg3_1]) return output[0]
XiangLiK/cv_course
RegWeightedL1Loss
false
18,115
[ "MIT" ]
8
da7c2318fd4128bbdab96db26ddbb2524f37d0a0
https://github.com/XiangLiK/cv_course/tree/da7c2318fd4128bbdab96db26ddbb2524f37d0a0
MultiscaleL1Loss
import torch import torch.utils.data import torch import torch.nn as nn class MultiscaleL1Loss(nn.Module): def __init__(self, scale=5): super(MultiscaleL1Loss, self).__init__() self.criterion = nn.L1Loss() self.downsample = nn.AvgPool2d(2, stride=2, count_include_pad=False) self.weights = [1, 0.5, 0.25, 0.125, 0.125] self.weights = self.weights[:scale] def forward(self, input, target, mask=None): loss = 0 if mask is not None: mask = mask.expand(-1, input.size()[1], -1, -1) for i in range(len(self.weights)): if mask is not None: loss += self.weights[i] * self.criterion(input * mask, target * mask) else: loss += self.weights[i] * self.criterion(input, target) if i != len(self.weights) - 1: input = self.downsample(input) target = self.downsample(target) if mask is not None: mask = self.downsample(mask) return loss def get_inputs(): return [torch.rand([4, 4, 64, 64]), torch.rand([4, 4, 64, 64])] 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.utils.data import torch 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_red_fused_abs_mean_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr): xnumel = 8 rnumel = 8192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rbase = tl.arange(0, RBLOCK)[None, :] x0 = xindex _tmp5 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r1 = rindex tmp0 = tl.load(in_ptr0 + (r1 + 8192 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 8192 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp2 = tmp0 - tmp1 tmp3 = tl_math.abs(tmp2) tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK]) tmp6 = _tmp5 + tmp4 _tmp5 = tl.where(rmask & xmask, tmp6, _tmp5) tmp5 = tl.sum(_tmp5, 1)[:, None] tl.store(out_ptr0 + x0, tmp5, xmask) @triton.jit def triton_per_fused_abs_mean_sub_1(in_ptr0, 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 tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.sum(tmp1, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp3, None) @triton.jit def triton_red_fused_abs_avg_pool2d_mean_sub_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl. constexpr): xnumel = 2 rnumel = 8192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rbase = tl.arange(0, RBLOCK)[None, :] x0 = xindex _tmp20 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r1 = rindex % 32 r2 = rindex // 32 r3 = rindex tmp0 = tl.load(in_ptr0 + (2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(in_ptr0 + (1 + 2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp3 = tl.load(in_ptr0 + (64 + 2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp5 = tl.load(in_ptr0 + (65 + 2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp9 = tl.load(in_ptr1 + (2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.load(in_ptr1 + (1 + 2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp12 = tl.load(in_ptr1 + (64 + 2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.load(in_ptr1 + (65 + 2 * r1 + 128 * r2 + 32768 * x0), rmask & xmask, eviction_policy='evict_last', other=0.0) tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp7 = 0.25 tmp8 = tmp6 * tmp7 tmp11 = tmp10 + tmp9 tmp13 = tmp12 + tmp11 tmp15 = tmp14 + tmp13 tmp16 = tmp15 * tmp7 tmp17 = tmp8 - tmp16 tmp18 = tl_math.abs(tmp17) tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK]) tmp21 = _tmp20 + tmp19 _tmp20 = tl.where(rmask & xmask, tmp21, _tmp20) tl.store(out_ptr0 + (r3 + 8192 * x0), tmp8, rmask & xmask) tl.store(out_ptr1 + (r3 + 8192 * x0), tmp16, rmask & xmask) tmp20 = tl.sum(_tmp20, 1)[:, None] tl.store(out_ptr2 + x0, tmp20, xmask) @triton.jit def triton_per_fused_abs_mean_sub_3(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 2 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.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.sum(tmp1, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp3, None) @triton.jit def triton_red_fused_abs_avg_pool2d_mean_sub_4(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl. constexpr): rnumel = 4096 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rbase = tl.arange(0, RBLOCK)[None, :] _tmp20 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r0 = rindex % 16 r1 = rindex // 16 r2 = rindex tmp0 = tl.load(in_ptr0 + (2 * r0 + 64 * r1), rmask, eviction_policy ='evict_last', other=0.0) tmp1 = tl.load(in_ptr0 + (1 + 2 * r0 + 64 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp3 = tl.load(in_ptr0 + (32 + 2 * r0 + 64 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp5 = tl.load(in_ptr0 + (33 + 2 * r0 + 64 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp9 = tl.load(in_ptr1 + (2 * r0 + 64 * r1), rmask, eviction_policy ='evict_last', other=0.0) tmp10 = tl.load(in_ptr1 + (1 + 2 * r0 + 64 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp12 = tl.load(in_ptr1 + (32 + 2 * r0 + 64 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.load(in_ptr1 + (33 + 2 * r0 + 64 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp7 = 0.25 tmp8 = tmp6 * tmp7 tmp11 = tmp10 + tmp9 tmp13 = tmp12 + tmp11 tmp15 = tmp14 + tmp13 tmp16 = tmp15 * tmp7 tmp17 = tmp8 - tmp16 tmp18 = tl_math.abs(tmp17) tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK]) tmp21 = _tmp20 + tmp19 _tmp20 = tl.where(rmask, tmp21, _tmp20) tl.store(out_ptr0 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp8, rmask) tl.store(out_ptr1 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp16, rmask ) tmp20 = tl.sum(_tmp20, 1)[:, None] tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp20, None) @triton.jit def triton_red_fused_abs_avg_pool2d_mean_sub_5(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl. constexpr): rnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rbase = tl.arange(0, RBLOCK)[None, :] _tmp20 = tl.full([XBLOCK, RBLOCK], 0, tl.float32) for roffset in range(0, rnumel, RBLOCK): rindex = roffset + rbase rmask = rindex < rnumel r0 = rindex % 8 r1 = rindex // 8 r2 = rindex tmp0 = tl.load(in_ptr0 + (2 * r0 + 32 * r1), rmask, eviction_policy ='evict_last', other=0.0) tmp1 = tl.load(in_ptr0 + (1 + 2 * r0 + 32 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp3 = tl.load(in_ptr0 + (16 + 2 * r0 + 32 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp5 = tl.load(in_ptr0 + (17 + 2 * r0 + 32 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp9 = tl.load(in_ptr1 + (2 * r0 + 32 * r1), rmask, eviction_policy ='evict_last', other=0.0) tmp10 = tl.load(in_ptr1 + (1 + 2 * r0 + 32 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp12 = tl.load(in_ptr1 + (16 + 2 * r0 + 32 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.load(in_ptr1 + (17 + 2 * r0 + 32 * r1), rmask, eviction_policy='evict_last', other=0.0) tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp7 = 0.25 tmp8 = tmp6 * tmp7 tmp11 = tmp10 + tmp9 tmp13 = tmp12 + tmp11 tmp15 = tmp14 + tmp13 tmp16 = tmp15 * tmp7 tmp17 = tmp8 - tmp16 tmp18 = tl_math.abs(tmp17) tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK]) tmp21 = _tmp20 + tmp19 _tmp20 = tl.where(rmask, tmp21, _tmp20) tl.store(out_ptr0 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp8, rmask) tl.store(out_ptr1 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp16, rmask ) tmp20 = tl.sum(_tmp20, 1)[:, None] tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp20, None) @triton.jit def triton_per_fused_abs_add_avg_pool2d_mean_mul_sub_6(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 % 4 r1 = rindex // 4 tmp0 = tl.load(in_ptr0 + (2 * r0 + 16 * r1), None, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * r0 + 16 * r1), None, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (8 + 2 * r0 + 16 * r1), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr0 + (9 + 2 * r0 + 16 * r1), None, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr1 + (2 * r0 + 16 * r1), None, eviction_policy= 'evict_last') tmp10 = tl.load(in_ptr1 + (1 + 2 * r0 + 16 * r1), None, eviction_policy ='evict_last') tmp12 = tl.load(in_ptr1 + (8 + 2 * r0 + 16 * r1), None, eviction_policy ='evict_last') tmp14 = tl.load(in_ptr1 + (9 + 2 * r0 + 16 * r1), None, eviction_policy ='evict_last') tmp22 = tl.load(in_out_ptr0 + 0) tmp23 = tl.broadcast_to(tmp22, [1]) tmp30 = tl.load(in_ptr2 + 0) tmp31 = tl.broadcast_to(tmp30, [1]) tmp37 = tl.load(in_ptr3 + 0) tmp38 = tl.broadcast_to(tmp37, [1]) tmp43 = tl.load(in_ptr4 + 0) tmp44 = tl.broadcast_to(tmp43, [1]) tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp7 = 0.25 tmp8 = tmp6 * tmp7 tmp11 = tmp10 + tmp9 tmp13 = tmp12 + tmp11 tmp15 = tmp14 + tmp13 tmp16 = tmp15 * tmp7 tmp17 = tmp8 - tmp16 tmp18 = tl_math.abs(tmp17) tmp19 = tl.broadcast_to(tmp18, [RBLOCK]) tmp21 = triton_helpers.promote_to_tensor(tl.sum(tmp19, 0)) tmp24 = 65536.0 tmp25 = tmp23 / tmp24 tmp26 = 1.0 tmp27 = tmp25 * tmp26 tmp28 = 0.0 tmp29 = tmp27 + tmp28 tmp32 = 16384.0 tmp33 = tmp31 / tmp32 tmp34 = 0.5 tmp35 = tmp33 * tmp34 tmp36 = tmp29 + tmp35 tmp39 = 4096.0 tmp40 = tmp38 / tmp39 tmp41 = tmp40 * tmp7 tmp42 = tmp36 + tmp41 tmp45 = 1024.0 tmp46 = tmp44 / tmp45 tmp47 = 0.125 tmp48 = tmp46 * tmp47 tmp49 = tmp42 + tmp48 tmp50 = 256.0 tmp51 = tmp21 / tmp50 tmp52 = tmp51 * tmp47 tmp53 = tmp49 + tmp52 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp53, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 64, 64), (16384, 4096, 64, 1)) assert_size_stride(arg1_1, (4, 4, 64, 64), (16384, 4096, 64, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((8,), (1,), torch.float32) get_raw_stream(0) triton_red_fused_abs_mean_sub_0[grid(8)](arg1_1, arg0_1, buf0, 8, 8192, XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1) buf1 = empty_strided_cuda((), (), torch.float32) triton_per_fused_abs_mean_sub_1[grid(1)](buf0, buf1, 1, 8, XBLOCK=1, num_warps=2, num_stages=1) del buf0 buf2 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1), torch.float32) buf3 = empty_strided_cuda((4, 4, 32, 32), (4096, 1024, 32, 1), torch.float32) buf4 = empty_strided_cuda((2,), (1,), torch.float32) triton_red_fused_abs_avg_pool2d_mean_sub_2[grid(2)](arg1_1, arg0_1, buf2, buf3, buf4, 2, 8192, XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1) del arg0_1 del arg1_1 buf5 = empty_strided_cuda((), (), torch.float32) triton_per_fused_abs_mean_sub_3[grid(1)](buf4, buf5, 1, 2, XBLOCK=1, num_warps=2, num_stages=1) del buf4 buf6 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1), torch .float32) buf7 = empty_strided_cuda((4, 4, 16, 16), (1024, 256, 16, 1), torch .float32) buf8 = empty_strided_cuda((), (), torch.float32) triton_red_fused_abs_avg_pool2d_mean_sub_4[grid(1)](buf2, buf3, buf6, buf7, buf8, 1, 4096, XBLOCK=1, RBLOCK=4096, num_warps=16, num_stages=1) del buf2 del buf3 buf9 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32) buf10 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32 ) buf11 = empty_strided_cuda((), (), torch.float32) triton_red_fused_abs_avg_pool2d_mean_sub_5[grid(1)](buf6, buf7, buf9, buf10, buf11, 1, 1024, XBLOCK=1, RBLOCK=1024, num_warps=8, num_stages=1) del buf6 del buf7 buf13 = buf1 del buf1 triton_per_fused_abs_add_avg_pool2d_mean_mul_sub_6[grid(1)](buf13, buf9, buf10, buf5, buf8, buf11, 1, 256, num_warps=2, num_stages=1) del buf10 del buf11 del buf5 del buf8 del buf9 return buf13, class MultiscaleL1LossNew(nn.Module): def __init__(self, scale=5): super(MultiscaleL1LossNew, self).__init__() self.criterion = nn.L1Loss() self.downsample = nn.AvgPool2d(2, stride=2, count_include_pad=False) self.weights = [1, 0.5, 0.25, 0.125, 0.125] self.weights = self.weights[:scale] def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
WeisiX/ITAS3D
MultiscaleL1Loss
false
18,116
[ "MIT" ]
4
fc861e0cb2d4516905bfadab5e5e880c2b021832
https://github.com/WeisiX/ITAS3D/tree/fc861e0cb2d4516905bfadab5e5e880c2b021832
ReverseAttentionLayer
import math import torch import torch.nn as nn from torch.nn.parameter import Parameter import torch.multiprocessing def weights_init(init_type='gaussian'): def init_func(m): classname = m.__class__.__name__ if (classname.find('Conv') == 0 or classname.find('Linear') == 0 ) and hasattr(m, 'weight'): if init_type == 'gaussian': nn.init.normal_(m.weight, 0.0, 0.02) elif init_type == 'xavier': nn.init.xavier_normal_(m.weight, gain=math.sqrt(2)) elif init_type == 'kaiming': nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') elif init_type == 'orthogonal': nn.init.orthogonal_(m.weight, gain=math.sqrt(2)) elif init_type == 'default': pass else: assert 0, 'Unsupported initialization: {}'.format(init_type) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0.0) return init_func class GaussianActivation(nn.Module): def __init__(self, a, mu, gamma_l, gamma_r): super(GaussianActivation, self).__init__() self.a = Parameter(torch.tensor(a, dtype=torch.float32)) self.mu = Parameter(torch.tensor(mu, dtype=torch.float32)) self.gamma_l = Parameter(torch.tensor(gamma_l, dtype=torch.float32)) self.gamma_r = Parameter(torch.tensor(gamma_r, dtype=torch.float32)) def forward(self, input_features): self.a.data = torch.clamp(self.a.data, 1.01, 6.0) self.mu.data = torch.clamp(self.mu.data, 0.1, 3.0) self.gamma_l.data = torch.clamp(self.gamma_l.data, 0.5, 2.0) self.gamma_r.data = torch.clamp(self.gamma_r.data, 0.5, 2.0) left = input_features < self.mu right = input_features >= self.mu g_A_left = self.a * torch.exp(-self.gamma_l * (input_features - self.mu) ** 2) g_A_left.masked_fill_(right, 0.0) g_A_right = 1 + (self.a - 1) * torch.exp(-self.gamma_r * ( input_features - self.mu) ** 2) g_A_right.masked_fill_(left, 0.0) g_A = g_A_left + g_A_right return g_A class MaskUpdate(nn.Module): def __init__(self, alpha): super(MaskUpdate, self).__init__() self.func = nn.ReLU(True) self.alpha = alpha def forward(self, input_masks): return torch.pow(self.func(input_masks), self.alpha) class ReverseAttentionLayer(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=4, stride=2, padding=1, dilation=1, groups=1, bias=False): super(ReverseAttentionLayer, self).__init__() self.mask_conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) self.mask_conv.apply(weights_init()) self.gaussian_activation = GaussianActivation(a=1.1, mu=2.0, gamma_l=1.0, gamma_r=1.0) self.mask_update = MaskUpdate(alpha=0.8) def forward(self, input_masks): conv_masks = self.mask_conv(input_masks) gaussian_masks = self.gaussian_activation(conv_masks) output_masks = self.mask_update(conv_masks) return output_masks, gaussian_masks 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, math as tl_math import math import torch.nn as nn from torch.nn.parameter import Parameter import torch.multiprocessing 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_0(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]) tmp2 = 1.01 tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp4 = 6.0 tmp5 = triton_helpers.minimum(tmp3, tmp4) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None) @triton.jit def triton_poi_fused_clamp_1(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]) tmp2 = 0.1 tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp4 = 3.0 tmp5 = triton_helpers.minimum(tmp3, tmp4) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None) @triton.jit def triton_poi_fused_clamp_2(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]) tmp2 = 0.5 tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp4 = 2.0 tmp5 = triton_helpers.minimum(tmp3, tmp4) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp5, None) @triton.jit def triton_poi_fused_add_exp_ge_lt_masked_fill_mul_neg_pow_relu_sub_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2, out_ptr3, 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_ptr1 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp5 = tl.load(in_ptr2 + 0) tmp6 = tl.broadcast_to(tmp5, [XBLOCK]) tmp7 = tl.load(in_ptr3 + 0) tmp8 = tl.broadcast_to(tmp7, [XBLOCK]) tmp19 = tl.load(in_ptr4 + 0) tmp20 = tl.broadcast_to(tmp19, [XBLOCK]) tmp3 = tmp0 < tmp2 tmp4 = tmp0 >= tmp2 tmp9 = -tmp8 tmp10 = tmp0 - tmp2 tmp11 = tmp10 * tmp10 tmp12 = tmp9 * tmp11 tmp13 = tl_math.exp(tmp12) tmp14 = tmp6 * tmp13 tmp15 = 0.0 tmp16 = tl.where(tmp4, tmp15, tmp14) tmp17 = 1.0 tmp18 = tmp6 - tmp17 tmp21 = -tmp20 tmp22 = tmp21 * tmp11 tmp23 = tl_math.exp(tmp22) tmp24 = tmp18 * tmp23 tmp25 = tmp24 + tmp17 tmp26 = tl.where(tmp3, tmp15, tmp25) tmp27 = tmp16 + tmp26 tmp28 = tl.full([1], 0, tl.int32) tmp29 = triton_helpers.maximum(tmp28, tmp0) tmp30 = 0.8 tmp31 = libdevice.pow(tmp29, tmp30) tl.store(out_ptr0 + x0, tmp3, xmask) tl.store(out_ptr1 + x0, tmp4, xmask) tl.store(out_ptr2 + x0, tmp27, xmask) tl.store(out_ptr3 + x0, tmp31, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (), ()) assert_size_stride(primals_4, (), ()) assert_size_stride(primals_5, (), ()) assert_size_stride(primals_6, (), ()) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(2, 2), padding=(1, 1), 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((), (), torch.float32) get_raw_stream(0) triton_poi_fused_clamp_0[grid(1)](primals_3, buf1, 1, XBLOCK=1, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((), (), torch.float32) triton_poi_fused_clamp_1[grid(1)](primals_4, buf2, 1, XBLOCK=1, num_warps=1, num_stages=1) buf3 = empty_strided_cuda((), (), torch.float32) triton_poi_fused_clamp_2[grid(1)](primals_5, buf3, 1, XBLOCK=1, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((), (), torch.float32) triton_poi_fused_clamp_2[grid(1)](primals_6, buf4, 1, XBLOCK=1, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.bool) buf6 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.bool) buf7 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) buf8 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) triton_poi_fused_add_exp_ge_lt_masked_fill_mul_neg_pow_relu_sub_3[grid (64)](buf0, buf2, buf1, buf3, buf4, buf5, buf6, buf7, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = torch.ops.aten.set_.source_Tensor(primals_3, buf1) assert_size_stride(buf9, (), ()) del primals_3 buf19 = torch.ops.aten.set_.source_Tensor(primals_4, buf2) assert_size_stride(buf19, (), ()) del primals_4 buf29 = torch.ops.aten.set_.source_Tensor(primals_5, buf3) assert_size_stride(buf29, (), ()) del primals_5 buf34 = torch.ops.aten.set_.source_Tensor(primals_6, buf4) assert_size_stride(buf34, (), ()) del primals_6 return (buf8, buf7, primals_1, primals_2, buf0, buf1, buf2, buf3, buf4, buf5, buf6) def weights_init(init_type='gaussian'): def init_func(m): classname = m.__class__.__name__ if (classname.find('Conv') == 0 or classname.find('Linear') == 0 ) and hasattr(m, 'weight'): if init_type == 'gaussian': nn.init.normal_(m.weight, 0.0, 0.02) elif init_type == 'xavier': nn.init.xavier_normal_(m.weight, gain=math.sqrt(2)) elif init_type == 'kaiming': nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') elif init_type == 'orthogonal': nn.init.orthogonal_(m.weight, gain=math.sqrt(2)) elif init_type == 'default': pass else: assert 0, 'Unsupported initialization: {}'.format(init_type) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0.0) return init_func class GaussianActivation(nn.Module): def __init__(self, a, mu, gamma_l, gamma_r): super(GaussianActivation, self).__init__() self.a = Parameter(torch.tensor(a, dtype=torch.float32)) self.mu = Parameter(torch.tensor(mu, dtype=torch.float32)) self.gamma_l = Parameter(torch.tensor(gamma_l, dtype=torch.float32)) self.gamma_r = Parameter(torch.tensor(gamma_r, dtype=torch.float32)) def forward(self, input_features): self.a.data = torch.clamp(self.a.data, 1.01, 6.0) self.mu.data = torch.clamp(self.mu.data, 0.1, 3.0) self.gamma_l.data = torch.clamp(self.gamma_l.data, 0.5, 2.0) self.gamma_r.data = torch.clamp(self.gamma_r.data, 0.5, 2.0) left = input_features < self.mu right = input_features >= self.mu g_A_left = self.a * torch.exp(-self.gamma_l * (input_features - self.mu) ** 2) g_A_left.masked_fill_(right, 0.0) g_A_right = 1 + (self.a - 1) * torch.exp(-self.gamma_r * ( input_features - self.mu) ** 2) g_A_right.masked_fill_(left, 0.0) g_A = g_A_left + g_A_right return g_A class MaskUpdate(nn.Module): def __init__(self, alpha): super(MaskUpdate, self).__init__() self.func = nn.ReLU(True) self.alpha = alpha def forward(self, input_masks): return torch.pow(self.func(input_masks), self.alpha) class ReverseAttentionLayerNew(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=4, stride=2, padding=1, dilation=1, groups=1, bias=False): super(ReverseAttentionLayerNew, self).__init__() self.mask_conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) self.mask_conv.apply(weights_init()) self.gaussian_activation = GaussianActivation(a=1.1, mu=2.0, gamma_l=1.0, gamma_r=1.0) self.mask_update = MaskUpdate(alpha=0.8) def forward(self, input_0): primals_1 = self.mask_conv.weight primals_3 = self.gaussian_activation.a primals_4 = self.gaussian_activation.mu primals_5 = self.gaussian_activation.gamma_l primals_6 = self.gaussian_activation.gamma_r primals_2 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0], output[1]
Xiefan-Guo/LBAM
ReverseAttentionLayer
false
18,118
[ "MIT" ]
4
9795e2af4677a9f5e8e13b5d89fc6d50534c006a
https://github.com/Xiefan-Guo/LBAM/tree/9795e2af4677a9f5e8e13b5d89fc6d50534c006a
patch_extractor
import torch import torch.nn as nn class patch_extractor(nn.Module): """ Module for creating custom patch extractor """ def __init__(self, patch_size, pad=False): super(patch_extractor, self).__init__() self.im2pat = nn.Unfold(kernel_size=patch_size) self.pad = pad self.padsize = patch_size - 1 def forward(self, input, batch_size=0): if self.pad: input = torch.cat((input, input[:, :, :self.padsize, :]), 2) input = torch.cat((input, input[:, :, :, :self.padsize]), 3) patches = self.im2pat(input).squeeze(0).transpose(1, 0) if batch_size > 0: idx = torch.randperm(patches.size(0))[:batch_size] patches = patches[idx, :] return patches def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'patch_size': 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 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_im2col_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 tmp0 = tl.load(in_ptr0 + x3, xmask) tl.store(out_ptr0 + x3, tmp0, 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, 1, 4, 1), (64, 16, 4, 4, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_im2col_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (64, 4, 1), (1, 64, 4), 0), class patch_extractorNew(nn.Module): """ Module for creating custom patch extractor """ def __init__(self, patch_size, pad=False): super(patch_extractorNew, self).__init__() self.im2pat = nn.Unfold(kernel_size=patch_size) self.pad = pad self.padsize = patch_size - 1 def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
Xmaster6y/wgenpatex
patch_extractor
false
18,119
[ "MIT" ]
8
08079dc131cc2e9c74ee4f9e16cf9b58667f2b07
https://github.com/Xmaster6y/wgenpatex/tree/08079dc131cc2e9c74ee4f9e16cf9b58667f2b07
gaussian_layer
import math import torch import torch.nn as nn class gaussian_downsample(nn.Module): """ Downsampling module with Gaussian filtering """ def __init__(self, kernel_size, sigma, stride, pad=False): super(gaussian_downsample, self).__init__() self.gauss = nn.Conv2d(3, 3, kernel_size, stride=stride, groups=3, bias=False) gaussian_weights = self.init_weights(kernel_size, sigma) self.gauss.weight.data = gaussian_weights self.gauss.weight.requires_grad_(False) self.pad = pad self.padsize = kernel_size - 1 def forward(self, x): if self.pad: x = torch.cat((x, x[:, :, :self.padsize, :]), 2) x = torch.cat((x, x[:, :, :, :self.padsize]), 3) return self.gauss(x) def init_weights(self, kernel_size, sigma): x_cord = torch.arange(kernel_size) x_grid = x_cord.repeat(kernel_size).view(kernel_size, kernel_size) y_grid = x_grid.t() xy_grid = torch.stack([x_grid, y_grid], dim=-1) mean = (kernel_size - 1) / 2.0 variance = sigma ** 2.0 gaussian_kernel = 1.0 / (2.0 * math.pi * variance) * torch.exp(- torch.sum((xy_grid - mean) ** 2.0, dim=-1) / (2 * variance)) gaussian_kernel = gaussian_kernel / torch.sum(gaussian_kernel) return gaussian_kernel.view(1, 1, kernel_size, kernel_size).repeat( 3, 1, 1, 1) class gaussian_layer(nn.Module): """ Gaussian layer for the dowsampling pyramid """ def __init__(self, gaussian_kernel_size, gaussian_std, stride=2, pad=False ): super(gaussian_layer, self).__init__() self.downsample = gaussian_downsample(gaussian_kernel_size, gaussian_std, stride, pad=pad) def forward(self, input): self.down_img = self.downsample(input) return self.down_img def get_inputs(): return [torch.rand([4, 3, 64, 64])] def get_init_inputs(): return [[], {'gaussian_kernel_size': 4, 'gaussian_std': 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 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_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 12 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 % 3 y1 = yindex // 3 tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, ymask) @triton.jit def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 12 xnumel = 961 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 % 3 y1 = yindex // 3 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 3 * x2 + 2883 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 961 * y3), tmp0, xmask & ymask) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (3, 1, 4, 4), (16, 16, 4, 1)) assert_size_stride(arg1_1, (4, 3, 64, 64), (12288, 4096, 64, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch .float32) get_raw_stream(0) triton_poi_fused_convolution_0[grid(12, 4096)](arg1_1, buf0, 12, 4096, XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1) del arg1_1 buf1 = extern_kernels.convolution(buf0, arg0_1, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=3, bias=None) assert_size_stride(buf1, (4, 3, 31, 31), (2883, 1, 93, 3)) del arg0_1 del buf0 buf2 = empty_strided_cuda((4, 3, 31, 31), (2883, 961, 31, 1), torch .float32) triton_poi_fused_convolution_1[grid(12, 961)](buf1, buf2, 12, 961, XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1) del buf1 return buf2, class gaussian_downsample(nn.Module): """ Downsampling module with Gaussian filtering """ def __init__(self, kernel_size, sigma, stride, pad=False): super(gaussian_downsample, self).__init__() self.gauss = nn.Conv2d(3, 3, kernel_size, stride=stride, groups=3, bias=False) gaussian_weights = self.init_weights(kernel_size, sigma) self.gauss.weight.data = gaussian_weights self.gauss.weight.requires_grad_(False) self.pad = pad self.padsize = kernel_size - 1 def forward(self, x): if self.pad: x = torch.cat((x, x[:, :, :self.padsize, :]), 2) x = torch.cat((x, x[:, :, :, :self.padsize]), 3) return self.gauss(x) def init_weights(self, kernel_size, sigma): x_cord = torch.arange(kernel_size) x_grid = x_cord.repeat(kernel_size).view(kernel_size, kernel_size) y_grid = x_grid.t() xy_grid = torch.stack([x_grid, y_grid], dim=-1) mean = (kernel_size - 1) / 2.0 variance = sigma ** 2.0 gaussian_kernel = 1.0 / (2.0 * math.pi * variance) * torch.exp(- torch.sum((xy_grid - mean) ** 2.0, dim=-1) / (2 * variance)) gaussian_kernel = gaussian_kernel / torch.sum(gaussian_kernel) return gaussian_kernel.view(1, 1, kernel_size, kernel_size).repeat( 3, 1, 1, 1) class gaussian_layerNew(nn.Module): """ Gaussian layer for the dowsampling pyramid """ def __init__(self, gaussian_kernel_size, gaussian_std, stride=2, pad=False ): super(gaussian_layerNew, self).__init__() self.downsample = gaussian_downsample(gaussian_kernel_size, gaussian_std, stride, pad=pad) def forward(self, input_0): arg0_1 = self.downsample.gauss.weight arg1_1 = input_0 output = call([arg0_1, arg1_1]) return output[0]
Xmaster6y/wgenpatex
gaussian_layer
false
18,120
[ "MIT" ]
8
08079dc131cc2e9c74ee4f9e16cf9b58667f2b07
https://github.com/Xmaster6y/wgenpatex/tree/08079dc131cc2e9c74ee4f9e16cf9b58667f2b07
ToRGB
from torch.autograd import Function import math import torch import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import nn as nn from torch.nn import init as init from torchvision.models import vgg as vgg from torch import autograd as autograd def make_resample_kernel(k): """Make resampling kernel for UpFirDn. Args: k (list[int]): A list indicating the 1D resample kernel magnitude. Returns: Tensor: 2D resampled kernel. """ k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape(-1, in_h, in_w, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(- pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :] out = out.permute(0, 3, 1, 2) out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1) out = out.permute(0, 2, 3, 1) out = out[:, ::down_y, ::down_x, :] out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 return out.view(-1, channel, out_h, out_w) def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): if input.device.type == 'cpu': out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) else: out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0 ], pad[1], pad[0], pad[1])) return out def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size): up_x, up_y = up down_x, down_y = down g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) grad_input = upfirdn2d_ext.upfirdn2d(grad_output, grad_kernel, down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) ctx.save_for_backward(kernel) pad_x0, pad_x1, pad_y0, pad_y1 = pad ctx.up_x = up_x ctx.up_y = up_y ctx.down_x = down_x ctx.down_y = down_y ctx.pad_x0 = pad_x0 ctx.pad_x1 = pad_x1 ctx.pad_y0 = pad_y0 ctx.pad_y1 = pad_y1 ctx.in_size = in_size ctx.out_size = out_size return grad_input @staticmethod def backward(ctx, gradgrad_input): kernel, = ctx.saved_tensors gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx. in_size[3], 1) gradgrad_out = upfirdn2d_ext.upfirdn2d(gradgrad_input, kernel, ctx. up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1, ctx.pad_y0, ctx.pad_y1) gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]) return gradgrad_out, None, None, None, None, None, None, None, None class UpFirDn2d(Function): @staticmethod def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape _batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = out_h, out_w ctx.up = up_x, up_y ctx.down = down_x, down_y ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1 g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 out = upfirdn2d_ext.upfirdn2d(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1) out = out.view(-1, channel, out_h, out_w) return out @staticmethod def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply(grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size) return grad_input, None, None, None, None class UpFirDnUpsample(nn.Module): """Upsample, FIR filter, and downsample (upsampole version). References: 1. https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.upfirdn.html # noqa: E501 2. http://www.ece.northwestern.edu/local-apps/matlabhelp/toolbox/signal/upfirdn.html # noqa: E501 Args: resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. factor (int): Upsampling scale factor. Default: 2. """ def __init__(self, resample_kernel, factor=2): super(UpFirDnUpsample, self).__init__() self.kernel = make_resample_kernel(resample_kernel) * factor ** 2 self.factor = factor pad = self.kernel.shape[0] - factor self.pad = (pad + 1) // 2 + factor - 1, pad // 2 def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=self.factor, down=1, pad=self.pad) return out def __repr__(self): return f'{self.__class__.__name__}(factor={self.factor})' class UpFirDnSmooth(nn.Module): """Upsample, FIR filter, and downsample (smooth version). Args: resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. upsample_factor (int): Upsampling scale factor. Default: 1. downsample_factor (int): Downsampling scale factor. Default: 1. kernel_size (int): Kernel size: Deafult: 1. """ def __init__(self, resample_kernel, upsample_factor=1, downsample_factor=1, kernel_size=1): super(UpFirDnSmooth, self).__init__() self.upsample_factor = upsample_factor self.downsample_factor = downsample_factor self.kernel = make_resample_kernel(resample_kernel) if upsample_factor > 1: self.kernel = self.kernel * upsample_factor ** 2 if upsample_factor > 1: pad = self.kernel.shape[0] - upsample_factor - (kernel_size - 1) self.pad = (pad + 1) // 2 + upsample_factor - 1, pad // 2 + 1 elif downsample_factor > 1: pad = self.kernel.shape[0] - downsample_factor + (kernel_size - 1) self.pad = (pad + 1) // 2, pad // 2 else: raise NotImplementedError def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=1, down=1, pad=self.pad) return out def __repr__(self): return ( f'{self.__class__.__name__}(upsample_factor={self.upsample_factor}, downsample_factor={self.downsample_factor})' ) class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) dim = [0] if grad_input.ndim > 2: dim += list(range(2, grad_input.ndim)) grad_bias = grad_input.sum(dim).detach() return grad_input, grad_bias @staticmethod def backward(ctx, gradgrad_input, gradgrad_bias): out, = ctx.saved_tensors gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale) return gradgrad_out, None, None, None class FusedLeakyReLUFunction(Function): @staticmethod def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out @staticmethod def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale) return grad_input, grad_bias, None, None class EqualLinear(nn.Module): """Equalized Linear as StyleGAN2. Args: in_channels (int): Size of each sample. out_channels (int): Size of each output sample. bias (bool): If set to ``False``, the layer will not learn an additive bias. Default: ``True``. bias_init_val (float): Bias initialized value. Default: 0. lr_mul (float): Learning rate multiplier. Default: 1. activation (None | str): The activation after ``linear`` operation. Supported: 'fused_lrelu', None. Default: None. """ def __init__(self, in_channels, out_channels, bias=True, bias_init_val= 0, lr_mul=1, activation=None): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ['fused_lrelu', None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}Supported ones are: ['fused_lrelu', None]." ) self.scale = 1 / math.sqrt(in_channels) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels). div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_( bias_init_val)) else: self.register_parameter('bias', None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == 'fused_lrelu': out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, bias={self.bias is not None})' ) class ModulatedConv2d(nn.Module): """Modulated Conv2d used in StyleGAN2. There is no bias in ModulatedConv2d. Args: in_channels (int): Channel number of the input. out_channels (int): Channel number of the output. kernel_size (int): Size of the convolving kernel. num_style_feat (int): Channel number of style features. demodulate (bool): Whether to demodulate in the conv layer. Default: True. sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None. resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. Default: (1, 3, 3, 1). eps (float): A value added to the denominator for numerical stability. Default: 1e-8. """ def __init__(self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, resample_kernel= (1, 3, 3, 1), eps=1e-08): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps if self.sample_mode == 'upsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=2, downsample_factor=1, kernel_size=kernel_size) elif self.sample_mode == 'downsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=1, downsample_factor=2, kernel_size=kernel_size) elif self.sample_mode is None: pass else: raise ValueError( f"Wrong sample mode {self.sample_mode}, supported ones are ['upsample', 'downsample', None]." ) self.scale = 1 / math.sqrt(in_channels * kernel_size ** 2) self.modulation = EqualLinear(num_style_feat, in_channels, bias= True, bias_init_val=1, lr_mul=1, activation=None) self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size)) self.padding = kernel_size // 2 def forward(self, x, style): """Forward function. Args: x (Tensor): Tensor with shape (b, c, h, w). style (Tensor): Tensor with shape (b, num_style_feat). Returns: Tensor: Modulated tensor after convolution. """ b, c, h, w = x.shape style = self.modulation(style).view(b, 1, c, 1, 1) weight = self.scale * self.weight * style if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(b, self.out_channels, 1, 1, 1) weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size) if self.sample_mode == 'upsample': x = x.view(1, b * c, h, w) weight = weight.view(b, self.out_channels, c, self.kernel_size, self.kernel_size) weight = weight.transpose(1, 2).reshape(b * c, self. out_channels, self.kernel_size, self.kernel_size) out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) out = self.smooth(out) elif self.sample_mode == 'downsample': x = self.smooth(x) x = x.view(1, b * c, *x.shape[2:4]) out = F.conv2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) else: x = x.view(1, b * c, h, w) out = F.conv2d(x, weight, padding=self.padding, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, kernel_size={self.kernel_size}, demodulate={self.demodulate}, sample_mode={self.sample_mode})' ) class ToRGB(nn.Module): """To RGB from features. Args: in_channels (int): Channel number of input. num_style_feat (int): Channel number of style features. upsample (bool): Whether to upsample. Default: True. resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. Default: (1, 3, 3, 1). """ def __init__(self, in_channels, num_style_feat, upsample=True, resample_kernel=(1, 3, 3, 1)): super(ToRGB, self).__init__() if upsample: self.upsample = UpFirDnUpsample(resample_kernel, factor=2) else: self.upsample = None self.modulated_conv = ModulatedConv2d(in_channels, 3, kernel_size=1, num_style_feat=num_style_feat, demodulate=False, sample_mode=None) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, x, style, skip=None): """Forward function. Args: x (Tensor): Feature tensor with shape (b, c, h, w). style (Tensor): Tensor with shape (b, num_style_feat). skip (Tensor): Base/skip tensor. Default: None. Returns: Tensor: RGB images. """ out = self.modulated_conv(x, style) out = out + self.bias if skip is not None: if self.upsample: skip = self.upsample(skip) out = out + skip return out def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'num_style_feat': 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.autograd import Function import math import torch.utils.data from torch.utils import data as data from torch.nn import functional as F from torch import 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_mul_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 = 0.5 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused_mul_1(in_ptr0, 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 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 48 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex % 12 x0 = xindex % 4 x2 = xindex // 12 x4 = xindex tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp1 = 0.5 tmp2 = tmp0 * tmp1 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x4, tmp4, xmask) @triton.jit def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 3 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 = 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, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (1, 3, 4, 1, 1), (12, 4, 1, 1, 1)) assert_size_stride(primals_6, (1, 3, 1, 1), (3, 1, 1, 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_0[grid(16)](primals_3, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 buf1 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused_mul_1[grid(4)](primals_2, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) del primals_2 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(buf1, primals_4, reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del buf0 del buf1 buf3 = empty_strided_cuda((4, 3, 4, 1, 1), (12, 4, 1, 1, 1), torch. float32) triton_poi_fused_mul_2[grid(48)](primals_5, buf2, buf3, 48, XBLOCK= 64, num_warps=1, num_stages=1) buf4 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf3, (12, 4, 1, 1), (4, 1, 0, 0), 0), stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None) assert_size_stride(buf4, (1, 12, 4, 4), (192, 16, 4, 1)) buf5 = reinterpret_tensor(buf4, (4, 3, 4, 4), (48, 16, 4, 1), 0) del buf4 triton_poi_fused_add_3[grid(192)](buf5, primals_6, 192, XBLOCK=128, num_warps=4, num_stages=1) del primals_6 return buf5, primals_4, primals_5, buf2, reinterpret_tensor(buf3, (12, 4, 1, 1), (4, 1, 1, 1), 0), reinterpret_tensor(primals_1, (1, 16, 4, 4), (256, 16, 4, 1), 0) def make_resample_kernel(k): """Make resampling kernel for UpFirDn. Args: k (list[int]): A list indicating the 1D resample kernel magnitude. Returns: Tensor: 2D resampled kernel. """ k = torch.tensor(k, dtype=torch.float32) if k.ndim == 1: k = k[None, :] * k[:, None] k /= k.sum() return k def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): _, channel, in_h, in_w = input.shape input = input.reshape(-1, in_h, in_w, 1) _, in_h, in_w, minor = input.shape kernel_h, kernel_w = kernel.shape out = input.view(-1, in_h, 1, in_w, 1, minor) out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) out = out.view(-1, in_h * up_y, in_w * up_x, minor) out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(- pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :] out = out.permute(0, 3, 1, 2) out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) out = F.conv2d(out, w) out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1) out = out.permute(0, 2, 3, 1) out = out[:, ::down_y, ::down_x, :] out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 return out.view(-1, channel, out_h, out_w) def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): if input.device.type == 'cpu': out = upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) else: out = UpFirDn2d.apply(input, kernel, (up, up), (down, down), (pad[0 ], pad[1], pad[0], pad[1])) return out def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size): up_x, up_y = up down_x, down_y = down g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) grad_input = upfirdn2d_ext.upfirdn2d(grad_output, grad_kernel, down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) ctx.save_for_backward(kernel) pad_x0, pad_x1, pad_y0, pad_y1 = pad ctx.up_x = up_x ctx.up_y = up_y ctx.down_x = down_x ctx.down_y = down_y ctx.pad_x0 = pad_x0 ctx.pad_x1 = pad_x1 ctx.pad_y0 = pad_y0 ctx.pad_y1 = pad_y1 ctx.in_size = in_size ctx.out_size = out_size return grad_input @staticmethod def backward(ctx, gradgrad_input): kernel, = ctx.saved_tensors gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx. in_size[3], 1) gradgrad_out = upfirdn2d_ext.upfirdn2d(gradgrad_input, kernel, ctx. up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1, ctx.pad_y0, ctx.pad_y1) gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1]) return gradgrad_out, None, None, None, None, None, None, None, None class UpFirDn2d(Function): @staticmethod def forward(ctx, input, kernel, up, down, pad): up_x, up_y = up down_x, down_y = down pad_x0, pad_x1, pad_y0, pad_y1 = pad kernel_h, kernel_w = kernel.shape _batch, channel, in_h, in_w = input.shape ctx.in_size = input.shape input = input.reshape(-1, in_h, in_w, 1) ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 ctx.out_size = out_h, out_w ctx.up = up_x, up_y ctx.down = down_x, down_y ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1 g_pad_x0 = kernel_w - pad_x0 - 1 g_pad_y0 = kernel_h - pad_y0 - 1 g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 out = upfirdn2d_ext.upfirdn2d(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1) out = out.view(-1, channel, out_h, out_w) return out @staticmethod def backward(ctx, grad_output): kernel, grad_kernel = ctx.saved_tensors grad_input = UpFirDn2dBackward.apply(grad_output, kernel, grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.in_size, ctx.out_size) return grad_input, None, None, None, None class UpFirDnUpsample(nn.Module): """Upsample, FIR filter, and downsample (upsampole version). References: 1. https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.upfirdn.html # noqa: E501 2. http://www.ece.northwestern.edu/local-apps/matlabhelp/toolbox/signal/upfirdn.html # noqa: E501 Args: resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. factor (int): Upsampling scale factor. Default: 2. """ def __init__(self, resample_kernel, factor=2): super(UpFirDnUpsample, self).__init__() self.kernel = make_resample_kernel(resample_kernel) * factor ** 2 self.factor = factor pad = self.kernel.shape[0] - factor self.pad = (pad + 1) // 2 + factor - 1, pad // 2 def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=self.factor, down=1, pad=self.pad) return out def __repr__(self): return f'{self.__class__.__name__}(factor={self.factor})' class UpFirDnSmooth(nn.Module): """Upsample, FIR filter, and downsample (smooth version). Args: resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. upsample_factor (int): Upsampling scale factor. Default: 1. downsample_factor (int): Downsampling scale factor. Default: 1. kernel_size (int): Kernel size: Deafult: 1. """ def __init__(self, resample_kernel, upsample_factor=1, downsample_factor=1, kernel_size=1): super(UpFirDnSmooth, self).__init__() self.upsample_factor = upsample_factor self.downsample_factor = downsample_factor self.kernel = make_resample_kernel(resample_kernel) if upsample_factor > 1: self.kernel = self.kernel * upsample_factor ** 2 if upsample_factor > 1: pad = self.kernel.shape[0] - upsample_factor - (kernel_size - 1) self.pad = (pad + 1) // 2 + upsample_factor - 1, pad // 2 + 1 elif downsample_factor > 1: pad = self.kernel.shape[0] - downsample_factor + (kernel_size - 1) self.pad = (pad + 1) // 2, pad // 2 else: raise NotImplementedError def forward(self, x): out = upfirdn2d(x, self.kernel.type_as(x), up=1, down=1, pad=self.pad) return out def __repr__(self): return ( f'{self.__class__.__name__}(upsample_factor={self.upsample_factor}, downsample_factor={self.downsample_factor})' ) class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_slope, scale): ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale empty = grad_output.new_empty(0) grad_input = fused_act_ext.fused_bias_act(grad_output, empty, out, 3, 1, negative_slope, scale) dim = [0] if grad_input.ndim > 2: dim += list(range(2, grad_input.ndim)) grad_bias = grad_input.sum(dim).detach() return grad_input, grad_bias @staticmethod def backward(ctx, gradgrad_input, gradgrad_bias): out, = ctx.saved_tensors gradgrad_out = fused_act_ext.fused_bias_act(gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale) return gradgrad_out, None, None, None class FusedLeakyReLUFunction(Function): @staticmethod def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scale = scale return out @staticmethod def backward(ctx, grad_output): out, = ctx.saved_tensors grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( grad_output, out, ctx.negative_slope, ctx.scale) return grad_input, grad_bias, None, None class EqualLinear(nn.Module): """Equalized Linear as StyleGAN2. Args: in_channels (int): Size of each sample. out_channels (int): Size of each output sample. bias (bool): If set to ``False``, the layer will not learn an additive bias. Default: ``True``. bias_init_val (float): Bias initialized value. Default: 0. lr_mul (float): Learning rate multiplier. Default: 1. activation (None | str): The activation after ``linear`` operation. Supported: 'fused_lrelu', None. Default: None. """ def __init__(self, in_channels, out_channels, bias=True, bias_init_val= 0, lr_mul=1, activation=None): super(EqualLinear, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.lr_mul = lr_mul self.activation = activation if self.activation not in ['fused_lrelu', None]: raise ValueError( f"Wrong activation value in EqualLinear: {activation}Supported ones are: ['fused_lrelu', None]." ) self.scale = 1 / math.sqrt(in_channels) * lr_mul self.weight = nn.Parameter(torch.randn(out_channels, in_channels). div_(lr_mul)) if bias: self.bias = nn.Parameter(torch.zeros(out_channels).fill_( bias_init_val)) else: self.register_parameter('bias', None) def forward(self, x): if self.bias is None: bias = None else: bias = self.bias * self.lr_mul if self.activation == 'fused_lrelu': out = F.linear(x, self.weight * self.scale) out = fused_leaky_relu(out, bias) else: out = F.linear(x, self.weight * self.scale, bias=bias) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, bias={self.bias is not None})' ) class ModulatedConv2d(nn.Module): """Modulated Conv2d used in StyleGAN2. There is no bias in ModulatedConv2d. Args: in_channels (int): Channel number of the input. out_channels (int): Channel number of the output. kernel_size (int): Size of the convolving kernel. num_style_feat (int): Channel number of style features. demodulate (bool): Whether to demodulate in the conv layer. Default: True. sample_mode (str | None): Indicating 'upsample', 'downsample' or None. Default: None. resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. Default: (1, 3, 3, 1). eps (float): A value added to the denominator for numerical stability. Default: 1e-8. """ def __init__(self, in_channels, out_channels, kernel_size, num_style_feat, demodulate=True, sample_mode=None, resample_kernel= (1, 3, 3, 1), eps=1e-08): super(ModulatedConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.demodulate = demodulate self.sample_mode = sample_mode self.eps = eps if self.sample_mode == 'upsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=2, downsample_factor=1, kernel_size=kernel_size) elif self.sample_mode == 'downsample': self.smooth = UpFirDnSmooth(resample_kernel, upsample_factor=1, downsample_factor=2, kernel_size=kernel_size) elif self.sample_mode is None: pass else: raise ValueError( f"Wrong sample mode {self.sample_mode}, supported ones are ['upsample', 'downsample', None]." ) self.scale = 1 / math.sqrt(in_channels * kernel_size ** 2) self.modulation = EqualLinear(num_style_feat, in_channels, bias= True, bias_init_val=1, lr_mul=1, activation=None) self.weight = nn.Parameter(torch.randn(1, out_channels, in_channels, kernel_size, kernel_size)) self.padding = kernel_size // 2 def forward(self, x, style): """Forward function. Args: x (Tensor): Tensor with shape (b, c, h, w). style (Tensor): Tensor with shape (b, num_style_feat). Returns: Tensor: Modulated tensor after convolution. """ b, c, h, w = x.shape style = self.modulation(style).view(b, 1, c, 1, 1) weight = self.scale * self.weight * style if self.demodulate: demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + self.eps) weight = weight * demod.view(b, self.out_channels, 1, 1, 1) weight = weight.view(b * self.out_channels, c, self.kernel_size, self.kernel_size) if self.sample_mode == 'upsample': x = x.view(1, b * c, h, w) weight = weight.view(b, self.out_channels, c, self.kernel_size, self.kernel_size) weight = weight.transpose(1, 2).reshape(b * c, self. out_channels, self.kernel_size, self.kernel_size) out = F.conv_transpose2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) out = self.smooth(out) elif self.sample_mode == 'downsample': x = self.smooth(x) x = x.view(1, b * c, *x.shape[2:4]) out = F.conv2d(x, weight, padding=0, stride=2, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) else: x = x.view(1, b * c, h, w) out = F.conv2d(x, weight, padding=self.padding, groups=b) out = out.view(b, self.out_channels, *out.shape[2:4]) return out def __repr__(self): return ( f'{self.__class__.__name__}(in_channels={self.in_channels}, out_channels={self.out_channels}, kernel_size={self.kernel_size}, demodulate={self.demodulate}, sample_mode={self.sample_mode})' ) class ToRGBNew(nn.Module): """To RGB from features. Args: in_channels (int): Channel number of input. num_style_feat (int): Channel number of style features. upsample (bool): Whether to upsample. Default: True. resample_kernel (list[int]): A list indicating the 1D resample kernel magnitude. Default: (1, 3, 3, 1). """ def __init__(self, in_channels, num_style_feat, upsample=True, resample_kernel=(1, 3, 3, 1)): super(ToRGBNew, self).__init__() if upsample: self.upsample = UpFirDnUpsample(resample_kernel, factor=2) else: self.upsample = None self.modulated_conv = ModulatedConv2d(in_channels, 3, kernel_size=1, num_style_feat=num_style_feat, demodulate=False, sample_mode=None) self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) def forward(self, input_0, input_1): primals_6 = self.bias primals_5 = self.modulated_conv.weight primals_3 = self.modulated_conv.modulation.weight primals_2 = self.modulated_conv.modulation.bias primals_1 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
WoojunePark/BasicSR
ToRGB
false
18,121
[ "Apache-2.0" ]
9
e0910b022b924bb913045fc412a5470dc2242cf0
https://github.com/WoojunePark/BasicSR/tree/e0910b022b924bb913045fc412a5470dc2242cf0
PairwiseRankingLoss
import torch import torch.nn as nn class PairwiseRankingLoss(nn.Module): """ Pairwise ranking loss """ def __init__(self, margin): super(PairwiseRankingLoss, self).__init__() self.margin = margin def forward(self, anchor1, anchor2, img_sentc, sent_imgc): cost_sent = torch.clamp(self.margin - anchor1 + img_sentc, min=0.0 ).sum() cost_img = torch.clamp(self.margin - anchor2 + sent_imgc, min=0.0).sum( ) loss = cost_sent + cost_img return 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])] def get_init_inputs(): return [[], {'margin': 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 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_clamp_rsub_sum_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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) tmp10 = tl.load(in_ptr2 + r0, None) tmp12 = tl.load(in_ptr3 + r0, None) tmp1 = 4.0 tmp2 = tmp1 - tmp0 tmp4 = tmp2 + tmp3 tmp5 = 0.0 tmp6 = triton_helpers.maximum(tmp4, tmp5) tmp7 = tl.broadcast_to(tmp6, [RBLOCK]) tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0)) tmp11 = tmp1 - tmp10 tmp13 = tmp11 + tmp12 tmp14 = triton_helpers.maximum(tmp13, tmp5) tmp15 = tl.broadcast_to(tmp14, [RBLOCK]) tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0)) tmp18 = tmp9 + tmp17 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp18, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_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)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_clamp_rsub_sum_0[grid(1)](buf2, arg0_1, arg1_1, arg2_1, arg3_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 return buf2, class PairwiseRankingLossNew(nn.Module): """ Pairwise ranking loss """ def __init__(self, margin): super(PairwiseRankingLossNew, self).__init__() self.margin = margin def forward(self, input_0, input_1, input_2, input_3): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 arg3_1 = input_3 output = call([arg0_1, arg1_1, arg2_1, arg3_1]) return output[0]
YJiangcm/DCPCSE
PairwiseRankingLoss
false
18,122
[ "MIT" ]
5
698255e2e66b402325ff611e098e01d2f322743e
https://github.com/YJiangcm/DCPCSE/tree/698255e2e66b402325ff611e098e01d2f322743e
Resv1Block
import torch import torch.nn as nn from itertools import product as product from math import sqrt as sqrt import torch.utils.data def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class Resv1Block(nn.Module): """ResNet v1 block without bn""" def __init__(self, inplanes, planes, stride=1): super(Resv1Block, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.relu1 = nn.ReLU() self.conv2 = conv3x3(planes, planes, stride) self.relu2 = nn.ReLU() def forward(self, x): out = self.conv1(x) out = self.relu1(out) out = self.conv2(out) out += x out = self.relu2(out) return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'inplanes': 4, 'planes': 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 itertools import product as product from math import sqrt as sqrt 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_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.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tl.store(in_out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused_add_relu_threshold_backward_1(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 x0 = xindex tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask) 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 + x0, tmp4, xmask) tl.store(out_ptr0 + x0, tmp6, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1, 1), padding=(1, 1), 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_relu_0[grid(256)](buf1, 256, XBLOCK=128, num_warps =4, num_stages=1) buf2 = extern_kernels.convolution(buf1, primals_3, 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 buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_add_relu_threshold_backward_1[grid(256)](buf3, primals_2, buf4, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf3, primals_1, primals_2, primals_3, buf1, buf4 def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class Resv1BlockNew(nn.Module): """ResNet v1 block without bn""" def __init__(self, inplanes, planes, stride=1): super(Resv1BlockNew, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.relu1 = nn.ReLU() self.conv2 = conv3x3(planes, planes, stride) self.relu2 = nn.ReLU() 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]
XiangLiK/cv_course
Resv1Block
false
18,124
[ "MIT" ]
8
da7c2318fd4128bbdab96db26ddbb2524f37d0a0
https://github.com/XiangLiK/cv_course/tree/da7c2318fd4128bbdab96db26ddbb2524f37d0a0
Similarity
import torch import torch.nn as nn class Similarity(nn.Module): """ Dot product or cosine similarity """ def __init__(self, temp): super().__init__() self.temp = temp self.cos = nn.CosineSimilarity(dim=-1) def forward(self, x, y): return self.cos(x, y) / self.temp def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'temp': 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 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_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 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') tmp16 = tl.load(in_ptr1 + x2, xmask) tmp17 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp19 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp22 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp25 = tl.load(in_ptr1 + (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-08 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 + x2, tmp31, xmask) @triton.jit def triton_poi_fused_div_sum_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 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 = 0.25 tmp8 = tmp6 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) 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((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_div_sum_1[grid(64)](buf0, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 return buf1, class SimilarityNew(nn.Module): """ Dot product or cosine similarity """ def __init__(self, temp): super().__init__() self.temp = temp self.cos = nn.CosineSimilarity(dim=-1) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
YJiangcm/DCPCSE
Similarity
false
18,125
[ "MIT" ]
5
698255e2e66b402325ff611e098e01d2f322743e
https://github.com/YJiangcm/DCPCSE/tree/698255e2e66b402325ff611e098e01d2f322743e
ResidualBlockNoBN
import torch import torch.utils.data from torch.utils import data as data from torch import nn as nn from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from torchvision.models import vgg as vgg from torch import autograd as autograd @torch.no_grad() def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs): """Initialize network weights. Args: module_list (list[nn.Module] | nn.Module): Modules to be initialized. scale (float): Scale initialized weights, especially for residual blocks. Default: 1. bias_fill (float): The value to fill bias. Default: 0 kwargs (dict): Other arguments for initialization function. """ if not isinstance(module_list, list): module_list = [module_list] for module in module_list: for m in module.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight, **kwargs) m.weight.data *= scale if m.bias is not None: m.bias.data.fill_(bias_fill) elif isinstance(m, nn.Linear): init.kaiming_normal_(m.weight, **kwargs) m.weight.data *= scale if m.bias is not None: m.bias.data.fill_(bias_fill) elif isinstance(m, _BatchNorm): init.constant_(m.weight, 1) if m.bias is not None: m.bias.data.fill_(bias_fill) class ResidualBlockNoBN(nn.Module): """Residual block without BN. It has a style of: ---Conv-ReLU-Conv-+- |________________| Args: num_feat (int): Channel number of intermediate features. Default: 64. res_scale (float): Residual scale. Default: 1. pytorch_init (bool): If set to True, use pytorch default init, otherwise, use default_init_weights. Default: False. """ def __init__(self, num_feat=64, res_scale=1, pytorch_init=False): super(ResidualBlockNoBN, self).__init__() self.res_scale = res_scale self.conv1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True) self.conv2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True) self.relu = nn.ReLU(inplace=True) if not pytorch_init: default_init_weights([self.conv1, self.conv2], 0.1) def forward(self, x): identity = x out = self.conv2(self.relu(self.conv1(x))) return identity + out * self.res_scale def get_inputs(): return [torch.rand([4, 64, 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.utils.data from torch.utils import data as data from torch import nn as nn from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from torchvision.models import vgg as vgg from torch import autograd as autograd 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): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 4096 % 64 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, 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 + x3, tmp4, None) @triton.jit def triton_poi_fused_add_convolution_mul_1(in_out_ptr0, in_ptr0, in_ptr1, 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 % 64 tmp0 = tl.load(in_ptr0 + x3, None) tmp1 = tl.load(in_out_ptr0 + x3, None) tmp2 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = 1.0 tmp5 = tmp3 * tmp4 tmp6 = tmp0 + tmp5 tl.store(in_out_ptr0 + x3, tmp6, None) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 64, 64, 64), (262144, 4096, 64, 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,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 64, 64, 64), (262144, 4096, 64, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(1048576)](buf1, primals_3, 1048576, XBLOCK=1024, num_warps=4, num_stages=1) del primals_3 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, 64, 64, 64), (262144, 4096, 64, 1)) buf3 = buf2 del buf2 triton_poi_fused_add_convolution_mul_1[grid(1048576)](buf3, primals_1, primals_5, 1048576, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 return buf3, primals_1, primals_2, primals_4, buf1 @torch.no_grad() def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs): """Initialize network weights. Args: module_list (list[nn.Module] | nn.Module): Modules to be initialized. scale (float): Scale initialized weights, especially for residual blocks. Default: 1. bias_fill (float): The value to fill bias. Default: 0 kwargs (dict): Other arguments for initialization function. """ if not isinstance(module_list, list): module_list = [module_list] for module in module_list: for m in module.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight, **kwargs) m.weight.data *= scale if m.bias is not None: m.bias.data.fill_(bias_fill) elif isinstance(m, nn.Linear): init.kaiming_normal_(m.weight, **kwargs) m.weight.data *= scale if m.bias is not None: m.bias.data.fill_(bias_fill) elif isinstance(m, _BatchNorm): init.constant_(m.weight, 1) if m.bias is not None: m.bias.data.fill_(bias_fill) class ResidualBlockNoBNNew(nn.Module): """Residual block without BN. It has a style of: ---Conv-ReLU-Conv-+- |________________| Args: num_feat (int): Channel number of intermediate features. Default: 64. res_scale (float): Residual scale. Default: 1. pytorch_init (bool): If set to True, use pytorch default init, otherwise, use default_init_weights. Default: False. """ def __init__(self, num_feat=64, res_scale=1, pytorch_init=False): super(ResidualBlockNoBNNew, self).__init__() self.res_scale = res_scale self.conv1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True) self.conv2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=True) self.relu = nn.ReLU(inplace=True) if not pytorch_init: default_init_weights([self.conv1, self.conv2], 0.1) 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_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
WoojunePark/BasicSR
ResidualBlockNoBN
false
18,127
[ "Apache-2.0" ]
9
e0910b022b924bb913045fc412a5470dc2242cf0
https://github.com/WoojunePark/BasicSR/tree/e0910b022b924bb913045fc412a5470dc2242cf0