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
SELoss
import torch from torch import Tensor from torch import nn class SELoss(nn.MSELoss): def __init__(self): super().__init__(reduction='none') def forward(self, inputs: 'Tensor', target: 'Tensor') ->Tensor: return super().forward(inputs, target).sum(1) 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 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_mse_loss_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask) tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask) tmp4 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask) tmp5 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask) tmp9 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask) tmp10 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask) tmp14 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask) tmp15 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask) 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 tl.store(out_ptr0 + x2, tmp18, 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), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mse_loss_sum_0[grid(64)](arg1_1, arg0_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del arg0_1 del arg1_1 return buf0, class SELossNew(nn.MSELoss): def __init__(self): super().__init__(reduction='none') def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
kfirgedal/lightning-bolts
SELoss
false
12,661
[ "Apache-2.0" ]
0
cbb8b6c21ca1de757d0f289fb840d59a3b6a10f5
https://github.com/kfirgedal/lightning-bolts/tree/cbb8b6c21ca1de757d0f289fb840d59a3b6a10f5
BPR
import torch import torch.nn as nn import torch.nn.functional as F class BPR(nn.Module): def __init__(self, user_size, item_size, dim, weight_decay): super().__init__() self.W = nn.Parameter(torch.empty(user_size, dim)) None self.H = nn.Parameter(torch.empty(item_size, dim)) None nn.init.xavier_normal_(self.W.data) nn.init.xavier_normal_(self.H.data) self.weight_decay = weight_decay def forward(self, u, i, j): """Return loss value. Args: u(torch.LongTensor): tensor stored user indexes. [batch_size,] i(torch.LongTensor): tensor stored item indexes which is prefered by user. [batch_size,] j(torch.LongTensor): tensor stored item indexes which is not prefered by user. [batch_size,] Returns: torch.FloatTensor """ u = self.W[u, :] i = self.H[i, :] j = self.H[j, :] x_ui = torch.mul(u, i).sum(dim=1) x_uj = torch.mul(u, j).sum(dim=1) x_uij = x_ui - x_uj log_prob = F.logsigmoid(x_uij).sum() regularization = self.weight_decay * (u.norm(dim=1).pow(2).sum() + i.norm(dim=1).pow(2).sum() + j.norm(dim=1).pow(2).sum()) return -log_prob + regularization def recommend(self, u): """Return recommended item list given users. Args: u(torch.LongTensor): tensor stored user indexes. [batch_size,] Returns: pred(torch.LongTensor): recommended item list sorted by preference. [batch_size, item_size] """ u = self.W[u, :] x_ui = torch.mm(u, self.H.t()) pred = torch.argsort(x_ui, dim=1) return pred def get_inputs(): return [torch.ones([4], dtype=torch.int64), torch.ones([4], dtype=torch .int64), torch.ones([4], dtype=torch.int64)] def get_init_inputs(): return [[], {'user_size': 4, 'item_size': 4, 'dim': 4, 'weight_decay': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_index_linalg_vector_norm_log_sigmoid_forward_mul_neg_pow_sub_sum_0( in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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) tmp7 = tl.load(in_ptr2 + r0, None) tmp26 = tl.load(in_ptr4 + 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 + 4 * tmp4, None, eviction_policy='evict_last') tmp8 = tmp7 + tmp1 tmp9 = tmp7 < 0 tmp10 = tl.where(tmp9, tmp8, tmp7) tl.device_assert((0 <= tmp10) & (tmp10 < 4), 'index out of bounds: 0 <= tmp10 < 4') tmp12 = tl.load(in_ptr3 + 4 * tmp10, None, eviction_policy='evict_last') tmp13 = tmp6 * tmp12 tmp14 = tl.load(in_ptr1 + (1 + 4 * tmp4), None, eviction_policy= 'evict_last') tmp15 = tl.load(in_ptr3 + (1 + 4 * tmp10), None, eviction_policy= 'evict_last') tmp16 = tmp14 * tmp15 tmp17 = tmp13 + tmp16 tmp18 = tl.load(in_ptr1 + (2 + 4 * tmp4), None, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr3 + (2 + 4 * tmp10), None, eviction_policy= 'evict_last') tmp20 = tmp18 * tmp19 tmp21 = tmp17 + tmp20 tmp22 = tl.load(in_ptr1 + (3 + 4 * tmp4), None, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr3 + (3 + 4 * tmp10), None, eviction_policy= 'evict_last') tmp24 = tmp22 * tmp23 tmp25 = tmp21 + tmp24 tmp27 = tmp26 + tmp1 tmp28 = tmp26 < 0 tmp29 = tl.where(tmp28, tmp27, tmp26) tl.device_assert((0 <= tmp29) & (tmp29 < 4), 'index out of bounds: 0 <= tmp29 < 4') tmp31 = tl.load(in_ptr3 + 4 * tmp29, None, eviction_policy='evict_last') tmp32 = tmp6 * tmp31 tmp33 = tl.load(in_ptr3 + (1 + 4 * tmp29), None, eviction_policy= 'evict_last') tmp34 = tmp14 * tmp33 tmp35 = tmp32 + tmp34 tmp36 = tl.load(in_ptr3 + (2 + 4 * tmp29), None, eviction_policy= 'evict_last') tmp37 = tmp18 * tmp36 tmp38 = tmp35 + tmp37 tmp39 = tl.load(in_ptr3 + (3 + 4 * tmp29), None, eviction_policy= 'evict_last') tmp40 = tmp22 * tmp39 tmp41 = tmp38 + tmp40 tmp42 = tmp6 * tmp6 tmp43 = tmp14 * tmp14 tmp44 = tmp42 + tmp43 tmp45 = tmp18 * tmp18 tmp46 = tmp44 + tmp45 tmp47 = tmp22 * tmp22 tmp48 = tmp46 + tmp47 tmp49 = libdevice.sqrt(tmp48) tmp50 = tmp49 * tmp49 tmp51 = tl.broadcast_to(tmp50, [XBLOCK, RBLOCK]) tmp53 = tl.sum(tmp51, 1)[:, None] tmp54 = tmp12 * tmp12 tmp55 = tmp15 * tmp15 tmp56 = tmp54 + tmp55 tmp57 = tmp19 * tmp19 tmp58 = tmp56 + tmp57 tmp59 = tmp23 * tmp23 tmp60 = tmp58 + tmp59 tmp61 = libdevice.sqrt(tmp60) tmp62 = tmp61 * tmp61 tmp63 = tl.broadcast_to(tmp62, [XBLOCK, RBLOCK]) tmp65 = tl.sum(tmp63, 1)[:, None] tmp66 = tmp31 * tmp31 tmp67 = tmp33 * tmp33 tmp68 = tmp66 + tmp67 tmp69 = tmp36 * tmp36 tmp70 = tmp68 + tmp69 tmp71 = tmp39 * tmp39 tmp72 = tmp70 + tmp71 tmp73 = libdevice.sqrt(tmp72) tmp74 = tmp73 * tmp73 tmp75 = tl.broadcast_to(tmp74, [XBLOCK, RBLOCK]) tmp77 = tl.sum(tmp75, 1)[:, None] tmp78 = tmp25 - tmp41 tmp79 = 0.0 tmp80 = triton_helpers.minimum(tmp79, tmp78) tmp81 = tl_math.abs(tmp78) tmp82 = -tmp81 tmp83 = tl_math.exp(tmp82) tmp84 = libdevice.log1p(tmp83) tmp85 = tmp80 - tmp84 tmp86 = tl.broadcast_to(tmp85, [XBLOCK, RBLOCK]) tmp88 = tl.sum(tmp86, 1)[:, None] tmp89 = -tmp88 tmp90 = tmp53 + tmp65 tmp91 = tmp90 + tmp77 tmp92 = 4.0 tmp93 = tmp91 * tmp92 tmp94 = tmp89 + tmp93 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp94, None) 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, 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) buf2 = empty_strided_cuda((), (), torch.float32) buf6 = buf2 del buf2 get_raw_stream(0) triton_per_fused_add_index_linalg_vector_norm_log_sigmoid_forward_mul_neg_pow_sub_sum_0[ grid(1)](buf6, primals_2, primals_1, primals_4, primals_3, primals_5, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) return buf6, primals_1, primals_2, primals_3, primals_4, primals_5 class BPRNew(nn.Module): def __init__(self, user_size, item_size, dim, weight_decay): super().__init__() self.W = nn.Parameter(torch.empty(user_size, dim)) None self.H = nn.Parameter(torch.empty(item_size, dim)) None nn.init.xavier_normal_(self.W.data) nn.init.xavier_normal_(self.H.data) self.weight_decay = weight_decay def recommend(self, u): """Return recommended item list given users. Args: u(torch.LongTensor): tensor stored user indexes. [batch_size,] Returns: pred(torch.LongTensor): recommended item list sorted by preference. [batch_size, item_size] """ u = self.W[u, :] x_ui = torch.mm(u, self.H.t()) pred = torch.argsort(x_ui, dim=1) return pred def forward(self, input_0, input_1, input_2): primals_1 = self.W primals_3 = self.H primals_2 = input_0 primals_4 = input_1 primals_5 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
kerengaiger/bpr
BPR
false
12,662
[ "MIT" ]
0
66bfa57469a9c70ba5b9158fde5210abe1bd8d7b
https://github.com/kerengaiger/bpr/tree/66bfa57469a9c70ba5b9158fde5210abe1bd8d7b
SimulatorReward
import torch import torch.nn.functional as F class SimulatorReward(torch.nn.Module): def __init__(self): super(SimulatorReward, self).__init__() self.conv1 = torch.nn.Conv2d(4, 8, kernel_size=3, padding=1) self.conv2 = torch.nn.Conv2d(8, 16, kernel_size=3, padding=1) self.conv3 = torch.nn.Conv2d(16, 32, kernel_size=3, padding=1) self.fc1 = torch.nn.Linear(512, 200) self.fc2 = torch.nn.Linear(200, 100) self.fc3 = torch.nn.Linear(100, 3) def forward(self, x): x = x.reshape(-1, 4, 4, 4) x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = self.conv3(x) x = x.view(-1, 512) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return F.softmax(x) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 8 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): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 16 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_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 16 % 32 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_relu_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 800 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 200 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 100 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__softmax_5(in_ptr0, out_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_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 3 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 3 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 3 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp0 - tmp5 tmp7 = tl_math.exp(tmp6) tmp8 = tmp1 - tmp5 tmp9 = tl_math.exp(tmp8) tmp10 = tmp2 - tmp5 tmp11 = tl_math.exp(tmp10) tmp12 = tmp9 + tmp11 tmp13 = tmp4 - tmp5 tmp14 = tl_math.exp(tmp13) tmp15 = tmp12 + tmp14 tmp16 = tmp7 / tmp15 tl.store(out_ptr0 + x2, tmp16, 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, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (8, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_3, (8,), (1,)) assert_size_stride(primals_4, (16, 8, 3, 3), (72, 9, 3, 1)) assert_size_stride(primals_5, (16,), (1,)) assert_size_stride(primals_6, (32, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_7, (32,), (1,)) assert_size_stride(primals_8, (200, 512), (512, 1)) assert_size_stride(primals_9, (200,), (1,)) assert_size_stride(primals_10, (100, 200), (200, 1)) assert_size_stride(primals_11, (100,), (1,)) assert_size_stride(primals_12, (3, 100), (100, 1)) assert_size_stride(primals_13, (3,), (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, 8, 4, 4), (128, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(512)](buf1, primals_3, 512, XBLOCK=256, 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, 16, 4, 4), (256, 16, 4, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_1[grid(1024)](buf3, primals_5, 1024, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 32, 4, 4), (512, 16, 4, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_2[grid(2048)](buf5, primals_7, 2048, XBLOCK=128, num_warps=4, num_stages=1) del primals_7 buf6 = empty_strided_cuda((4, 200), (200, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (4, 512), (512, 1), 0), reinterpret_tensor(primals_8, (512, 200), (1, 512), 0), out=buf6) buf7 = buf6 del buf6 triton_poi_fused_relu_3[grid(800)](buf7, primals_9, 800, XBLOCK=128, num_warps=4, num_stages=1) del primals_9 buf8 = empty_strided_cuda((4, 100), (100, 1), torch.float32) extern_kernels.mm(buf7, reinterpret_tensor(primals_10, (200, 100), (1, 200), 0), out=buf8) buf9 = buf8 del buf8 triton_poi_fused_relu_4[grid(400)](buf9, primals_11, 400, XBLOCK= 256, num_warps=4, num_stages=1) del primals_11 buf10 = empty_strided_cuda((4, 3), (3, 1), torch.float32) extern_kernels.addmm(primals_13, buf9, reinterpret_tensor( primals_12, (100, 3), (1, 100), 0), alpha=1, beta=1, out=buf10) del primals_13 buf11 = empty_strided_cuda((4, 3), (3, 1), torch.float32) triton_poi_fused__softmax_5[grid(12)](buf10, buf11, 12, XBLOCK=16, num_warps=1, num_stages=1) del buf10 return (buf11, primals_2, primals_4, primals_6, primals_1, buf1, buf3, reinterpret_tensor(buf5, (4, 512), (512, 1), 0), buf7, buf9, buf11, primals_12, primals_10, primals_8) class SimulatorRewardNew(torch.nn.Module): def __init__(self): super(SimulatorRewardNew, self).__init__() self.conv1 = torch.nn.Conv2d(4, 8, kernel_size=3, padding=1) self.conv2 = torch.nn.Conv2d(8, 16, kernel_size=3, padding=1) self.conv3 = torch.nn.Conv2d(16, 32, kernel_size=3, padding=1) self.fc1 = torch.nn.Linear(512, 200) self.fc2 = torch.nn.Linear(200, 100) self.fc3 = torch.nn.Linear(100, 3) def forward(self, input_0): primals_2 = self.conv1.weight primals_3 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_6 = self.conv3.weight primals_7 = self.conv3.bias primals_8 = self.fc1.weight primals_9 = self.fc1.bias primals_10 = self.fc2.weight primals_11 = self.fc2.bias primals_12 = self.fc3.weight primals_13 = self.fc3.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]
karshtharyani/DeepReinforcementLearningInAction
SimulatorReward
false
12,663
[ "MIT" ]
0
9dc40a43b43f05daf9aecb7e3ec7592cf38720e5
https://github.com/karshtharyani/DeepReinforcementLearningInAction/tree/9dc40a43b43f05daf9aecb7e3ec7592cf38720e5
UnpoolingAsConvolution
import torch import torch.nn as nn def get_incoming_shape(incoming): size = incoming.size() return [size[0], size[1], size[2], size[3]] def interleave(tensors, axis): old_shape = get_incoming_shape(tensors[0])[1:] new_shape = [-1] + old_shape new_shape[axis] *= len(tensors) stacked = torch.stack(tensors, axis + 1) reshaped = stacked.view(new_shape) return reshaped class UnpoolingAsConvolution(nn.Module): def __init__(self, inplanes, planes): super(UnpoolingAsConvolution, self).__init__() self.conv_A = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(3, 3), stride=1, padding=1) self.conv_B = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(2, 3), stride=1, padding=0) self.conv_C = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(3, 2), stride=1, padding=0) self.conv_D = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(2, 2), stride=1, padding=0) def forward(self, x): output_a = self.conv_A(x) padded_b = nn.functional.pad(x, (1, 1, 0, 1)) output_b = self.conv_B(padded_b) padded_c = nn.functional.pad(x, (0, 1, 1, 1)) output_c = self.conv_C(padded_c) padded_d = nn.functional.pad(x, (0, 1, 0, 1)) output_d = self.conv_D(padded_d) left = interleave([output_a, output_b], axis=2) right = interleave([output_c, output_d], axis=2) y = interleave([left, right], axis=3) return y 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 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 = 480 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 6 % 5 x0 = xindex % 6 x2 = xindex // 30 x4 = xindex tmp0 = x1 tmp1 = tl.full([1], 4, tl.int64) tmp2 = tmp0 < tmp1 tmp3 = -1 + x0 tmp4 = tl.full([1], 0, tl.int64) tmp5 = tmp3 >= tmp4 tmp6 = tmp3 < tmp1 tmp7 = tmp2 & tmp5 tmp8 = tmp7 & tmp6 tmp9 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1 + 16 * x2), tmp8 & xmask, other=0.0) tl.store(out_ptr0 + x4, tmp9, xmask) @triton.jit def triton_poi_fused_constant_pad_nd_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 480 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 5 % 6 x0 = xindex % 5 x2 = xindex // 30 x3 = 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 = x0 tmp6 = tmp5 < tmp3 tmp7 = tmp2 & tmp4 tmp8 = tmp7 & tmp6 tmp9 = tl.load(in_ptr0 + (-4 + x0 + 4 * x1 + 16 * x2), tmp8 & xmask, other=0.0) tl.store(out_ptr0 + x3, tmp9, xmask) @triton.jit def triton_poi_fused_constant_pad_nd_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 5 % 5 x0 = xindex % 5 x2 = xindex // 25 x3 = xindex tmp0 = x1 tmp1 = tl.full([1], 4, tl.int64) tmp2 = tmp0 < tmp1 tmp3 = x0 tmp4 = tmp3 < tmp1 tmp5 = tmp2 & tmp4 tmp6 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp5 & xmask, other=0.0) tl.store(out_ptr0 + x3, tmp6, xmask) @triton.jit def triton_poi_fused_stack_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 2 x1 = xindex // 2 % 4 x2 = xindex // 8 % 8 x5 = xindex // 64 x3 = xindex // 64 % 4 x6 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = x1 + 4 * (x2 % 2) tmp7 = tl.full([1], 4, tl.int64) tmp8 = tmp5 < tmp7 tmp9 = tmp8 & tmp4 tmp10 = tl.load(in_ptr0 + (4 * (x2 // 2) + 16 * x5 + (x1 + 4 * (x2 % 2) )), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tl.load(in_ptr1 + x3, tmp9 & xmask, eviction_policy= 'evict_last', other=0.0) tmp12 = tmp10 + tmp11 tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype) tmp14 = tl.where(tmp9, tmp12, tmp13) tmp15 = tmp5 >= tmp7 tl.full([1], 8, tl.int64) tmp18 = tmp15 & tmp4 tmp19 = tl.load(in_ptr2 + (4 * (x2 // 2) + 16 * x5 + (-4 + x1 + 4 * (x2 % 2))), tmp18 & xmask, eviction_policy='evict_last', other=0.0) tmp20 = tl.load(in_ptr3 + x3, tmp18 & xmask, eviction_policy= 'evict_last', other=0.0) tmp21 = tmp19 + tmp20 tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype) tmp23 = tl.where(tmp18, tmp21, tmp22) tmp24 = tl.where(tmp8, tmp14, tmp23) tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype) tmp26 = tl.where(tmp4, tmp24, tmp25) tmp27 = tmp0 >= tmp3 tl.full([1], 2, tl.int64) tmp30 = tmp8 & tmp27 tmp31 = tl.load(in_ptr4 + (4 * (x2 // 2) + 16 * x5 + (x1 + 4 * (x2 % 2) )), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp32 = tl.load(in_ptr5 + x3, tmp30 & xmask, eviction_policy= 'evict_last', other=0.0) tmp33 = tmp31 + tmp32 tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype) tmp35 = tl.where(tmp30, tmp33, tmp34) tmp36 = tmp15 & tmp27 tmp37 = tl.load(in_ptr6 + (4 * (x2 // 2) + 16 * x5 + (-4 + x1 + 4 * (x2 % 2))), tmp36 & xmask, eviction_policy='evict_last', other=0.0) tmp38 = tl.load(in_ptr7 + x3, tmp36 & xmask, eviction_policy= 'evict_last', other=0.0) tmp39 = tmp37 + tmp38 tmp40 = tl.full(tmp39.shape, 0.0, tmp39.dtype) tmp41 = tl.where(tmp36, tmp39, tmp40) tmp42 = tl.where(tmp8, tmp35, tmp41) tmp43 = tl.full(tmp42.shape, 0.0, tmp42.dtype) tmp44 = tl.where(tmp27, tmp42, tmp43) tmp45 = tl.where(tmp4, tmp26, tmp44) tl.store(out_ptr0 + x6, tmp45, 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, 3, 3), (36, 9, 3, 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, 2, 3), (24, 6, 3, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 3, 2), (24, 6, 2, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4, 2, 2), (16, 4, 2, 1)) assert_size_stride(primals_9, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = 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(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = empty_strided_cuda((4, 4, 5, 6), (120, 30, 6, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(480)](primals_3, buf1, 480, XBLOCK=256, num_warps=4, num_stages=1) 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, 4, 4, 4), (64, 16, 4, 1)) buf3 = empty_strided_cuda((4, 4, 6, 5), (120, 30, 5, 1), torch.float32) triton_poi_fused_constant_pad_nd_1[grid(480)](primals_3, buf3, 480, XBLOCK=128, num_warps=4, num_stages=1) buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1)) buf5 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32) triton_poi_fused_constant_pad_nd_2[grid(400)](primals_3, buf5, 400, XBLOCK=256, num_warps=4, num_stages=1) buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1)) buf7 = empty_strided_cuda((4, 4, 8, 4, 2), (256, 64, 8, 2, 1), torch.float32) triton_poi_fused_stack_3[grid(1024)](buf0, primals_2, buf2, primals_5, buf4, primals_7, buf6, primals_9, buf7, 1024, XBLOCK =128, num_warps=4, num_stages=1) del buf0 del buf2 del buf4 del buf6 del primals_2 del primals_5 del primals_7 del primals_9 return reinterpret_tensor(buf7, (4, 4, 8, 8), (256, 64, 8, 1), 0 ), primals_1, primals_3, primals_4, primals_6, primals_8, buf1, buf3, buf5 def get_incoming_shape(incoming): size = incoming.size() return [size[0], size[1], size[2], size[3]] def interleave(tensors, axis): old_shape = get_incoming_shape(tensors[0])[1:] new_shape = [-1] + old_shape new_shape[axis] *= len(tensors) stacked = torch.stack(tensors, axis + 1) reshaped = stacked.view(new_shape) return reshaped class UnpoolingAsConvolutionNew(nn.Module): def __init__(self, inplanes, planes): super(UnpoolingAsConvolutionNew, self).__init__() self.conv_A = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(3, 3), stride=1, padding=1) self.conv_B = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(2, 3), stride=1, padding=0) self.conv_C = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(3, 2), stride=1, padding=0) self.conv_D = nn.Conv2d(in_channels=inplanes, out_channels=planes, kernel_size=(2, 2), stride=1, padding=0) def forward(self, input_0): primals_1 = self.conv_A.weight primals_2 = self.conv_A.bias primals_4 = self.conv_B.weight primals_5 = self.conv_B.bias primals_6 = self.conv_C.weight primals_7 = self.conv_C.bias primals_8 = self.conv_D.weight primals_9 = self.conv_D.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9]) return output[0]
karoly-hars/DE_hybrid_CNN
UnpoolingAsConvolution
false
12,664
[ "BSD-3-Clause" ]
0
d74ba4291d6db335151d5262ab96e8e3806a7587
https://github.com/karoly-hars/DE_hybrid_CNN/tree/d74ba4291d6db335151d5262ab96e8e3806a7587
ActorCriticMLP
import torch from torch import Tensor from torch import nn from typing import Tuple from torch.nn import functional as F class ActorCriticMLP(nn.Module): """MLP network with heads for actor and critic.""" def __init__(self, input_shape: 'Tuple[int]', n_actions: 'int', hidden_size: 'int'=128): """ Args: input_shape: observation shape of the environment n_actions: number of discrete actions available in the environment hidden_size: size of hidden layers """ super().__init__() self.fc1 = nn.Linear(input_shape[0], hidden_size) self.actor_head = nn.Linear(hidden_size, n_actions) self.critic_head = nn.Linear(hidden_size, 1) def forward(self, x) ->Tuple[Tensor, Tensor]: """Forward pass through network. Calculates the action logits and the value. Args: x: input to network Returns: action log probs (logits), value """ x = F.relu(self.fc1(x.float())) a = F.log_softmax(self.actor_head(x), dim=-1) c = self.critic_head(x) return a, c def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_shape': [4, 4], 'n_actions': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math from torch import nn from typing import Tuple 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) @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 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 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused__log_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') 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 = 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 tl.store(out_ptr0 + x2, tmp13, 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, (128, 4), (4, 1)) assert_size_stride(primals_3, (128,), (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_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 128), (1, 4), 0), out=buf0) del primals_2 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0) del buf0 buf7 = 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_3, buf7, 8192, XBLOCK=256, 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, 128), (128, 1), 0), reinterpret_tensor(primals_4, (128, 4), (1, 128), 0), alpha=1, beta=1, out=buf2) del primals_5 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__log_softmax_1[grid(256)](buf2, buf3, 256, XBLOCK= 256, num_warps=4, num_stages=1) buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused__log_softmax_2[grid(256)](buf3, buf4, 256, XBLOCK= 128, num_warps=4, num_stages=1) del buf3 buf6 = 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=buf6) del primals_7 return buf4, reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0 ), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 128), (128, 1), 0 ), buf4, primals_6, primals_4, buf7 class ActorCriticMLPNew(nn.Module): """MLP network with heads for actor and critic.""" def __init__(self, input_shape: 'Tuple[int]', n_actions: 'int', hidden_size: 'int'=128): """ Args: input_shape: observation shape of the environment n_actions: number of discrete actions available in the environment hidden_size: size of hidden layers """ super().__init__() self.fc1 = nn.Linear(input_shape[0], hidden_size) self.actor_head = nn.Linear(hidden_size, n_actions) self.critic_head = nn.Linear(hidden_size, 1) def forward(self, input_0): primals_2 = self.fc1.weight primals_3 = self.fc1.bias primals_4 = self.actor_head.weight primals_5 = self.actor_head.bias primals_6 = self.critic_head.weight primals_7 = self.critic_head.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0], output[1]
kfirgedal/lightning-bolts
ActorCriticMLP
false
12,665
[ "Apache-2.0" ]
0
cbb8b6c21ca1de757d0f289fb840d59a3b6a10f5
https://github.com/kfirgedal/lightning-bolts/tree/cbb8b6c21ca1de757d0f289fb840d59a3b6a10f5
SDNE_layer
import torch import torch.utils.data import torch.nn as nn import torch.nn.functional as F import torch as torch class SDNE_layer(nn.Module): def __init__(self, num_node, hidden_size1, hidden_size2, droput, alpha, beta, nu1, nu2): super(SDNE_layer, self).__init__() self.num_node = num_node self.hidden_size1 = hidden_size1 self.hidden_size2 = hidden_size2 self.droput = droput self.alpha = alpha self.beta = beta self.nu1 = nu1 self.nu2 = nu2 self.encode0 = nn.Linear(self.num_node, self.hidden_size1) self.encode1 = nn.Linear(self.hidden_size1, self.hidden_size2) self.decode0 = nn.Linear(self.hidden_size2, self.hidden_size1) self.decode1 = nn.Linear(self.hidden_size1, self.num_node) def forward(self, adj_mat, l_mat): t0 = F.leaky_relu(self.encode0(adj_mat)) t0 = F.leaky_relu(self.encode1(t0)) self.embedding = t0 t0 = F.leaky_relu(self.decode0(t0)) t0 = F.leaky_relu(self.decode1(t0)) L_1st = 2 * torch.trace(torch.mm(torch.mm(torch.t(self.embedding), l_mat), self.embedding)) L_2nd = torch.sum((adj_mat - t0) * adj_mat * self.beta * ((adj_mat - t0) * adj_mat * self.beta)) L_reg = 0 for param in self.parameters(): L_reg += self.nu1 * torch.sum(torch.abs(param) ) + self.nu2 * torch.sum(param * param) return self.alpha * L_1st, L_2nd, self.alpha * L_1st + L_2nd, L_reg def get_emb(self, adj): t0 = self.encode0(adj) t0 = self.encode1(t0) return t0 def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'num_node': 4, 'hidden_size1': 4, 'hidden_size2': 4, 'droput': 4, 'alpha': 4, 'beta': 4, 'nu1': 4, 'nu2': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import math as tl_math import torch.utils.data import torch.nn as nn import torch as torch 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_leaky_relu_0(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 x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.01 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr1 + x2, tmp7, xmask) @triton.jit def triton_per_fused_leaky_relu_mul_sub_sum_1(in_ptr0, in_ptr1, out_ptr0, 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) tmp1 = tl.load(in_ptr1 + r0, None) tmp2 = 0.0 tmp3 = tmp1 > tmp2 tmp4 = 0.01 tmp5 = tmp1 * tmp4 tmp6 = tl.where(tmp3, tmp1, tmp5) tmp7 = tmp0 - tmp6 tmp8 = tmp7 * tmp0 tmp9 = 4.0 tmp10 = tmp8 * tmp9 tmp11 = tmp10 * tmp10 tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK]) tmp14 = tl.sum(tmp12, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp14, None) @triton.jit def triton_per_fused_add_mul_trace_2(in_ptr0, in_ptr1, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + 0) tmp9 = tl.broadcast_to(tmp8, [XBLOCK, 1]) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.sum(tmp1, 1)[:, None] tmp4 = 2.0 tmp5 = tmp3 * tmp4 tmp6 = 4.0 tmp7 = tmp5 * tmp6 tmp10 = tmp7 + tmp9 tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None) tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp10, None) @triton.jit def triton_per_fused_abs_mul_sum_3(in_ptr0, out_ptr0, 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 + r0, None) tmp1 = tl_math.abs(tmp0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp5 = tmp0 * tmp0 tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tmp8 = tl.sum(tmp6, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp4, None) tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None) @triton.jit def triton_per_fused_abs_add_mul_sum_4(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10, in_ptr11, 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_ptr1 + r0, None) tmp18 = tl.load(in_ptr2 + r0, None) tmp27 = tl.load(in_ptr3 + r0, None) tmp42 = tl.load(in_ptr4 + 0) tmp43 = tl.broadcast_to(tmp42, [XBLOCK, 1]) tmp45 = tl.load(in_ptr5 + 0) tmp46 = tl.broadcast_to(tmp45, [XBLOCK, 1]) tmp54 = tl.load(in_ptr6 + 0) tmp55 = tl.broadcast_to(tmp54, [XBLOCK, 1]) tmp57 = tl.load(in_ptr7 + 0) tmp58 = tl.broadcast_to(tmp57, [XBLOCK, 1]) tmp66 = tl.load(in_ptr8 + 0) tmp67 = tl.broadcast_to(tmp66, [XBLOCK, 1]) tmp69 = tl.load(in_ptr9 + 0) tmp70 = tl.broadcast_to(tmp69, [XBLOCK, 1]) tmp78 = tl.load(in_ptr10 + 0) tmp79 = tl.broadcast_to(tmp78, [XBLOCK, 1]) tmp81 = tl.load(in_ptr11 + 0) tmp82 = tl.broadcast_to(tmp81, [XBLOCK, 1]) tmp1 = tl_math.abs(tmp0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp5 = tmp0 * tmp0 tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tmp8 = tl.sum(tmp6, 1)[:, None] tmp10 = tl_math.abs(tmp9) tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK]) tmp13 = tl.sum(tmp11, 1)[:, None] tmp14 = tmp9 * tmp9 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.sum(tmp15, 1)[:, None] tmp19 = tl_math.abs(tmp18) tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK]) tmp22 = tl.sum(tmp20, 1)[:, None] tmp23 = tmp18 * tmp18 tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK]) tmp26 = tl.sum(tmp24, 1)[:, None] tmp28 = tl_math.abs(tmp27) tmp29 = tl.broadcast_to(tmp28, [XBLOCK, RBLOCK]) tmp31 = tl.sum(tmp29, 1)[:, None] tmp32 = tmp27 * tmp27 tmp33 = tl.broadcast_to(tmp32, [XBLOCK, RBLOCK]) tmp35 = tl.sum(tmp33, 1)[:, None] tmp36 = 4.0 tmp37 = tmp4 * tmp36 tmp38 = tmp8 * tmp36 tmp39 = tmp37 + tmp38 tmp40 = 0.0 tmp41 = tmp39 + tmp40 tmp44 = tmp43 * tmp36 tmp47 = tmp46 * tmp36 tmp48 = tmp44 + tmp47 tmp49 = tmp41 + tmp48 tmp50 = tmp22 * tmp36 tmp51 = tmp26 * tmp36 tmp52 = tmp50 + tmp51 tmp53 = tmp49 + tmp52 tmp56 = tmp55 * tmp36 tmp59 = tmp58 * tmp36 tmp60 = tmp56 + tmp59 tmp61 = tmp53 + tmp60 tmp62 = tmp31 * tmp36 tmp63 = tmp35 * tmp36 tmp64 = tmp62 + tmp63 tmp65 = tmp61 + tmp64 tmp68 = tmp67 * tmp36 tmp71 = tmp70 * tmp36 tmp72 = tmp68 + tmp71 tmp73 = tmp65 + tmp72 tmp74 = tmp13 * tmp36 tmp75 = tmp17 * tmp36 tmp76 = tmp74 + tmp75 tmp77 = tmp73 + tmp76 tmp80 = tmp79 * tmp36 tmp83 = tmp82 * tmp36 tmp84 = tmp80 + tmp83 tmp85 = tmp77 + tmp84 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp85, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4), (4, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.bool) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_leaky_relu_0[grid(16)](buf0, primals_2, buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) buf3 = buf0 del buf0 extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4 ), 0), out=buf3) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_leaky_relu_0[grid(16)](buf3, primals_5, buf4, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1) buf6 = buf3 del buf3 extern_kernels.mm(buf5, reinterpret_tensor(primals_6, (4, 4), (1, 4 ), 0), out=buf6) buf7 = empty_strided_cuda((4, 4), (4, 1), torch.bool) buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_leaky_relu_0[grid(16)](buf6, primals_7, buf7, buf8, 16, XBLOCK=16, num_warps=1, num_stages=1) buf9 = buf6 del buf6 extern_kernels.addmm(primals_9, buf8, reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf9) buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (4, 4), (1, 4), 0), primals_10, out=buf10) buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf10, buf5, out=buf11) buf13 = empty_strided_cuda((), (), torch.float32) triton_per_fused_leaky_relu_mul_sub_sum_1[grid(1)](primals_3, buf9, buf13, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) buf31 = empty_strided_cuda((), (), torch.float32) buf32 = empty_strided_cuda((), (), torch.float32) triton_per_fused_add_mul_trace_2[grid(1)](buf11, buf13, buf31, buf32, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf11 buf16 = empty_strided_cuda((), (), torch.float32) buf17 = empty_strided_cuda((), (), torch.float32) triton_per_fused_abs_mul_sum_3[grid(1)](primals_2, buf16, buf17, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) buf20 = empty_strided_cuda((), (), torch.float32) buf21 = empty_strided_cuda((), (), torch.float32) triton_per_fused_abs_mul_sum_3[grid(1)](primals_5, buf20, buf21, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) buf25 = empty_strided_cuda((), (), torch.float32) buf26 = empty_strided_cuda((), (), torch.float32) triton_per_fused_abs_mul_sum_3[grid(1)](primals_7, buf25, buf26, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) buf29 = empty_strided_cuda((), (), torch.float32) buf30 = empty_strided_cuda((), (), torch.float32) triton_per_fused_abs_mul_sum_3[grid(1)](primals_9, buf29, buf30, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) buf14 = empty_strided_cuda((), (), torch.float32) buf24 = buf14 del buf14 buf33 = buf24 del buf24 triton_per_fused_abs_add_mul_sum_4[grid(1)](buf33, primals_1, primals_8, primals_4, primals_6, buf16, buf17, buf20, buf21, buf25, buf26, buf29, buf30, 1, 16, XBLOCK=1, num_warps=2, num_stages=1) del buf16 del buf17 del buf20 del buf21 del buf25 del buf26 del buf29 del buf30 return (buf31, buf13, buf32, buf33, buf5, primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, buf1, buf2, buf4, buf5, buf7, buf8, buf9, reinterpret_tensor(buf10, (4, 4), (1, 4), 0)) class SDNE_layerNew(nn.Module): def __init__(self, num_node, hidden_size1, hidden_size2, droput, alpha, beta, nu1, nu2): super(SDNE_layerNew, self).__init__() self.num_node = num_node self.hidden_size1 = hidden_size1 self.hidden_size2 = hidden_size2 self.droput = droput self.alpha = alpha self.beta = beta self.nu1 = nu1 self.nu2 = nu2 self.encode0 = nn.Linear(self.num_node, self.hidden_size1) self.encode1 = nn.Linear(self.hidden_size1, self.hidden_size2) self.decode0 = nn.Linear(self.hidden_size2, self.hidden_size1) self.decode1 = nn.Linear(self.hidden_size1, self.num_node) def get_emb(self, adj): t0 = self.encode0(adj) t0 = self.encode1(t0) return t0 def forward(self, input_0, input_1): primals_1 = self.encode0.weight primals_2 = self.encode0.bias primals_3 = self.encode1.weight primals_5 = self.encode1.bias primals_4 = self.decode0.weight primals_7 = self.decode0.bias primals_6 = self.decode1.weight primals_9 = self.decode1.bias primals_8 = input_0 primals_10 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10]) return output[0], output[1], output[2], output[3]
ckhui/cogdl
SDNE_layer
false
12,666
[ "MIT" ]
0
93bea17c2dc7084857cd0a4af8178c174965127c
https://github.com/ckhui/cogdl/tree/93bea17c2dc7084857cd0a4af8178c174965127c
LearnedPositionalEmbedding
import torch import torch.utils.data from torch import nn def create_position_ids_from_input_ids(input_ids, padding_idx): """ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. :param torch.Tensor x: :return torch.Tensor: """ mask = input_ids.ne(padding_idx).int() incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask return incremental_indices.long() + padding_idx class LearnedPositionalEmbedding(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. Padding ids are ignored by either offsetting based on padding_idx or by setting padding_idx to None and ensuring that the appropriate position ids are passed to the forward function. """ def __init__(self, num_embeddings: 'int', embedding_dim: 'int', padding_idx: 'int'): assert padding_idx is not None num_embeddings += padding_idx + 1 super().__init__(num_embeddings, embedding_dim, padding_idx=padding_idx ) def forward(self, input, use_cache=False): """Input is expected to be of size [bsz x seqlen].""" if use_cache: pos = int(self.padding_idx + input.size(1)) positions = input.data.new(1, 1).fill_(pos) else: positions = create_position_ids_from_input_ids(input, self. padding_idx) return super().forward(positions), positions def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_embeddings': 4, 'embedding_dim': 4, 'padding_idx': 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.utils.data 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_helper_fn_add0(arg0_0, arg1_0): tmp0 = arg0_0 + arg1_0 return tmp0 @triton.jit def triton_per_fused__to_copy_cumsum_ne_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 64 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) r2 = rindex x0 = xindex % 16 x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), xmask, other=0.0) tmp1 = 4.0 tmp2 = tmp0 != tmp1 tmp3 = tmp2.to(tl.int32) tmp4 = tmp3.to(tl.int64) tmp5 = tmp4.to(tl.int64) tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tmp7, = tl.associative_scan((tmp6,), 1, _triton_helper_fn_add0) tl.store(out_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp7, xmask) @triton.jit def triton_poi_fused__to_copy_add_mul_ne_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 x0 = xindex tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp2 = tl.load(in_ptr0 + x0, xmask) tmp1 = tmp0.to(tl.int32) tmp3 = 4.0 tmp4 = tmp2 != tmp3 tmp5 = tmp4.to(tl.int32) tmp6 = tmp1 * tmp5 tmp7 = tmp6.to(tl.int64) tmp8 = tl.full([1], 4, tl.int64) tmp9 = tmp7 + tmp8 tl.store(in_out_ptr0 + x0, tmp9, xmask) @triton.jit def triton_poi_fused_embedding_2(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 x1 = xindex // 4 x0 = xindex % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp1 = tl.full([XBLOCK], 9, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 9) | ~xmask, 'index out of bounds: 0 <= tmp4 < 9') tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask) tl.store(out_ptr0 + x2, tmp6, 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, (9, 4), (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.int64) get_raw_stream(0) triton_per_fused__to_copy_cumsum_ne_0[grid(64)](primals_1, buf0, 64, 4, XBLOCK=32, num_warps=2, num_stages=1) buf1 = buf0 del buf0 triton_poi_fused__to_copy_add_mul_ne_1[grid(256)](buf1, primals_1, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_poi_fused_embedding_2[grid(1024)](buf1, primals_2, buf2, 1024, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 return buf2, buf1, buf1 def create_position_ids_from_input_ids(input_ids, padding_idx): """ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. :param torch.Tensor x: :return torch.Tensor: """ mask = input_ids.ne(padding_idx).int() incremental_indices = torch.cumsum(mask, dim=1).type_as(mask) * mask return incremental_indices.long() + padding_idx class LearnedPositionalEmbeddingNew(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. Padding ids are ignored by either offsetting based on padding_idx or by setting padding_idx to None and ensuring that the appropriate position ids are passed to the forward function. """ def __init__(self, num_embeddings: 'int', embedding_dim: 'int', padding_idx: 'int'): assert padding_idx is not None num_embeddings += padding_idx + 1 super().__init__(num_embeddings, embedding_dim, padding_idx=padding_idx ) def forward(self, input_0): primals_2 = self.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0], output[1]
kev2513/gap-text2sql
LearnedPositionalEmbedding
false
12,667
[ "Apache-2.0" ]
0
67c4d6489ac44d4785a0cc1b836c889f00226f1d
https://github.com/kev2513/gap-text2sql/tree/67c4d6489ac44d4785a0cc1b836c889f00226f1d
CrossEntropyLoss
import torch import torch.utils.cpp_extension class CrossEntropyLoss(torch.nn.Module): def __init__(self): super(CrossEntropyLoss, self).__init__() self.ce_loss = torch.nn.CrossEntropyLoss() def forward(self, cls_output, label, **_): return self.ce_loss(cls_output, label).mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.utils.cpp_extension assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_div_mean_mul_neg_sum_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) 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 tmp22 = 1.0 tmp23 = tmp21 / tmp22 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp23, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused__log_softmax_div_mean_mul_neg_sum_1[grid(1)](buf2, buf0, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del buf0 return buf2, class CrossEntropyLossNew(torch.nn.Module): def __init__(self): super(CrossEntropyLossNew, self).__init__() self.ce_loss = torch.nn.CrossEntropyLoss() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
hugobloem/PyTorch-StudioGAN
CrossEntropyLoss
false
12,668
[ "MIT" ]
0
3deab27c0774adba5a94c7f452d32d4cbc3b117c
https://github.com/hugobloem/PyTorch-StudioGAN/tree/3deab27c0774adba5a94c7f452d32d4cbc3b117c
LSoftLoss
import torch import torch.nn.functional as F import torch.nn as nn class LSoftLoss(nn.Module): def __init__(self): super().__init__() def forward(self, y_pred, y_true, beta): with torch.no_grad(): y_true_updated = beta * y_true + (1 - beta) * y_pred return F.binary_cross_entropy(y_pred, y_true_updated, reduction='none') 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, 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_mul_rsub_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask) tmp5 = tl.load(in_ptr2 + x0, xmask) tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp3 - tmp0 tmp6 = tmp4 * tmp5 tmp7 = tmp2 + tmp6 tmp8 = tmp7 - tmp3 tmp9 = -tmp5 tmp10 = libdevice.log1p(tmp9) tmp11 = -100.0 tmp12 = triton_helpers.maximum(tmp10, tmp11) tmp13 = tmp8 * tmp12 tmp14 = tl_math.log(tmp5) tmp15 = triton_helpers.maximum(tmp14, tmp11) tmp16 = tmp7 * tmp15 tmp17 = tmp13 - tmp16 tl.store(out_ptr0 + x0, tmp17, xmask) 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, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_binary_cross_entropy_mul_rsub_0[grid(256)](arg0_1, arg1_1, arg2_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 del arg1_1 del arg2_1 return buf0, class LSoftLossNew(nn.Module): def __init__(self): super().__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]
khodwe56/kaggle-birdsong-recognition
LSoftLoss
false
12,669
[ "MIT" ]
0
95a902c37355619cf02558968f000038e487db47
https://github.com/khodwe56/kaggle-birdsong-recognition/tree/95a902c37355619cf02558968f000038e487db47
RNN
import torch import torch.nn as nn class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.i2h = nn.Linear(input_size + hidden_size, hidden_size) self.i2o = nn.Linear(input_size + hidden_size, output_size) def forward(self, input, hidden): combined = torch.cat((input, hidden), 1) hidden = self.i2h(combined) output = self.i2o(combined) return output, hidden def initHidden(self): return torch.zeros(1, self.hidden_size) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'input_size': 4, 'hidden_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 import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x1 = xindex // 8 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x2, tmp10, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 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, 8), (8, 1)) assert_size_stride(primals_6, (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 buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_6, buf0, reinterpret_tensor(primals_5, (8, 4), (1, 8), 0), alpha=1, beta=1, out=buf2) del primals_5 del primals_6 return buf2, buf1, buf0 class RNNNew(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNNNew, self).__init__() self.hidden_size = hidden_size self.i2h = nn.Linear(input_size + hidden_size, hidden_size) self.i2o = nn.Linear(input_size + hidden_size, output_size) def initHidden(self): return torch.zeros(1, self.hidden_size) def forward(self, input_0, input_1): primals_3 = self.i2h.weight primals_4 = self.i2h.bias primals_5 = self.i2o.weight primals_6 = self.i2o.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0], output[1]
khalilbalaree/Key-Smasher
RNN
false
12,670
[ "Apache-2.0" ]
0
981bb1fd9b91e9a693dba8b1cd4ee7ea82409d14
https://github.com/khalilbalaree/Key-Smasher/tree/981bb1fd9b91e9a693dba8b1cd4ee7ea82409d14
CDEFunc
import torch class CDEFunc(torch.nn.Module): def __init__(self, input_channels, hidden_channels): super(CDEFunc, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, 128) self.linear2 = torch.nn.Linear(128, input_channels * hidden_channels) def forward(self, z): z = self.linear1(z) z = z.relu() z = self.linear2(z) z = z.tanh() z = z.view(*z.shape[:-1], self.hidden_channels, self.input_channels) return z def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_channels': 4, 'hidden_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 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) @triton.jit def triton_poi_fused_tanh_tanh_backward_1(in_out_ptr0, 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 x0 = xindex % 16 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) tmp4 = tmp3 * tmp3 tmp5 = 1.0 tmp6 = tmp5 - tmp4 tl.store(in_out_ptr0 + x2, tmp3, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = 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, (16, 128), (128, 1)) assert_size_stride(primals_5, (16,), (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=256, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 128), (128, 1), 0), reinterpret_tensor(primals_4, (128, 16), (1, 128), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 16), (256, 64, 16, 1), 0) del buf2 buf4 = empty_strided_cuda((4, 4, 4, 16), (256, 64, 16, 1), torch. float32) triton_poi_fused_tanh_tanh_backward_1[grid(1024)](buf3, primals_5, buf4, 1024, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 return reinterpret_tensor(buf3, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 128), (128, 1), 0 ), buf4, primals_4, buf5 class CDEFuncNew(torch.nn.Module): def __init__(self, input_channels, hidden_channels): super(CDEFuncNew, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear(hidden_channels, 128) self.linear2 = torch.nn.Linear(128, input_channels * hidden_channels) def forward(self, input_0): primals_1 = self.linear1.weight primals_2 = self.linear1.bias primals_4 = self.linear2.weight primals_5 = self.linear2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
khaledsaab/NeuralCDE
CDEFunc
false
12,671
[ "Apache-2.0" ]
0
559d9d6fdb137afd14965725ea4845cf31e9235c
https://github.com/khaledsaab/NeuralCDE/tree/559d9d6fdb137afd14965725ea4845cf31e9235c
NegativeSampling
import torch import torch.nn as nn class NegativeSampling(nn.Module): """Negative sampling loss as proposed by T. Mikolov et al. in Distributed Representations of Words and Phrases and their Compositionality. """ def __init__(self): super(NegativeSampling, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, scores): """Computes the value of the loss function. Parameters ---------- scores: autograd.Variable of size (batch_size, num_noise_words + 1) Sparse unnormalized log probabilities. The first element in each row is the ground truth score (i.e. the target), other elements are scores of samples from the noise distribution. """ k = scores.size()[1] - 1 return -torch.sum(self._log_sigmoid(scores[:, 0]) + torch.sum(self. _log_sigmoid(-scores[:, 1:]), dim=1) / k) / scores.size()[0] def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, 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_div_log_sigmoid_forward_neg_sum_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp16 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp25 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp1 = 0.0 tmp2 = triton_helpers.minimum(tmp1, tmp0) tmp3 = tl_math.abs(tmp0) tmp4 = -tmp3 tmp5 = tl_math.exp(tmp4) tmp6 = libdevice.log1p(tmp5) tmp7 = tmp2 - tmp6 tmp9 = -tmp8 tmp10 = triton_helpers.minimum(tmp1, tmp9) tmp11 = tl_math.abs(tmp9) tmp12 = -tmp11 tmp13 = tl_math.exp(tmp12) tmp14 = libdevice.log1p(tmp13) tmp15 = tmp10 - tmp14 tmp17 = -tmp16 tmp18 = triton_helpers.minimum(tmp1, tmp17) tmp19 = tl_math.abs(tmp17) tmp20 = -tmp19 tmp21 = tl_math.exp(tmp20) tmp22 = libdevice.log1p(tmp21) tmp23 = tmp18 - tmp22 tmp24 = tmp15 + tmp23 tmp26 = -tmp25 tmp27 = triton_helpers.minimum(tmp1, tmp26) tmp28 = tl_math.abs(tmp26) tmp29 = -tmp28 tmp30 = tl_math.exp(tmp29) tmp31 = libdevice.log1p(tmp30) tmp32 = tmp27 - tmp31 tmp33 = tmp24 + tmp32 tmp34 = 0.3333333333333333 tmp35 = tmp33 * tmp34 tmp36 = tmp7 + tmp35 tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK]) tmp39 = tl.sum(tmp37, 1)[:, None] tmp40 = -tmp39 tmp41 = 0.25 tmp42 = tmp40 * tmp41 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp42, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 get_raw_stream(0) triton_per_fused_add_div_log_sigmoid_forward_neg_sum_0[grid(1)](buf2, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 return buf2, class NegativeSamplingNew(nn.Module): """Negative sampling loss as proposed by T. Mikolov et al. in Distributed Representations of Words and Phrases and their Compositionality. """ def __init__(self): super(NegativeSamplingNew, self).__init__() self._log_sigmoid = nn.LogSigmoid() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
kimoyerr/my-dataloader
NegativeSampling
false
12,672
[ "MIT" ]
0
a235e2f02d936df3f835b423dd015afa52e54066
https://github.com/kimoyerr/my-dataloader/tree/a235e2f02d936df3f835b423dd015afa52e54066
SpatialAttention2d
import torch import torch.nn as nn class SpatialAttention2d(nn.Module): def __init__(self, channel): super(SpatialAttention2d, self).__init__() self.squeeze = nn.Conv2d(channel, 1, kernel_size=1, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, x): z = self.squeeze(x) z = self.sigmoid(z) return x * z def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'channel': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_mul_sigmoid_0(in_ptr0, 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 = args args.clear() assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 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 = extern_kernels.convolution(primals_2, 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, 1, 4, 4), (16, 16, 4, 1)) buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_sigmoid_0[grid(256)](primals_2, buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf1, primals_1, primals_2, buf0 class SpatialAttention2dNew(nn.Module): def __init__(self, channel): super(SpatialAttention2dNew, self).__init__() self.squeeze = nn.Conv2d(channel, 1, kernel_size=1, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_1 = self.squeeze.weight primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
khodwe56/kaggle-birdsong-recognition
SpatialAttention2d
false
12,673
[ "MIT" ]
0
95a902c37355619cf02558968f000038e487db47
https://github.com/khodwe56/kaggle-birdsong-recognition/tree/95a902c37355619cf02558968f000038e487db47
AnswerModule
import torch import torch.nn as nn import torch.nn.init as init class AnswerModule(nn.Module): def __init__(self, vocab_size, hidden_size): super(AnswerModule, self).__init__() self.z = nn.Linear(2 * hidden_size, vocab_size) init.xavier_normal_(self.z.state_dict()['weight']) self.dropout = nn.Dropout(0.1) def forward(self, M, questions): M = self.dropout(M) concat = torch.cat([M, questions], dim=2).squeeze(1) z = self.z(concat) return z def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'vocab_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 import torch.nn as nn 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 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 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), (16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4, 8), (8, 1)) assert_size_stride(primals_4, (4,), (1,)) 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_1, primals_2, 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.addmm(primals_4, reinterpret_tensor(buf0, (16, 8), ( 8, 1), 0), reinterpret_tensor(primals_3, (8, 4), (1, 8), 0), alpha=1, beta=1, out=buf1) del primals_3 del primals_4 return reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(buf0, (16, 8), (8, 1), 0) class AnswerModuleNew(nn.Module): def __init__(self, vocab_size, hidden_size): super(AnswerModuleNew, self).__init__() self.z = nn.Linear(2 * hidden_size, vocab_size) init.xavier_normal_(self.z.state_dict()['weight']) self.dropout = nn.Dropout(0.1) def forward(self, input_0, input_1): primals_3 = self.z.weight primals_4 = self.z.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
kirubarajan/Dynamic-Memory-Network-Plus
AnswerModule
false
12,674
[ "Apache-2.0" ]
0
0613287ef5a959c7b260afcea2c31afcfb0ea189
https://github.com/kirubarajan/Dynamic-Memory-Network-Plus/tree/0613287ef5a959c7b260afcea2c31afcfb0ea189
BinaryClassifier
import torch import torch.nn.functional as F import torch.nn as nn import torch.utils.data class BinaryClassifier(nn.Module): """ Define a neural network that performs binary classification. The network should accept your number of features as input, and produce a single sigmoid value, that can be rounded to a label: 0 or 1, as output. Notes on training: To train a binary classifier in PyTorch, use BCELoss. BCELoss is binary cross entropy loss, documentation: https://pytorch.org/docs/stable/nn.html#torch.nn.BCELoss """ def __init__(self, input_features, hidden_dim, output_dim): """ Initialize model with setting up the linear layers. then make input parameters so define the layers of our model. :param input_features: make our number for input features in our training/test data :param hidden_dim: define number of the nodes in hidden layer(s) :param output_dim: number of the outputs we want to produce """ super(BinaryClassifier, self).__init__() self.fc1 = nn.Linear(input_features, hidden_dim) self.fc2 = nn.Linear(hidden_dim, int(hidden_dim // 2)) self.fc3 = nn.Linear(int(hidden_dim // 2), output_dim) self.drop = nn.Dropout(0.25) self.sig = nn.Sigmoid() def forward(self, x): """ displaythe forward pass for our model of the input features, x. :param x: the batch of the input features of the size (batch_size, input_features) :return: thesingle, sigmoid-activated value as the output """ x = F.relu(self.fc1(x)) x = self.drop(x) x = F.relu(self.fc2(x)) x = self.drop(x) x = self.sig(self.fc3(x)) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_features': 4, 'hidden_dim': 4, 'output_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 import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, 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 x0 = xindex % 2 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, 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, (2, 4), (4, 1)) assert_size_stride(primals_5, (2,), (1,)) assert_size_stride(primals_6, (4, 2), (2, 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 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, 2), (2, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 2), (1, 4), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 2), (32, 8, 2, 1), 0) del buf2 buf6 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(128)](buf3, primals_5, buf6, 128, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (64, 2), (2, 1), 0), reinterpret_tensor(primals_6, (2, 4), (1, 2), 0), out=buf4) buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf4 triton_poi_fused_sigmoid_2[grid(256)](buf5, primals_7, 256, XBLOCK= 128, num_warps=4, num_stages=1) del primals_7 return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor( buf3, (64, 2), (2, 1), 0), buf5, primals_6, buf6, primals_4, buf7 class BinaryClassifierNew(nn.Module): """ Define a neural network that performs binary classification. The network should accept your number of features as input, and produce a single sigmoid value, that can be rounded to a label: 0 or 1, as output. Notes on training: To train a binary classifier in PyTorch, use BCELoss. BCELoss is binary cross entropy loss, documentation: https://pytorch.org/docs/stable/nn.html#torch.nn.BCELoss """ def __init__(self, input_features, hidden_dim, output_dim): """ Initialize model with setting up the linear layers. then make input parameters so define the layers of our model. :param input_features: make our number for input features in our training/test data :param hidden_dim: define number of the nodes in hidden layer(s) :param output_dim: number of the outputs we want to produce """ super(BinaryClassifierNew, self).__init__() self.fc1 = nn.Linear(input_features, hidden_dim) self.fc2 = nn.Linear(hidden_dim, int(hidden_dim // 2)) self.fc3 = nn.Linear(int(hidden_dim // 2), output_dim) self.drop = nn.Dropout(0.25) self.sig = nn.Sigmoid() 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]
khadija267/Plagiarism-Detection
BinaryClassifier
false
12,675
[ "MIT" ]
0
90334167a8e6406e3f1ee178e616d6aa0094b1b5
https://github.com/khadija267/Plagiarism-Detection/tree/90334167a8e6406e3f1ee178e616d6aa0094b1b5
SCse
import torch import torch.nn as nn class SpatialAttention2d(nn.Module): def __init__(self, channel): super(SpatialAttention2d, self).__init__() self.squeeze = nn.Conv2d(channel, 1, kernel_size=1, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, x): z = self.squeeze(x) z = self.sigmoid(z) return x * z class GAB(nn.Module): def __init__(self, input_dim, reduction=4): super(GAB, self).__init__() self.global_avgpool = nn.AdaptiveAvgPool2d(1) self.conv1 = nn.Conv2d(input_dim, input_dim // reduction, kernel_size=1, stride=1) self.conv2 = nn.Conv2d(input_dim // reduction, input_dim, kernel_size=1, stride=1) self.relu = nn.ReLU(inplace=True) self.sigmoid = nn.Sigmoid() def forward(self, x): z = self.global_avgpool(x) z = self.relu(self.conv1(z)) z = self.sigmoid(self.conv2(z)) return x * z class SCse(nn.Module): def __init__(self, dim): super(SCse, self).__init__() self.satt = SpatialAttention2d(dim) self.catt = GAB(dim) def forward(self, x): return self.satt(x) + self.catt(x) def get_inputs(): return [torch.rand([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 import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp5 = 16.0 tmp6 = tmp4 / tmp5 tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 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 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp3 = tmp0 + tmp2 tmp4 = tl.full([1], 0, tl.int32) tmp5 = triton_helpers.maximum(tmp4, tmp3) tl.store(in_out_ptr0 + x0, tmp5, xmask) @triton.jit def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_add_mul_sigmoid_3(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 % 16 x2 = xindex // 64 x4 = xindex // 16 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp2 = tl.sigmoid(tmp1) tmp3 = tmp0 * tmp2 tmp5 = tl.sigmoid(tmp4) tmp6 = tmp0 * tmp5 tmp7 = tmp3 + tmp6 tl.store(out_ptr0 + x3, tmp7, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_4, (1,), (1,)) assert_size_stride(primals_5, (4, 1, 1, 1), (1, 1, 1, 1)) assert_size_stride(primals_6, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_2, 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, 1, 4, 4), (16, 16, 4, 1)) buf1 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32) buf2 = reinterpret_tensor(buf1, (4, 4, 1, 1), (4, 1, 1, 1), 0) del buf1 get_raw_stream(0) triton_per_fused_mean_0[grid(16)](buf2, primals_2, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) buf3 = extern_kernels.convolution(buf2, primals_3, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 1, 1, 1), (1, 1, 1, 1)) buf4 = buf3 del buf3 triton_poi_fused_convolution_relu_1[grid(4)](buf4, primals_4, 4, XBLOCK=4, num_warps=1, num_stages=1) del primals_4 buf5 = extern_kernels.convolution(buf4, primals_5, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 4, 1, 1), (4, 1, 1, 1)) buf6 = buf5 del buf5 triton_poi_fused_convolution_2[grid(16)](buf6, primals_6, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_6 buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_mul_sigmoid_3[grid(256)](primals_2, buf0, buf6, buf7, 256, XBLOCK=256, num_warps=4, num_stages=1) return (buf7, primals_1, primals_2, primals_3, primals_5, buf0, buf2, buf4, buf6) class SpatialAttention2d(nn.Module): def __init__(self, channel): super(SpatialAttention2d, self).__init__() self.squeeze = nn.Conv2d(channel, 1, kernel_size=1, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, x): z = self.squeeze(x) z = self.sigmoid(z) return x * z class GAB(nn.Module): def __init__(self, input_dim, reduction=4): super(GAB, self).__init__() self.global_avgpool = nn.AdaptiveAvgPool2d(1) self.conv1 = nn.Conv2d(input_dim, input_dim // reduction, kernel_size=1, stride=1) self.conv2 = nn.Conv2d(input_dim // reduction, input_dim, kernel_size=1, stride=1) self.relu = nn.ReLU(inplace=True) self.sigmoid = nn.Sigmoid() def forward(self, x): z = self.global_avgpool(x) z = self.relu(self.conv1(z)) z = self.sigmoid(self.conv2(z)) return x * z class SCseNew(nn.Module): def __init__(self, dim): super(SCseNew, self).__init__() self.satt = SpatialAttention2d(dim) self.catt = GAB(dim) def forward(self, input_0): primals_1 = self.satt.squeeze.weight primals_3 = self.catt.conv1.weight primals_4 = self.catt.conv1.bias primals_5 = self.catt.conv2.weight primals_6 = self.catt.conv2.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
khodwe56/kaggle-birdsong-recognition
SCse
false
12,676
[ "MIT" ]
0
95a902c37355619cf02558968f000038e487db47
https://github.com/khodwe56/kaggle-birdsong-recognition/tree/95a902c37355619cf02558968f000038e487db47
NN
import torch import torch.nn as nn class NN(nn.Module): def __init__(self, input_size, h1, h2, h3, num_output): super(NN, self).__init__() self.fc1 = nn.Linear(input_size, h1) self.fc2 = nn.Linear(h1, h2) self.fc3 = nn.Linear(h2, h3) self.fc4 = nn.Linear(h3, num_output) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.tanh(self.fc2(x)) x = torch.relu(self.fc3(x)) x = self.fc4(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_size': 4, 'h1': 4, 'h2': 4, 'h3': 4, 'num_output': 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_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = 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,)) assert_size_stride(primals_8, (4, 4), (4, 1)) assert_size_stride(primals_9, (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 buf8 = 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, buf8, 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_1[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.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4) buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf4 buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf5, primals_7, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_7 buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf6) del primals_9 return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0 ), buf3, reinterpret_tensor(buf5, (64, 4), (4, 1), 0 ), primals_8, buf7, primals_6, primals_4, buf8 class NNNew(nn.Module): def __init__(self, input_size, h1, h2, h3, num_output): super(NNNew, self).__init__() self.fc1 = nn.Linear(input_size, h1) self.fc2 = nn.Linear(h1, h2) self.fc3 = nn.Linear(h2, h3) self.fc4 = nn.Linear(h3, num_output) 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_8 = self.fc4.weight primals_9 = self.fc4.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9]) return output[0]
kgarg8/hypertune
NN
false
12,677
[ "MIT" ]
0
fbc4b87c9aefcd8449f6068232d7105975ff9dc9
https://github.com/kgarg8/hypertune/tree/fbc4b87c9aefcd8449f6068232d7105975ff9dc9
Clamp
import torch from torch import nn class Clamp(nn.Module): """Clamp energy output""" def forward(self, x): x = torch.clamp(x, min=0, max=30) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_clamp_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.0 tmp2 = triton_helpers.maximum(tmp0, tmp1) tmp3 = 30.0 tmp4 = triton_helpers.minimum(tmp2, tmp3) tl.store(out_ptr0 + x0, tmp4, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clamp_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class ClampNew(nn.Module): """Clamp energy output""" def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
kmiec96/mlhep-2021-baseline-track_1
Clamp
false
12,678
[ "Apache-2.0" ]
0
6fd2aa1529734204c522c49dba40fdc4b2bce353
https://github.com/kmiec96/mlhep-2021-baseline-track_1/tree/6fd2aa1529734204c522c49dba40fdc4b2bce353
NeuralNetwork
import torch import torch.nn as nn class NeuralNetwork(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, action_bound): super(NeuralNetwork, self).__init__() self.input_layer = nn.Linear(input_dim, hidden_dim) self.hidden_layer = nn.Linear(hidden_dim, hidden_dim) self.output_layer = nn.Linear(hidden_dim, output_dim) self.action_bound = action_bound def forward(self, inp): inp = torch.tensor(inp, dtype=torch.float) hidden = torch.relu(self.input_layer(inp)) hidden = torch.relu(self.hidden_layer(hidden)) action = torch.tanh(self.output_layer(hidden)) return self.action_bound * action def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_dim': 4, 'hidden_dim': 4, 'output_dim': 4, 'action_bound': 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_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_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, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0) del primals_2 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 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_3, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_3 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3, primals_5, buf6, 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=256, num_warps=4, num_stages=1) return buf5, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor( buf3, (64, 4), (4, 1), 0), buf4, primals_6, buf6, primals_4, buf7 class NeuralNetworkNew(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, action_bound): super(NeuralNetworkNew, self).__init__() self.input_layer = nn.Linear(input_dim, hidden_dim) self.hidden_layer = nn.Linear(hidden_dim, hidden_dim) self.output_layer = nn.Linear(hidden_dim, output_dim) self.action_bound = action_bound def forward(self, input_0): primals_2 = self.input_layer.weight primals_3 = self.input_layer.bias primals_4 = self.hidden_layer.weight primals_5 = self.hidden_layer.bias primals_6 = self.output_layer.weight primals_7 = self.output_layer.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
keyshor/homework
NeuralNetwork
false
12,679
[ "MIT" ]
0
687f9edf73bbac8fc492dfd82d634c19a38f5aab
https://github.com/keyshor/homework/tree/687f9edf73bbac8fc492dfd82d634c19a38f5aab
UpSample
import torch import torch.nn.functional as F import torch.nn as nn class UpSample(nn.Sequential): def __init__(self, skip_input, output_features): super(UpSample, self).__init__() self.convA = nn.Conv2d(skip_input, output_features, kernel_size=3, stride=1, padding=1) self.leakyreluA = nn.LeakyReLU(0.2) self.convB = nn.Conv2d(output_features, output_features, kernel_size=3, stride=1, padding=1) self.leakyreluB = nn.LeakyReLU(0.2) def forward(self, x, concat_with): up_x = F.interpolate(x, size=[concat_with.size(2), concat_with.size (3)], mode='bilinear', align_corners=True) return self.leakyreluB(self.convB(self.leakyreluA(self.convA(torch. cat([up_x, concat_with], dim=1))))) def get_inputs(): return [torch.rand([4, 3, 4, 4]), torch.rand([4, 1, 4, 4])] def get_init_inputs(): return [[], {'skip_input': 4, 'output_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 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__to_copy__unsafe_index_add_arange_clamp_mul_sub_0(in_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 4 x0 = xindex % 4 x2 = xindex // 16 x4 = xindex // 48 x7 = xindex % 48 tmp0 = x1 tmp1 = tmp0.to(tl.float32) tmp2 = 1.0 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 3, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tmp11 = x0 tmp12 = tmp11.to(tl.float32) tmp13 = tmp12 * tmp2 tmp14 = triton_helpers.maximum(tmp13, tmp4) tmp15 = tmp14.to(tl.int32) tmp16 = tl.load(in_ptr0 + (tmp15 + 4 * tmp10 + 16 * x2), xmask, eviction_policy='evict_last') tmp17 = tmp15 + tmp7 tmp18 = triton_helpers.minimum(tmp17, tmp9) tmp19 = tl.load(in_ptr0 + (tmp18 + 4 * tmp10 + 16 * x2), xmask, eviction_policy='evict_last') tmp20 = tmp19 - tmp16 tmp21 = tmp15.to(tl.float32) tmp22 = tmp14 - tmp21 tmp23 = triton_helpers.maximum(tmp22, tmp4) tmp24 = triton_helpers.minimum(tmp23, tmp2) tmp25 = tmp20 * tmp24 tmp26 = tmp16 + tmp25 tmp27 = tl.load(in_ptr0 + (tmp15 + 4 * tmp6 + 16 * x2), xmask, eviction_policy='evict_last') tmp28 = tl.load(in_ptr0 + (tmp18 + 4 * tmp6 + 16 * x2), xmask, eviction_policy='evict_last') tmp29 = tmp28 - tmp27 tmp30 = tmp29 * tmp24 tmp31 = tmp27 + tmp30 tmp32 = tmp26 - tmp31 tmp33 = tmp6.to(tl.float32) tmp34 = tmp5 - tmp33 tmp35 = triton_helpers.maximum(tmp34, tmp4) tmp36 = triton_helpers.minimum(tmp35, tmp2) tmp37 = tmp32 * tmp36 tmp38 = tmp31 + tmp37 tl.store(out_ptr1 + (x7 + 64 * x4), tmp38, xmask) @triton.jit def triton_poi_fused_cat_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 x0 = xindex % 16 x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + x2, xmask) tl.store(out_ptr0 + (x0 + 64 * x1), tmp0, xmask) @triton.jit def triton_poi_fused_convolution_leaky_relu_2(in_ptr0, in_ptr1, 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 x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.2 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(out_ptr0 + x3, tmp4, xmask) tl.store(out_ptr1 + x3, tmp7, 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, 1, 4, 4), (16, 16, 4, 1)) assert_size_stride(primals_2, (4, 3, 4, 4), (48, 16, 4, 1)) assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_6, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf1 = reinterpret_tensor(buf3, (4, 3, 4, 4), (64, 16, 4, 1), 0) get_raw_stream(0) triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_0[grid (192)](primals_2, buf1, 192, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = reinterpret_tensor(buf3, (4, 1, 4, 4), (64, 16, 4, 1), 48) triton_poi_fused_cat_1[grid(64)](primals_1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 buf4 = extern_kernels.convolution(buf3, primals_3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1)) 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_convolution_leaky_relu_2[grid(256)](buf4, primals_4, buf5, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_4 buf7 = extern_kernels.convolution(buf6, primals_5, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 4, 4, 4), (64, 16, 4, 1)) buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) buf9 = buf4 del buf4 triton_poi_fused_convolution_leaky_relu_2[grid(256)](buf7, primals_6, buf8, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf7 del primals_6 return buf9, primals_3, primals_5, buf3, buf5, buf6, buf8 class UpSampleNew(nn.Sequential): def __init__(self, skip_input, output_features): super(UpSampleNew, self).__init__() self.convA = nn.Conv2d(skip_input, output_features, kernel_size=3, stride=1, padding=1) self.leakyreluA = nn.LeakyReLU(0.2) self.convB = nn.Conv2d(output_features, output_features, kernel_size=3, stride=1, padding=1) self.leakyreluB = nn.LeakyReLU(0.2) def forward(self, input_0, input_1): primals_3 = self.convA.weight primals_4 = self.convA.bias primals_5 = self.convB.weight primals_6 = self.convB.bias primals_2 = input_0 primals_1 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
kimtaehyeong/msnnff
UpSample
false
12,680
[ "MIT" ]
0
75586be601bbdbfafcdf4038bc08f239e119b417
https://github.com/kimtaehyeong/msnnff/tree/75586be601bbdbfafcdf4038bc08f239e119b417
nn_model
import torch import torch.nn as nn import torch.nn.functional as F class nn_model(nn.Module): def __init__(self, feature_dim, num_classes): super(nn_model, self).__init__() self.l1 = nn.Linear(feature_dim, 1024) self.l2 = nn.Linear(1024, 1024) self.l3 = nn.Linear(1024, num_classes) def forward(self, x): x = F.relu(self.l1(x)) x = F.relu(self.l2(x)) x = self.l3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'feature_dim': 4, 'num_classes': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_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 % 1024 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, (1024, 4), (4, 1)) assert_size_stride(primals_2, (1024,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (1024, 1024), (1024, 1)) assert_size_stride(primals_5, (1024,), (1,)) assert_size_stride(primals_6, (4, 1024), (1024, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 1024), (1024, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1024), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 1024), (16384, 4096, 1024, 1), 0) del buf0 buf6 = empty_strided_cuda((4, 4, 4, 1024), (16384, 4096, 1024, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(65536)](buf1, primals_2, buf6, 65536, XBLOCK=512, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 1024), (1024, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 1024), (1024, 1), 0 ), reinterpret_tensor(primals_4, (1024, 1024), (1, 1024), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 1024), (16384, 4096, 1024, 1), 0) del buf2 buf5 = empty_strided_cuda((4, 4, 4, 1024), (16384, 4096, 1024, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(65536)](buf3, primals_5, buf5, 65536, XBLOCK=512, 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, 1024), (1024, 1), 0), reinterpret_tensor(primals_6, (1024, 4), (1, 1024), 0), alpha=1, beta=1, out=buf4) del primals_7 return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 1024), (1024, 1), 0 ), reinterpret_tensor(buf3, (64, 1024), (1024, 1), 0 ), primals_6, buf5, primals_4, buf6 class nn_modelNew(nn.Module): def __init__(self, feature_dim, num_classes): super(nn_modelNew, self).__init__() self.l1 = nn.Linear(feature_dim, 1024) self.l2 = nn.Linear(1024, 1024) self.l3 = nn.Linear(1024, num_classes) 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]
kiankd/quicksand
nn_model
false
12,681
[ "MIT" ]
0
20f9505c843eec00e423a0e1589ebd1e6264e174
https://github.com/kiankd/quicksand/tree/20f9505c843eec00e423a0e1589ebd1e6264e174
ConvMeanPool
import torch from torch import nn class MyConvo2d(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, he_init=True, stride=1, bias=True): super(MyConvo2d, self).__init__() self.he_init = he_init self.padding = int((kernel_size - 1) / 2) self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride=1, padding=self.padding, bias=bias) def forward(self, input): output = self.conv(input) return output class ConvMeanPool(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, he_init=True): super(ConvMeanPool, self).__init__() self.he_init = he_init self.conv = MyConvo2d(input_dim, output_dim, kernel_size, he_init= self.he_init) def forward(self, input): output = self.conv(input) output = (output[:, :, ::2, ::2] + output[:, :, 1::2, ::2] + output [:, :, ::2, 1::2] + output[:, :, 1::2, 1::2]) / 4 return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_dim': 4, 'output_dim': 4, 'kernel_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch 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_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 % 2 x1 = xindex // 2 % 2 x4 = xindex // 4 x2 = xindex // 4 % 4 x6 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 6 * x1 + 9 * x4), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (3 + 2 * x0 + 9 * x4), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (1 + 6 * x1 + 9 * x4), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (4 + 9 * x4), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp3 + tmp1 tmp5 = tmp2 + tmp4 tmp7 = tmp6 + tmp1 tmp8 = tmp5 + tmp7 tmp10 = tmp9 + tmp1 tmp11 = tmp8 + tmp10 tmp12 = 0.25 tmp13 = tmp11 * tmp12 tl.store(out_ptr0 + x6, tmp13, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 3, 3), (36, 9, 3, 1)) buf1 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_0[grid(64)](buf0, primals_2, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 del primals_2 return buf1, primals_1, primals_3 class MyConvo2d(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, he_init=True, stride=1, bias=True): super(MyConvo2d, self).__init__() self.he_init = he_init self.padding = int((kernel_size - 1) / 2) self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride=1, padding=self.padding, bias=bias) def forward(self, input): output = self.conv(input) return output class ConvMeanPoolNew(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, he_init=True): super(ConvMeanPoolNew, self).__init__() self.he_init = he_init self.conv = MyConvo2d(input_dim, output_dim, kernel_size, he_init= self.he_init) def forward(self, input_0): primals_1 = self.conv.conv.weight primals_2 = self.conv.conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
kolchinski/humanception-score
ConvMeanPool
false
12,682
[ "MIT" ]
0
da8880eec3be39574718409cfe8ca303f41c64e6
https://github.com/kolchinski/humanception-score/tree/da8880eec3be39574718409cfe8ca303f41c64e6
Generator
import torch import torch.nn as nn class Generator(nn.Module): def __init__(self, hidden_size, output_size): super(Generator, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.out = nn.Linear(hidden_size, output_size) self.sm = nn.LogSoftmax(dim=1) def forward(self, inputs): assert inputs.size(1) == self.hidden_size return self.sm(self.out(inputs)) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'hidden_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._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused__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_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') 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 = 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 tl.store(out_ptr0 + x3, tmp13, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_2 del primals_3 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)](buf0, buf1, 256, XBLOCK= 256, num_warps=4, num_stages=1) buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 triton_poi_fused__log_softmax_1[grid(256)](buf1, buf2, 256, XBLOCK= 256, num_warps=4, num_stages=1) del buf1 return buf2, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), buf2 class GeneratorNew(nn.Module): def __init__(self, hidden_size, output_size): super(GeneratorNew, self).__init__() self.hidden_size = hidden_size self.output_size = output_size self.out = nn.Linear(hidden_size, output_size) self.sm = nn.LogSoftmax(dim=1) def forward(self, input_0): primals_2 = self.out.weight primals_3 = self.out.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
kompotiks/Boris
Generator
false
12,683
[ "Apache-2.0" ]
0
2cf9487e4bc8d81206f819c0fe5c1d793d554062
https://github.com/kompotiks/Boris/tree/2cf9487e4bc8d81206f819c0fe5c1d793d554062
AttentionGRUCell
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init class AttentionGRUCell(nn.Module): def __init__(self, input_size, hidden_size): super(AttentionGRUCell, self).__init__() self.hidden_size = hidden_size self.Wr = nn.Linear(input_size, hidden_size) init.xavier_normal_(self.Wr.state_dict()['weight']) self.Ur = nn.Linear(hidden_size, hidden_size) init.xavier_normal_(self.Ur.state_dict()['weight']) self.W = nn.Linear(input_size, hidden_size) init.xavier_normal_(self.W.state_dict()['weight']) self.U = nn.Linear(hidden_size, hidden_size) init.xavier_normal_(self.U.state_dict()['weight']) def forward(self, fact, C, g): """ fact.size() -> (#batch, #hidden = #embedding) c.size() -> (#hidden, ) -> (#batch, #hidden = #embedding) r.size() -> (#batch, #hidden = #embedding) h_tilda.size() -> (#batch, #hidden = #embedding) g.size() -> (#batch, ) """ r = F.sigmoid(self.Wr(fact) + self.Ur(C)) h_tilda = F.tanh(self.W(fact) + r * self.U(C)) g = g.unsqueeze(1).expand_as(h_tilda) h = g * h_tilda + (1 - g) * C return h def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand( [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.triton_helpers import libdevice import torch.nn as nn 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_add_mul_rsub_sigmoid_tanh_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, 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 % 4 x2 = xindex % 16 x4 = xindex // 64 tmp0 = tl.load(in_out_ptr0 + x5, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + x5, xmask) tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr3 + (x2 + 16 * x4), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr4 + x5, xmask) tmp10 = tl.load(in_ptr5 + x5, xmask) tmp17 = tl.load(in_ptr6 + x5, xmask) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp7 = tl.sigmoid(tmp6) tmp11 = tmp7 * tmp10 tmp12 = tmp9 + tmp11 tmp13 = libdevice.tanh(tmp12) tmp14 = tmp8 * tmp13 tmp15 = 1.0 tmp16 = tmp15 - tmp8 tmp18 = tmp16 * tmp17 tmp19 = tmp14 + tmp18 tl.store(in_out_ptr0 + x5, tmp7, xmask) tl.store(out_ptr0 + x5, tmp19, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_7, (4, 4), (4, 1)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (4, 4), (4, 1)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (4, 4, 4), (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.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 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) del primals_4 buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_8, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf3) del primals_7 del primals_8 buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_10, reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), reinterpret_tensor(primals_9, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf4) del primals_10 del primals_9 buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_rsub_sigmoid_tanh_0[grid(256)](buf2, primals_2, buf1, primals_5, primals_11, buf3, buf4, primals_6, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf1 del primals_2 del primals_5 return buf5, primals_11, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), buf2, buf3, buf4 class AttentionGRUCellNew(nn.Module): def __init__(self, input_size, hidden_size): super(AttentionGRUCellNew, self).__init__() self.hidden_size = hidden_size self.Wr = nn.Linear(input_size, hidden_size) init.xavier_normal_(self.Wr.state_dict()['weight']) self.Ur = nn.Linear(hidden_size, hidden_size) init.xavier_normal_(self.Ur.state_dict()['weight']) self.W = nn.Linear(input_size, hidden_size) init.xavier_normal_(self.W.state_dict()['weight']) self.U = nn.Linear(hidden_size, hidden_size) init.xavier_normal_(self.U.state_dict()['weight']) def forward(self, input_0, input_1, input_2): primals_1 = self.Wr.weight primals_2 = self.Wr.bias primals_4 = self.Ur.weight primals_5 = self.Ur.bias primals_7 = self.W.weight primals_8 = self.W.bias primals_9 = self.U.weight primals_10 = self.U.bias primals_3 = input_0 primals_6 = input_1 primals_11 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11]) return output[0]
kirubarajan/Dynamic-Memory-Network-Plus
AttentionGRUCell
false
12,684
[ "Apache-2.0" ]
0
0613287ef5a959c7b260afcea2c31afcfb0ea189
https://github.com/kirubarajan/Dynamic-Memory-Network-Plus/tree/0613287ef5a959c7b260afcea2c31afcfb0ea189
FocalLoss
import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda import torch.distributed import torch.multiprocessing class FocalLoss(nn.Module): """Focal Loss - https://arxiv.org/abs/1708.02002""" def __init__(self, alpha=0.25, gamma=2): super().__init__() self.alpha = alpha self.gamma = gamma def forward(self, pred_logits, target): pred = pred_logits.sigmoid() ce = F.binary_cross_entropy_with_logits(pred_logits, target, reduction='none') alpha = target * self.alpha + (1.0 - target) * (1.0 - self.alpha) pt = torch.where(target == 1, pred, 1 - pred) return alpha * (1.0 - pt) ** self.gamma * ce 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 import torch.cuda import torch.distributed 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_add_binary_cross_entropy_with_logits_eq_mul_pow_rsub_sigmoid_where_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) tmp9 = 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 tmp8 = tmp0 == tmp3 tmp10 = tl.sigmoid(tmp9) tmp11 = tmp3 - tmp10 tmp12 = tl.where(tmp8, tmp10, tmp11) tmp13 = tmp3 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tmp7 * tmp14 tmp16 = tmp4 * tmp9 tmp17 = 0.0 tmp18 = triton_helpers.minimum(tmp17, tmp9) tmp19 = tl_math.abs(tmp9) tmp20 = -tmp19 tmp21 = tl_math.exp(tmp20) tmp22 = libdevice.log1p(tmp21) tmp23 = tmp18 - tmp22 tmp24 = tmp16 - tmp23 tmp25 = tmp15 * tmp24 tl.store(out_ptr0 + x0, tmp25, 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_eq_mul_pow_rsub_sigmoid_where_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): """Focal Loss - https://arxiv.org/abs/1708.02002""" def __init__(self, alpha=0.25, gamma=2): super().__init__() self.alpha = alpha 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]
krisk84/retinanet-examples
FocalLoss
false
12,685
[ "BSD-3-Clause" ]
0
174d95f3aabe1746d105c66f87aa445607f4eab8
https://github.com/krisk84/retinanet-examples/tree/174d95f3aabe1746d105c66f87aa445607f4eab8
GlobalAveragePooling
import torch import torch.nn as nn import torch.nn.parallel import torch.optim import torch.nn.functional as F class GlobalAveragePooling(nn.Module): def __init__(self): super(GlobalAveragePooling, self).__init__() def forward(self, feat): num_channels = feat.size(1) return F.avg_pool2d(feat, (feat.size(2), feat.size(3))).view(-1, num_channels) 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.nn.parallel import torch.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_avg_pool2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp7 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp9 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp11 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp13 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp15 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp17 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp21 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp25 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp27 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp29 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp8 = tmp7 + tmp6 tmp10 = tmp9 + tmp8 tmp12 = tmp11 + tmp10 tmp14 = tmp13 + tmp12 tmp16 = tmp15 + tmp14 tmp18 = tmp17 + tmp16 tmp20 = tmp19 + tmp18 tmp22 = tmp21 + tmp20 tmp24 = tmp23 + tmp22 tmp26 = tmp25 + tmp24 tmp28 = tmp27 + tmp26 tmp30 = tmp29 + tmp28 tmp31 = 0.0625 tmp32 = tmp30 * tmp31 tl.store(out_ptr0 + x0, tmp32, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_avg_pool2d_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 4), (4, 1), 0), class GlobalAveragePoolingNew(nn.Module): def __init__(self): super(GlobalAveragePoolingNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
kristinakupf/FeatureLearningRotNet
GlobalAveragePooling
false
12,686
[ "MIT" ]
0
d495bcfaed3e7a3ca92b7434f8ad6d7584ab173d
https://github.com/kristinakupf/FeatureLearningRotNet/tree/d495bcfaed3e7a3ca92b7434f8ad6d7584ab173d
KLDLoss
import torch import torch.nn as nn import torch.utils.data class KLDLoss(nn.Module): def forward(self, mu, logvar): return -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) 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 import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_exp_mul_pow_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) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 1.0 tmp2 = tmp0 + tmp1 tmp4 = tmp3 * tmp3 tmp5 = tmp2 - tmp4 tmp6 = tl_math.exp(tmp0) tmp7 = tmp5 - tmp6 tmp8 = tl.broadcast_to(tmp7, [RBLOCK]) tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0)) tmp11 = -0.5 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_add_exp_mul_pow_sub_sum_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 KLDLossNew(nn.Module): def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
kudoNCT/michigan_copy
KLDLoss
false
12,687
[ "MIT" ]
0
e857b96a65b270ef2506cb9866b7e01f117c4396
https://github.com/kudoNCT/michigan_copy/tree/e857b96a65b270ef2506cb9866b7e01f117c4396
GatedMaskedConv2d
import torch import torch.utils.data from torch import nn import torch.nn.functional as F class GatedMaskedConv2d(nn.Module): def __init__(self, in_dim, out_dim=None, kernel_size=3, mask='B'): super(GatedMaskedConv2d, self).__init__() if out_dim is None: out_dim = in_dim self.dim = out_dim self.size = kernel_size self.mask = mask pad = self.size // 2 self.v_conv = nn.Conv2d(in_dim, 2 * self.dim, kernel_size=(pad + 1, self.size)) self.v_pad1 = nn.ConstantPad2d((pad, pad, pad, 0), 0) self.v_pad2 = nn.ConstantPad2d((0, 0, 1, 0), 0) self.vh_conv = nn.Conv2d(2 * self.dim, 2 * self.dim, kernel_size=1) self.h_conv = nn.Conv2d(in_dim, 2 * self.dim, kernel_size=(1, pad + 1)) self.h_pad1 = nn.ConstantPad2d((self.size // 2, 0, 0, 0), 0) self.h_pad2 = nn.ConstantPad2d((1, 0, 0, 0), 0) self.h_conv_res = nn.Conv2d(self.dim, self.dim, 1) def forward(self, v_map, h_map): v_out = self.v_pad2(self.v_conv(self.v_pad1(v_map)))[:, :, :-1, :] v_map_out = F.tanh(v_out[:, :self.dim]) * F.sigmoid(v_out[:, self.dim:] ) vh = self.vh_conv(v_out) h_out = self.h_conv(self.h_pad1(h_map)) if self.mask == 'A': h_out = self.h_pad2(h_out)[:, :, :, :-1] h_out = h_out + vh h_out = F.tanh(h_out[:, :self.dim]) * F.sigmoid(h_out[:, self.dim:]) h_map_out = self.h_conv_res(h_out) if self.mask == 'B': h_map_out = h_map_out + h_map return v_map_out, h_map_out def get_inputs(): return [torch.rand([4, 4, 4, 4]), 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.triton_helpers import libdevice import torch.utils.data 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_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 480 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 6 % 5 x0 = xindex % 6 x2 = xindex // 30 x4 = xindex tmp0 = -1 + x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = -1 + x0 tmp4 = tmp3 >= tmp1 tmp5 = tl.full([1], 4, tl.int64) tmp6 = tmp3 < tmp5 tmp7 = tmp2 & tmp4 tmp8 = tmp7 & tmp6 tmp9 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp8 & xmask, other=0.0) tl.store(out_ptr0 + x4, tmp9, xmask) @triton.jit def triton_poi_fused_constant_pad_nd_convolution_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 640 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 5 x4 = xindex // 20 x5 = xindex % 20 x2 = xindex // 20 % 8 x6 = xindex tmp0 = -1 + x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.load(in_ptr0 + (-4 + x5 + 16 * x4), tmp2 & xmask, other=0.0) tmp4 = tl.load(in_ptr1 + x2, tmp2 & xmask, eviction_policy='evict_last', other=0.0) tmp5 = tmp3 + tmp4 tmp6 = tl.full(tmp5.shape, 0.0, tmp5.dtype) tmp7 = tl.where(tmp2, tmp5, tmp6) tl.store(out_ptr0 + x6, tmp7, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_tanh_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 % 16 x1 = xindex // 16 % 4 x2 = xindex // 64 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 20 * x1 + 160 * x2), xmask) tmp2 = tl.load(in_ptr0 + (80 + x0 + 20 * x1 + 160 * x2), xmask) tmp1 = libdevice.tanh(tmp0) tmp3 = tl.sigmoid(tmp2) tmp4 = tmp1 * tmp3 tl.store(out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_constant_pad_nd_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 320 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 5 x1 = xindex // 5 x2 = xindex tmp0 = -1 + x0 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1), tmp2 & xmask, other=0.0) tl.store(out_ptr0 + x2, tmp3, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_tanh_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex // 64 x4 = xindex % 64 x1 = xindex // 16 % 4 x3 = xindex tmp0 = tl.load(in_ptr0 + (x4 + 128 * x2), xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + (x4 + 128 * x2), xmask) tmp4 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (64 + x4 + 128 * x2), xmask) tmp9 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr2 + (64 + x4 + 128 * x2), xmask) tmp12 = tl.load(in_ptr3 + (4 + x1), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp7 = libdevice.tanh(tmp6) tmp10 = tmp8 + tmp9 tmp13 = tmp11 + tmp12 tmp14 = tmp10 + tmp13 tmp15 = tl.sigmoid(tmp14) tmp16 = tmp7 * tmp15 tl.store(out_ptr0 + x3, tmp7, xmask) tl.store(out_ptr1 + x3, tmp15, xmask) tl.store(out_ptr2 + x3, tmp16, xmask) @triton.jit def triton_poi_fused_add_convolution_5(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) = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (8, 4, 2, 3), (24, 6, 3, 1)) assert_size_stride(primals_3, (8,), (1,)) assert_size_stride(primals_4, (8, 8, 1, 1), (8, 1, 1, 1)) assert_size_stride(primals_5, (8,), (1,)) assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_7, (8, 4, 1, 2), (8, 2, 2, 1)) assert_size_stride(primals_8, (8,), (1,)) assert_size_stride(primals_9, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_10, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 5, 6), (120, 30, 6, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(480)](primals_1, buf0, 480, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 8, 4, 4), (128, 16, 4, 1)) buf2 = empty_strided_cuda((4, 8, 5, 4), (160, 20, 4, 1), torch.float32) triton_poi_fused_constant_pad_nd_convolution_1[grid(640)](buf1, primals_3, buf2, 640, XBLOCK=128, num_warps=4, num_stages=1) del buf1 del primals_3 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_sigmoid_tanh_2[grid(256)](buf2, buf3, 256, XBLOCK=128, num_warps=4, num_stages=1) buf4 = extern_kernels.convolution(reinterpret_tensor(buf2, (4, 8, 4, 4), (160, 20, 4, 1), 0), primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 8, 4, 4), (128, 16, 4, 1)) buf5 = empty_strided_cuda((4, 4, 4, 5), (80, 20, 5, 1), torch.float32) triton_poi_fused_constant_pad_nd_3[grid(320)](primals_6, buf5, 320, XBLOCK=256, num_warps=4, num_stages=1) buf6 = extern_kernels.convolution(buf5, primals_7, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 8, 4, 4), (128, 16, 4, 1)) buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_sigmoid_tanh_4[grid(256)](buf6, primals_8, buf4, primals_5, buf7, buf8, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf4 del buf6 del primals_5 del primals_8 buf10 = extern_kernels.convolution(buf9, primals_9, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 4, 4, 4), (64, 16, 4, 1)) buf11 = buf10 del buf10 triton_poi_fused_add_convolution_5[grid(256)](buf11, primals_10, primals_6, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_10 del primals_6 return (buf3, buf11, primals_2, primals_4, primals_7, primals_9, buf0, reinterpret_tensor(buf2, (4, 8, 4, 4), (160, 20, 4, 1), 0), buf5, buf7, buf8, buf9) class GatedMaskedConv2dNew(nn.Module): def __init__(self, in_dim, out_dim=None, kernel_size=3, mask='B'): super(GatedMaskedConv2dNew, self).__init__() if out_dim is None: out_dim = in_dim self.dim = out_dim self.size = kernel_size self.mask = mask pad = self.size // 2 self.v_conv = nn.Conv2d(in_dim, 2 * self.dim, kernel_size=(pad + 1, self.size)) self.v_pad1 = nn.ConstantPad2d((pad, pad, pad, 0), 0) self.v_pad2 = nn.ConstantPad2d((0, 0, 1, 0), 0) self.vh_conv = nn.Conv2d(2 * self.dim, 2 * self.dim, kernel_size=1) self.h_conv = nn.Conv2d(in_dim, 2 * self.dim, kernel_size=(1, pad + 1)) self.h_pad1 = nn.ConstantPad2d((self.size // 2, 0, 0, 0), 0) self.h_pad2 = nn.ConstantPad2d((1, 0, 0, 0), 0) self.h_conv_res = nn.Conv2d(self.dim, self.dim, 1) def forward(self, input_0, input_1): primals_2 = self.v_conv.weight primals_3 = self.v_conv.bias primals_4 = self.vh_conv.weight primals_5 = self.vh_conv.bias primals_7 = self.h_conv.weight primals_8 = self.h_conv.bias primals_9 = self.h_conv_res.weight primals_10 = self.h_conv_res.bias primals_1 = input_0 primals_6 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10]) return output[0], output[1]
kj141/vae-lagging-encoder
GatedMaskedConv2d
false
12,688
[ "MIT" ]
0
79dda8baed0129bc8234b7602332a54210164fbc
https://github.com/kj141/vae-lagging-encoder/tree/79dda8baed0129bc8234b7602332a54210164fbc
DuelingDQN
import torch import torch.nn.functional as F import torch.nn as nn class DuelingDQN(nn.Module): def __init__(self, state_size, action_size, seed): super(DuelingDQN, self).__init__() torch.manual_seed(seed) self.state_size = state_size self.action_size = action_size self.fc1 = nn.Linear(state_size, 128) self.fc2 = nn.Linear(128, 128) self.value_fc1 = nn.Linear(128, 32) self.value_activation = nn.Linear(32, 1) self.advantage_fc1 = nn.Linear(128, 32) self.advantage_activation = nn.Linear(32, action_size) def forward(self, state): x = F.relu(self.fc1(state)) x = F.relu(self.fc2(x)) v = F.relu(self.value_fc1(x)) v = self.value_activation(v).expand(x.size(0), self.action_size) a = F.relu(self.advantage_fc1(x)) a = self.advantage_activation(a) x = v + a - a.mean(1).unsqueeze(1).expand(x.size(0), self.action_size) return x def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'state_size': 4, 'action_size': 4, 'seed': 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_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 128 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, 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 % 32 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_add_sub_2(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 x2 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp4 = tl.load(in_ptr2 + x2, xmask) tmp6 = tl.load(in_ptr2 + 4 * x1, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr2 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr2 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr2 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp3 = tmp0 + tmp2 tmp5 = tmp3 + tmp4 tmp8 = tmp6 + tmp7 tmp10 = tmp8 + tmp9 tmp12 = tmp10 + tmp11 tmp13 = 4.0 tmp14 = tmp12 / tmp13 tmp15 = tmp5 - tmp14 tl.store(out_ptr0 + x2, tmp15, 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, (128, 4), (4, 1)) assert_size_stride(primals_2, (128,), (1,)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (128, 128), (128, 1)) assert_size_stride(primals_5, (128,), (1,)) assert_size_stride(primals_6, (32, 128), (128, 1)) assert_size_stride(primals_7, (32,), (1,)) assert_size_stride(primals_8, (1, 32), (32, 1)) assert_size_stride(primals_9, (1,), (1,)) assert_size_stride(primals_10, (32, 128), (128, 1)) assert_size_stride(primals_11, (32,), (1,)) assert_size_stride(primals_12, (4, 32), (32, 1)) assert_size_stride(primals_13, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 128), (128, 1), torch.float32) extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 128), (1, 4), 0), out=buf0) del primals_1 buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_relu_0[grid(512)](buf1, primals_2, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((4, 128), (128, 1), torch.float32) extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (128, 128), ( 1, 128), 0), out=buf2) buf3 = buf2 del buf2 triton_poi_fused_relu_0[grid(512)](buf3, primals_5, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((4, 32), (32, 1), torch.float32) extern_kernels.mm(buf3, reinterpret_tensor(primals_6, (128, 32), (1, 128), 0), out=buf4) buf5 = buf4 del buf4 triton_poi_fused_relu_1[grid(128)](buf5, primals_7, 128, XBLOCK=128, num_warps=4, num_stages=1) del primals_7 buf6 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.mm(buf5, reinterpret_tensor(primals_8, (32, 1), (1, 32), 0), out=buf6) buf7 = empty_strided_cuda((4, 32), (32, 1), torch.float32) extern_kernels.mm(buf3, reinterpret_tensor(primals_10, (128, 32), ( 1, 128), 0), out=buf7) buf8 = buf7 del buf7 triton_poi_fused_relu_1[grid(128)](buf8, primals_11, 128, XBLOCK= 128, num_warps=4, num_stages=1) del primals_11 buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_13, buf8, reinterpret_tensor( primals_12, (32, 4), (1, 32), 0), alpha=1, beta=1, out=buf9) del primals_13 buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_add_sub_2[grid(16)](buf6, primals_9, buf9, buf10, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf6 del buf9 del primals_9 return (buf10, primals_3, buf1, buf3, buf5, buf8, primals_12, primals_10, primals_8, primals_6, primals_4) class DuelingDQNNew(nn.Module): def __init__(self, state_size, action_size, seed): super(DuelingDQNNew, self).__init__() torch.manual_seed(seed) self.state_size = state_size self.action_size = action_size self.fc1 = nn.Linear(state_size, 128) self.fc2 = nn.Linear(128, 128) self.value_fc1 = nn.Linear(128, 32) self.value_activation = nn.Linear(32, 1) self.advantage_fc1 = nn.Linear(128, 32) self.advantage_activation = nn.Linear(32, action_size) 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.value_fc1.weight primals_7 = self.value_fc1.bias primals_8 = self.value_activation.weight primals_9 = self.value_activation.bias primals_10 = self.advantage_fc1.weight primals_11 = self.advantage_fc1.bias primals_12 = self.advantage_activation.weight primals_13 = self.advantage_activation.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]) return output[0]
kscharpf/drlnd_p1_navigation
DuelingDQN
false
12,689
[ "MIT" ]
0
7f5e2aebcabb9d94c45a2fa7e9e8baec5c4b7a00
https://github.com/kscharpf/drlnd_p1_navigation/tree/7f5e2aebcabb9d94c45a2fa7e9e8baec5c4b7a00
SmoothL1Loss
import torch import torch.nn as nn import torch.cuda import torch.distributed import torch.multiprocessing class SmoothL1Loss(nn.Module): """Smooth L1 Loss""" def __init__(self, beta=0.11): super().__init__() self.beta = beta def forward(self, pred, target): x = (pred - target).abs() l1 = x - 0.5 * self.beta l2 = 0.5 * x ** 2 / self.beta return torch.where(x >= self.beta, l1, l2) 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 import torch.nn as nn import torch.cuda import torch.distributed 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_abs_div_ge_mul_pow_sub_where_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) tmp1 = tl.load(in_ptr1 + x0, xmask) tmp2 = tmp0 - tmp1 tmp3 = tl_math.abs(tmp2) tmp4 = 0.11 tmp5 = tmp3 >= tmp4 tmp6 = 0.055 tmp7 = tmp3 - tmp6 tmp8 = tmp3 * tmp3 tmp9 = 0.5 tmp10 = tmp8 * tmp9 tmp11 = 9.090909090909092 tmp12 = tmp10 * tmp11 tmp13 = tl.where(tmp5, tmp7, tmp12) tl.store(out_ptr0 + x0, tmp13, 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_abs_div_ge_mul_pow_sub_where_0[grid(256)](arg0_1, arg1_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del arg1_1 return buf0, class SmoothL1LossNew(nn.Module): """Smooth L1 Loss""" def __init__(self, beta=0.11): super().__init__() self.beta = beta def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
krisk84/retinanet-examples
SmoothL1Loss
false
12,690
[ "BSD-3-Clause" ]
0
174d95f3aabe1746d105c66f87aa445607f4eab8
https://github.com/krisk84/retinanet-examples/tree/174d95f3aabe1746d105c66f87aa445607f4eab8
GELU
import torch import torch.nn as nn from torch.nn import functional as F class GELU(nn.Module): def forward(self, input): return F.gelu(input) 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_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): 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_gelu_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class GELUNew(nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
kwonyos/decision-transformer
GELU
false
12,691
[ "MIT" ]
0
c3ad7df28a897a016dd24c5337cb871d1f33f456
https://github.com/kwonyos/decision-transformer/tree/c3ad7df28a897a016dd24c5337cb871d1f33f456
WeightedFeatureFusion
import torch import torch.nn as nn import torch.utils.data class WeightedFeatureFusion(nn.Module): def __init__(self, layers, weight=False): super(WeightedFeatureFusion, self).__init__() self.layers = layers self.weight = weight self.n = len(layers) + 1 if weight: self.w = nn.Parameter(torch.zeros(self.n), requires_grad=True) def forward(self, x, outputs): if self.weight: w = torch.sigmoid(self.w) * (2 / self.n) x = x * w[0] nx = x.shape[1] for i in range(self.n - 1): a = outputs[self.layers[i]] * w[i + 1] if self.weight else outputs[ self.layers[i]] na = a.shape[1] if nx == na: x = x + a elif nx > na: x[:, :na] = x[:, :na] + a else: x = x + a[:, :nx] return x def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([5, 4, 4, 4])] def get_init_inputs(): return [[], {'layers': [4, 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 @triton.jit def triton_poi_fused_add_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 x0 = xindex % 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + (256 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tmp2 + tmp1 tl.store(out_ptr0 + x2, tmp3, 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, (5, 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_0[grid(256)](arg0_1, arg1_1, buf0, 256, XBLOCK =128, num_warps=4, num_stages=1) del arg0_1 del arg1_1 return buf0, class WeightedFeatureFusionNew(nn.Module): def __init__(self, layers, weight=False): super(WeightedFeatureFusionNew, self).__init__() self.layers = layers self.weight = weight self.n = len(layers) + 1 if weight: self.w = nn.Parameter(torch.zeros(self.n), requires_grad=True) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
ks1320/Traffic-Surveillance-System
WeightedFeatureFusion
false
12,692
[ "MIT" ]
0
fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
https://github.com/ks1320/Traffic-Surveillance-System/tree/fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
Reorg
import torch import torch.nn as nn import torch.utils.data class Reorg(nn.Module): def forward(self, x): return torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 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_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex // 4 % 16 x0 = xindex % 2 x1 = xindex // 2 % 2 x3 = xindex // 64 x4 = xindex tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2 + 64 * x3), 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_ptr0 + (4 + 2 * x0 + 8 * x1 + 16 * (-4 + x2) + 64 * x3), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1 + 16 * (-8 + x2) + 64 * x3), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1], 16, tl.int64) tmp19 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1 + 16 * (-12 + x2) + 64 * x3), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp20 = tl.where(tmp14, tmp15, tmp19) tmp21 = tl.where(tmp9, tmp10, tmp20) tmp22 = tl.where(tmp4, tmp5, tmp21) tl.store(out_ptr0 + x4, tmp22, 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, 16, 2, 2), (64, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class ReorgNew(nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
ks1320/Traffic-Surveillance-System
Reorg
false
12,693
[ "MIT" ]
0
fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
https://github.com/ks1320/Traffic-Surveillance-System/tree/fa1eb2a3a3d494c798fa2eeb0528ef48b1978332
GCN
import torch import torch.nn as nn import torch.nn.functional as F class GCN(nn.Module): def __init__(self, dim_nd, dim_ft, dim_hd, dim_ot, drop_rate=0.5): super(GCN, self).__init__() self.lin1 = nn.Linear(dim_ft, dim_hd) self.lin2 = nn.Linear(dim_hd, dim_ot) self.act1 = F.relu self.act2 = nn.Softmax self.drop1 = nn.Dropout(p=drop_rate) self.drop2 = nn.Dropout(p=drop_rate) def forward(self, A, X): temp = self.drop1(X) temp = torch.sparse.mm(A, temp) temp = self.lin1(temp) temp = self.act1(temp) temp = self.drop2(temp) temp = torch.sparse.mm(A, temp) temp = self.lin2(temp) output = temp return output def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'dim_nd': 4, 'dim_ft': 4, 'dim_hd': 4, 'dim_ot': 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_zeros_0(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 = 0.0 tl.store(out_ptr0 + x0, tmp0, 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 x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = 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,), (1,)) assert_size_stride(primals_5, (4, 4), (4, 1)) assert_size_stride(primals_6, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_zeros_0[grid(16)](buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = torch.ops.aten._sparse_addmm.default(reinterpret_tensor(buf0, (4, 4), (1, 4), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4 ), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), beta=0) del primals_1 buf2 = buf1 del buf1 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf2, (4, 4), (1, 4), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf3) del primals_3 buf4 = buf3 del buf3 buf8 = empty_strided_cuda((4, 4), (4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(16)](buf4, primals_4, buf8, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_4 buf5 = torch.ops.aten._sparse_addmm.default(reinterpret_tensor(buf0, (4, 4), (1, 4), 0), reinterpret_tensor(buf4, (4, 4), (1, 4), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), beta=0) del buf0 buf6 = buf5 del buf5 buf7 = buf4 del buf4 extern_kernels.addmm(primals_6, reinterpret_tensor(buf6, (4, 4), (1, 4), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), alpha =1, beta=1, out=buf7) del primals_6 return buf7, reinterpret_tensor(buf2, (4, 4), (1, 4), 0 ), reinterpret_tensor(buf6, (4, 4), (1, 4), 0), reinterpret_tensor( primals_5, (4, 4), (1, 4), 0), primals_2, buf8 class GCNNew(nn.Module): def __init__(self, dim_nd, dim_ft, dim_hd, dim_ot, drop_rate=0.5): super(GCNNew, self).__init__() self.lin1 = nn.Linear(dim_ft, dim_hd) self.lin2 = nn.Linear(dim_hd, dim_ot) self.act1 = F.relu self.act2 = nn.Softmax self.drop1 = nn.Dropout(p=drop_rate) self.drop2 = nn.Dropout(p=drop_rate) def forward(self, input_0, input_1): primals_1 = self.lin1.weight primals_4 = self.lin1.bias primals_2 = self.lin2.weight primals_6 = self.lin2.bias primals_3 = input_0 primals_5 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
lanseyege/Graph
GCN
false
12,694
[ "MIT" ]
0
ec94502ea59d2b68de095d8160f37aa22d26f8cb
https://github.com/lanseyege/Graph/tree/ec94502ea59d2b68de095d8160f37aa22d26f8cb
DQN
import torch import torch.nn.functional as F import torch.nn as nn class DQN(nn.Module): """Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure. """ def __init__(self, gamma, ddqn=False, in_channels=4, num_actions=4): """ Parameters: ----------- in_channels: number of channel of input. i.e The number of most recent frames stacked together, here we use 4 frames, which means each state in Breakout is composed of 4 frames. num_actions: number of action-value to output, one-to-one correspondence to action in game. You can add additional arguments as you need. In the constructor we instantiate modules and assign them as member variables. """ super(DQN, self).__init__() self.gamma = gamma self.ddqn = ddqn self.in_channels = in_channels self.num_actions = num_actions self.pool = nn.MaxPool2d(2, 2) self.conv_1 = nn.Conv2d(self.in_channels, 32, kernel_size=8, stride=4) self.conv_2 = nn.Conv2d(32, 64, kernel_size=4, stride=2) self.conv_3 = nn.Conv2d(64, 64, kernel_size=3, stride=1) self.fc_1 = nn.Linear(64 * 7 * 7, 512) self.output_layer = nn.Linear(512, self.num_actions) def forward(self, x): """ In the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use Modules defined in the constructor as well as arbitrary operators on Tensors. """ """Execute a forward propagation step for the neural network. Args: x: An observation in the form of a (4, 84, 84) tensor. """ x = F.relu(self.conv_1(x)) x = F.relu(self.conv_2(x)) x = F.relu(self.conv_3(x)) x = x.reshape(-1, 64 * 7 * 7) x = F.relu(self.fc_1(x)) x = self.output_layer(x) return x def compute_loss(self, tensor_lst, target_network, criterion): """Computes loss between target-Q function and current Q-function. Args: tensor_lst: A list of 5 tensors - current states, current actions, current rewards, terminal state booleans, and next states. Returns: Loss values in the form of a PyTorch tensor. """ obs, act, rew, done, next_obs = tensor_lst with torch.no_grad(): if self.ddqn: next_state_training_q_vals = self(next_obs) max_training_q_vals_ind = next_state_training_q_vals.argmax(dim =1, keepdim=True) next_state_target_q_vals = target_network(next_obs) max_target_q_vals = torch.gather(input= next_state_target_q_vals, dim=1, index= max_training_q_vals_ind) target_q_vals = rew + self.gamma * (1 - done ) * max_target_q_vals else: next_state_target_q_vals = target_network(next_obs) max_target_q_vals = next_state_target_q_vals.max(dim=1, keepdim=True)[0] target_q_vals = rew + self.gamma * (1 - done ) * max_target_q_vals q_vals = self(obs) actual_q_vals = torch.gather(input=q_vals, dim=1, index=act) return criterion(actual_q_vals, target_q_vals) def get_inputs(): return [torch.rand([4, 4, 144, 144])] def get_init_inputs(): return [[], {'gamma': 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_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 156800 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 1225 % 32 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 // 256 % 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_convolution_relu_threshold_backward_2(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 50176 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 196 % 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) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x3, tmp4, xmask) tl.store(out_ptr0 + x3, tmp6, xmask) @triton.jit def triton_poi_fused_relu_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 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) tl.store(in_out_ptr0 + x2, tmp4, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11) = args args.clear() assert_size_stride(primals_1, (32, 4, 8, 8), (256, 64, 8, 1)) assert_size_stride(primals_2, (32,), (1,)) assert_size_stride(primals_3, (4, 4, 144, 144), (82944, 20736, 144, 1)) assert_size_stride(primals_4, (64, 32, 4, 4), (512, 16, 4, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_7, (64,), (1,)) assert_size_stride(primals_8, (512, 3136), (3136, 1)) assert_size_stride(primals_9, (512,), (1,)) assert_size_stride(primals_10, (4, 512), (512, 1)) assert_size_stride(primals_11, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(4, 4), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 32, 35, 35), (39200, 1225, 35, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(156800)](buf1, primals_2, 156800, XBLOCK=512, num_warps=8, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 64, 16, 16), (16384, 256, 16, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_1[grid(65536)](buf3, primals_5, 65536, XBLOCK=512, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 64, 14, 14), (12544, 196, 14, 1)) buf5 = buf4 del buf4 buf9 = empty_strided_cuda((4, 64, 14, 14), (12544, 196, 14, 1), torch.bool) triton_poi_fused_convolution_relu_threshold_backward_2[grid(50176)]( buf5, primals_7, buf9, 50176, XBLOCK=256, num_warps=4, num_stages=1 ) del primals_7 buf6 = empty_strided_cuda((16, 512), (512, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (16, 3136), (3136, 1), 0 ), reinterpret_tensor(primals_8, (3136, 512), (1, 3136), 0), out=buf6) buf7 = buf6 del buf6 triton_poi_fused_relu_3[grid(8192)](buf7, primals_9, 8192, XBLOCK= 256, num_warps=4, num_stages=1) del primals_9 buf8 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_11, buf7, reinterpret_tensor( primals_10, (512, 4), (1, 512), 0), alpha=1, beta=1, out=buf8) del primals_11 return (buf8, primals_1, primals_3, primals_4, primals_6, buf1, buf3, reinterpret_tensor(buf5, (16, 3136), (3136, 1), 0), buf7, primals_10, primals_8, buf9) class DQNNew(nn.Module): """Initialize a deep Q-learning network Hints: ----- Original paper for DQN https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf This is just a hint. You can build your own structure. """ def __init__(self, gamma, ddqn=False, in_channels=4, num_actions=4): """ Parameters: ----------- in_channels: number of channel of input. i.e The number of most recent frames stacked together, here we use 4 frames, which means each state in Breakout is composed of 4 frames. num_actions: number of action-value to output, one-to-one correspondence to action in game. You can add additional arguments as you need. In the constructor we instantiate modules and assign them as member variables. """ super(DQNNew, self).__init__() self.gamma = gamma self.ddqn = ddqn self.in_channels = in_channels self.num_actions = num_actions self.pool = nn.MaxPool2d(2, 2) self.conv_1 = nn.Conv2d(self.in_channels, 32, kernel_size=8, stride=4) self.conv_2 = nn.Conv2d(32, 64, kernel_size=4, stride=2) self.conv_3 = nn.Conv2d(64, 64, kernel_size=3, stride=1) self.fc_1 = nn.Linear(64 * 7 * 7, 512) self.output_layer = nn.Linear(512, self.num_actions) def compute_loss(self, tensor_lst, target_network, criterion): """Computes loss between target-Q function and current Q-function. Args: tensor_lst: A list of 5 tensors - current states, current actions, current rewards, terminal state booleans, and next states. Returns: Loss values in the form of a PyTorch tensor. """ obs, act, rew, done, next_obs = tensor_lst with torch.no_grad(): if self.ddqn: next_state_training_q_vals = self(next_obs) max_training_q_vals_ind = next_state_training_q_vals.argmax(dim =1, keepdim=True) next_state_target_q_vals = target_network(next_obs) max_target_q_vals = torch.gather(input= next_state_target_q_vals, dim=1, index= max_training_q_vals_ind) target_q_vals = rew + self.gamma * (1 - done ) * max_target_q_vals else: next_state_target_q_vals = target_network(next_obs) max_target_q_vals = next_state_target_q_vals.max(dim=1, keepdim=True)[0] target_q_vals = rew + self.gamma * (1 - done ) * max_target_q_vals q_vals = self(obs) actual_q_vals = torch.gather(input=q_vals, dim=1, index=act) return criterion(actual_q_vals, target_q_vals) def forward(self, input_0): primals_1 = self.conv_1.weight primals_2 = self.conv_1.bias primals_4 = self.conv_2.weight primals_5 = self.conv_2.bias primals_6 = self.conv_3.weight primals_7 = self.conv_3.bias primals_8 = self.fc_1.weight primals_9 = self.fc_1.bias primals_10 = self.output_layer.weight primals_11 = self.output_layer.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11]) return output[0]
khaiyichin/DS595-RL-Projects
DQN
false
12,695
[ "MIT" ]
0
4add6b2adc2cb9f7cdb783d50b005ecd1b4aada3
https://github.com/khaiyichin/DS595-RL-Projects/tree/4add6b2adc2cb9f7cdb783d50b005ecd1b4aada3
BasicBlock
import torch import torch.nn as nn import torch.utils.data def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) class BasicBlock(nn.Module): expansion = 1 __constants__ = ['downsample'] def __init__(self, inplanes, planes, stride=1, downsample=None, groups= 1, base_width=64, dilation=1, norm_model='instance'): super(BasicBlock, self).__init__() if 'instance' == norm_model: norm_layer = nn.InstanceNorm2d else: norm_layer = nn.BatchNorm2d if groups != 1 or base_width != 64: raise ValueError( 'BasicBlock only supports groups=1 and base_width=64') if dilation > 1: raise NotImplementedError( 'Dilation > 1 not supported in BasicBlock') self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = norm_layer(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = norm_layer(planes) self.stride = stride if stride != 1 or inplanes != planes: self.downsample = nn.Sequential(conv1x1(inplanes, planes, stride), norm_layer(planes)) else: self.downsample = downsample def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(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 from torch._inductor.runtime.triton_helpers import libdevice import torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_per_fused__native_batch_norm_legit_relu_0(in_ptr0, out_ptr0, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tl.where(xmask, tmp1, 0) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp6 = tl.where(xmask, tmp4, 0) tmp7 = tl.sum(tmp6, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 16, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp1 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.where(xmask, tmp13, 0) tmp16 = tl.sum(tmp15, 1)[:, None] tmp17 = tmp0 - tmp10 tmp18 = 16.0 tmp19 = tmp16 / tmp18 tmp20 = 1e-05 tmp21 = tmp19 + tmp20 tmp22 = libdevice.rsqrt(tmp21) tmp23 = tmp17 * tmp22 tmp24 = tl.full([1, 1], 0, tl.int32) tmp25 = triton_helpers.maximum(tmp24, tmp23) tl.store(out_ptr2 + (r1 + 16 * x0), tmp25, xmask) tl.store(out_ptr3 + x0, tmp22, xmask) tl.store(out_ptr0 + x0, tmp10, xmask) @triton.jit def triton_per_fused__native_batch_norm_legit_relu_threshold_backward_1(in_ptr0 , in_ptr1, out_ptr0, out_ptr2, out_ptr3, out_ptr4, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 RBLOCK: tl.constexpr = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp24 = tl.load(in_ptr1 + (r1 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tl.where(xmask, tmp1, 0) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp6 = tl.where(xmask, tmp4, 0) tmp7 = tl.sum(tmp6, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 16, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp1 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.where(xmask, tmp13, 0) tmp16 = tl.sum(tmp15, 1)[:, None] tmp17 = tmp0 - tmp10 tmp18 = 16.0 tmp19 = tmp16 / tmp18 tmp20 = 1e-05 tmp21 = tmp19 + tmp20 tmp22 = libdevice.rsqrt(tmp21) tmp23 = tmp17 * tmp22 tmp25 = tmp23 + tmp24 tmp26 = tl.full([1, 1], 0, tl.int32) tmp27 = triton_helpers.maximum(tmp26, tmp25) tmp28 = 0.0 tmp29 = tmp27 <= tmp28 tl.store(out_ptr2 + (r1 + 16 * x0), tmp27, xmask) tl.store(out_ptr3 + (r1 + 16 * x0), tmp29, xmask) tl.store(out_ptr4 + x0, tmp22, xmask) tl.store(out_ptr0 + x0, tmp10, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 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_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, 4, 4, 4), (64, 16, 4, 1)) buf1 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf4 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) get_raw_stream(0) triton_per_fused__native_batch_norm_legit_relu_0[grid(16)](buf0, buf1, buf5, buf4, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) buf6 = extern_kernels.convolution(buf5, primals_3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1)) buf7 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) buf10 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch. float32) triton_per_fused__native_batch_norm_legit_relu_threshold_backward_1[ grid(16)](buf6, primals_1, buf7, buf11, buf12, buf10, 16, 16, XBLOCK=1, num_warps=2, num_stages=1) return buf11, primals_1, primals_2, primals_3, buf0, reinterpret_tensor( buf4, (16,), (1,), 0), buf5, buf6, reinterpret_tensor(buf10, (16,), (1,), 0), buf12, reinterpret_tensor(buf7, (1, 16, 1, 1), (16, 1, 1, 1), 0), reinterpret_tensor(buf1, (1, 16, 1, 1), (16, 1, 1, 1), 0) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) class BasicBlockNew(nn.Module): expansion = 1 __constants__ = ['downsample'] def __init__(self, inplanes, planes, stride=1, downsample=None, groups= 1, base_width=64, dilation=1, norm_model='instance'): super(BasicBlockNew, self).__init__() if 'instance' == norm_model: norm_layer = nn.InstanceNorm2d else: norm_layer = nn.BatchNorm2d if groups != 1 or base_width != 64: raise ValueError( 'BasicBlock only supports groups=1 and base_width=64') if dilation > 1: raise NotImplementedError( 'Dilation > 1 not supported in BasicBlock') self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = norm_layer(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = norm_layer(planes) self.stride = stride if stride != 1 or inplanes != planes: self.downsample = nn.Sequential(conv1x1(inplanes, planes, stride), norm_layer(planes)) else: self.downsample = downsample def forward(self, input_0): primals_2 = self.conv1.weight primals_3 = self.conv2.weight primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
kudoNCT/michigan_copy
BasicBlock
false
12,696
[ "MIT" ]
0
e857b96a65b270ef2506cb9866b7e01f117c4396
https://github.com/kudoNCT/michigan_copy/tree/e857b96a65b270ef2506cb9866b7e01f117c4396
FeaturePyramidNetwork
import torch import torch.nn as nn class FeaturePyramidNetwork(nn.Module): def __init__(self, C3_feature, C4_feature, C5_feature, feature_size=256): super(FeaturePyramidNetwork, self).__init__() self.P5_1 = nn.Conv2d(C5_feature, feature_size, kernel_size=1, stride=1, padding=0) self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest') self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) self.P4_1 = nn.Conv2d(C4_feature, feature_size, kernel_size=1, stride=1, padding=0) self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest') self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) self.P3_1 = nn.Conv2d(C3_feature, feature_size, kernel_size=1, stride=1, padding=0) self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) def forward(self, C3, C4, C5): P5_x = self.P5_1(C5) P5_upsampled_x = self.P5_upsampled(P5_x) P5_x = self.P5_2(P5_x) P4_x = self.P4_1(C4) P4_x = P5_upsampled_x + P4_x P4_upsampled_x = self.P4_upsampled(P4_x) P4_x = self.P4_2(P4_x) P3_x = self.P3_1(C3) P3_x = P3_x + P4_upsampled_x P3_x = self.P3_2(P3_x) return P3_x def get_inputs(): return [torch.rand([4, 4, 16, 16]), torch.rand([4, 4, 8, 8]), torch. rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'C3_feature': 4, 'C4_feature': 4, 'C5_feature': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 16 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask) tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 64 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 64 * y3), xmask & ymask, eviction_policy ='evict_last') tl.store(out_ptr0 + (y0 + 4 * x2 + 256 * y1), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 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] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 256 * y3), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (y0 + 4 * x2 + 1024 * y1), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): xnumel = 9 yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1) ) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 256 y1 = yindex // 256 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask) @triton.jit def triton_poi_fused__to_copy_add_arange_mul_4(out_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 8 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 * tmp2 tmp4 = tmp3.to(tl.int32) tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused__to_copy_add_arange_mul_5(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 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 * tmp2 tmp4 = tmp3.to(tl.int32) tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused__unsafe_index_add_convolution_6(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x4 = xindex x0 = xindex % 256 x2 = xindex // 4096 % 16 x1 = xindex // 256 % 16 x3 = xindex // 65536 tmp0 = tl.load(in_out_ptr0 + x4, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + x2, None, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last') tmp22 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp25 = tl.load(in_ptr6 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tl.full([XBLOCK], 8, tl.int32) tmp5 = tmp3 + tmp4 tmp6 = tmp3 < 0 tmp7 = tl.where(tmp6, tmp5, tmp3) tmp9 = tmp8 + tmp4 tmp10 = tmp8 < 0 tmp11 = tl.where(tmp10, tmp9, tmp8) tmp12 = tl.load(in_ptr2 + tmp7, None, eviction_policy='evict_last') tmp13 = tl.full([XBLOCK], 4, tl.int32) tmp14 = tmp12 + tmp13 tmp15 = tmp12 < 0 tmp16 = tl.where(tmp15, tmp14, tmp12) tmp17 = tl.load(in_ptr2 + tmp11, None, eviction_policy='evict_last') tmp18 = tmp17 + tmp13 tmp19 = tmp17 < 0 tmp20 = tl.where(tmp19, tmp18, tmp17) tmp21 = tl.load(in_ptr3 + (x0 + 256 * tmp20 + 1024 * tmp16 + 4096 * x3), None) tmp23 = tmp21 + tmp22 tmp24 = tl.load(in_ptr5 + (x0 + 256 * tmp11 + 2048 * tmp7 + 16384 * x3), None) tmp26 = tmp24 + tmp25 tmp27 = tmp23 + tmp26 tmp28 = tmp2 + tmp27 tl.store(in_out_ptr0 + x4, tmp28, None) @triton.jit def triton_poi_fused_convolution_7(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 256 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] tl.full([XBLOCK, YBLOCK], True, tl.int1) xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 65536 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x2 + 256 * y3), 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) = args args.clear() assert_size_stride(primals_1, (256, 4, 1, 1), (4, 1, 1, 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, (256, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_5, (256,), (1,)) assert_size_stride(primals_6, (256, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_7, (256,), (1,)) assert_size_stride(primals_8, (4, 4, 8, 8), (256, 64, 8, 1)) assert_size_stride(primals_9, (256, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_10, (256,), (1,)) assert_size_stride(primals_11, (256, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_12, (256,), (1,)) assert_size_stride(primals_13, (4, 4, 16, 16), (1024, 256, 16, 1)) assert_size_stride(primals_14, (256, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_15, (256,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(16, 16)](primals_3, buf0, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1) del primals_3 buf1 = empty_strided_cuda((4, 4, 8, 8), (256, 1, 32, 4), torch.float32) triton_poi_fused_1[grid(16, 64)](primals_8, buf1, 16, 64, XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1) del primals_8 buf2 = empty_strided_cuda((4, 4, 16, 16), (1024, 1, 64, 4), torch. float32) triton_poi_fused_2[grid(16, 256)](primals_13, buf2, 16, 256, XBLOCK =64, YBLOCK=16, num_warps=4, num_stages=1) del primals_13 buf3 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256), torch.float32) triton_poi_fused_3[grid(65536, 9)](primals_14, buf3, 65536, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_14 buf4 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 256, 4, 4), (4096, 1, 1024, 256)) buf5 = empty_strided_cuda((8,), (1,), torch.int64) triton_poi_fused__to_copy_add_arange_mul_4[grid(8)](buf5, 8, XBLOCK =8, num_warps=1, num_stages=1) buf6 = extern_kernels.convolution(buf1, 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, 256, 8, 8), (16384, 1, 2048, 256)) buf7 = empty_strided_cuda((16,), (1,), torch.int64) triton_poi_fused__to_copy_add_arange_mul_5[grid(16)](buf7, 16, XBLOCK=16, num_warps=1, num_stages=1) buf8 = extern_kernels.convolution(buf2, primals_11, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 256, 16, 16), (65536, 1, 4096, 256)) buf9 = buf8 del buf8 triton_poi_fused__unsafe_index_add_convolution_6[grid(262144)](buf9, primals_12, buf7, buf5, buf4, primals_2, buf6, primals_7, 262144, XBLOCK=1024, num_warps=4, num_stages=1) del buf4 del buf6 del primals_12 del primals_2 del primals_7 buf10 = extern_kernels.convolution(buf9, buf3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 256, 16, 16), (65536, 1, 4096, 256)) buf11 = empty_strided_cuda((4, 256, 16, 16), (65536, 256, 16, 1), torch.float32) triton_poi_fused_convolution_7[grid(1024, 256)](buf10, primals_15, buf11, 1024, 256, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del buf10 del primals_15 return (buf11, primals_1, buf0, primals_6, buf1, primals_11, buf2, buf3, buf5, buf7, buf9) class FeaturePyramidNetworkNew(nn.Module): def __init__(self, C3_feature, C4_feature, C5_feature, feature_size=256): super(FeaturePyramidNetworkNew, self).__init__() self.P5_1 = nn.Conv2d(C5_feature, feature_size, kernel_size=1, stride=1, padding=0) self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest') self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) self.P4_1 = nn.Conv2d(C4_feature, feature_size, kernel_size=1, stride=1, padding=0) self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest') self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) self.P3_1 = nn.Conv2d(C3_feature, feature_size, kernel_size=1, stride=1, padding=0) self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) def forward(self, input_0, input_1, input_2): primals_1 = self.P5_1.weight primals_2 = self.P5_1.bias primals_4 = self.P5_2.weight primals_5 = self.P5_2.bias primals_6 = self.P4_1.weight primals_7 = self.P4_1.bias primals_9 = self.P4_2.weight primals_10 = self.P4_2.bias primals_11 = self.P3_1.weight primals_12 = self.P3_1.bias primals_14 = self.P3_2.weight primals_15 = self.P3_2.bias primals_13 = input_0 primals_8 = input_1 primals_3 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15]) return output[0]
kiyohiro8/SemanticReasoningNetworks
FeaturePyramidNetwork
false
12,697
[ "MIT" ]
0
9dc20706a2234511789a7a2fa07cc3b77c64bf81
https://github.com/kiyohiro8/SemanticReasoningNetworks/tree/9dc20706a2234511789a7a2fa07cc3b77c64bf81
_Hswish
import torch import torch.nn as nn class _Hswish(nn.Module): def __init__(self, inplace=True): super(_Hswish, self).__init__() self.relu6 = nn.ReLU6(inplace) def forward(self, x): return x * self.relu6(x + 3.0) / 6.0 def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_div_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = tmp0 * tmp6 tmp8 = 0.16666666666666666 tmp9 = tmp7 * tmp8 tl.store(out_ptr0 + x0, tmp9, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_hardtanh_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class _HswishNew(nn.Module): def __init__(self, inplace=True): super(_HswishNew, self).__init__() self.relu6 = nn.ReLU6(inplace) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
hzwangjl/Lightweight-Segmentation
_Hswish
false
12,698
[ "Apache-2.0" ]
0
3a476719bdfee653ac1e1617c22714b7ee932cef
https://github.com/hzwangjl/Lightweight-Segmentation/tree/3a476719bdfee653ac1e1617c22714b7ee932cef
AR
import torch import torch.utils.data import torch.nn as nn from typing import * class AR(nn.Module): def __init__(self, window): super(AR, self).__init__() self.linear = nn.Linear(window, 1) def forward(self, x): x = torch.transpose(x, 1, 2) x = self.linear(x) x = torch.transpose(x, 1, 2) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'window': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.utils.data import torch.nn as nn from typing import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_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_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) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1, 4), (4, 1)) assert_size_stride(primals_3, (1,), (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= 128, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 1), (1, 4), 0), out=buf1) del primals_2 buf2 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf1 triton_poi_fused_add_1[grid(64)](buf2, primals_3, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 return reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 1, 4, 1), 0 ), reinterpret_tensor(buf0, (64, 4), (4, 1), 0) class ARNew(nn.Module): def __init__(self, window): super(ARNew, self).__init__() self.linear = nn.Linear(window, 1) def forward(self, input_0): primals_2 = self.linear.weight primals_3 = self.linear.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
kuleshov/multivariate-deep-learning
AR
false
12,699
[ "MIT" ]
0
c87bf321a13fdb44c22decf6f685296b8f637a67
https://github.com/kuleshov/multivariate-deep-learning/tree/c87bf321a13fdb44c22decf6f685296b8f637a67
SoftNLL
import torch import torch.nn as nn class SoftNLL(nn.Module): def __init__(self): """The `soft' version of negative_log_likelihood, where y is a distribution over classes rather than a one-hot coding """ super(SoftNLL, self).__init__() def forward(self, input, target): return -torch.mean(torch.sum(torch.log(input) * target, dim=1)) 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 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_log_mean_mul_neg_sum_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) tmp2 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp6 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp11 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp16 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp1 = tl_math.log(tmp0) tmp3 = tmp1 * tmp2 tmp5 = tl_math.log(tmp4) tmp7 = tmp5 * tmp6 tmp8 = tmp3 + tmp7 tmp10 = tl_math.log(tmp9) tmp12 = tmp10 * tmp11 tmp13 = tmp8 + tmp12 tmp15 = tl_math.log(tmp14) tmp17 = tmp15 * tmp16 tmp18 = tmp13 + tmp17 tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK]) tmp21 = tl.sum(tmp19, 1)[:, None] tmp22 = 64.0 tmp23 = tmp21 / tmp22 tmp24 = -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_log_mean_mul_neg_sum_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 SoftNLLNew(nn.Module): def __init__(self): """The `soft' version of negative_log_likelihood, where y is a distribution over classes rather than a one-hot coding """ super(SoftNLLNew, 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]
lehgtrung/gcn-over-pruned-trees
SoftNLL
false
12,700
[ "Apache-2.0" ]
0
ebf0de0948883009a9bebb8ff336e8d6fe50a26f
https://github.com/lehgtrung/gcn-over-pruned-trees/tree/ebf0de0948883009a9bebb8ff336e8d6fe50a26f
GlobalMaxPool1d
import torch from torch import nn class GlobalMaxPool1d(nn.Module): """Performs global max pooling over the entire length of a batched 1D tensor # Arguments input: Input tensor """ def forward(self, input): return nn.functional.max_pool1d(input, kernel_size=input.size()[2:] ).view(-1, input.size(1)) def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tl.store(out_ptr0 + x0, tmp6, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32) get_raw_stream(0) triton_poi_fused_max_pool2d_with_indices_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 4), (4, 1), 0), class GlobalMaxPool1dNew(nn.Module): """Performs global max pooling over the entire length of a batched 1D tensor # Arguments input: Input tensor """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
liaoweiduo/few-shot
GlobalMaxPool1d
false
12,701
[ "MIT" ]
0
24d54fa3b472194b8cdab0ec6017bc5f649380a0
https://github.com/liaoweiduo/few-shot/tree/24d54fa3b472194b8cdab0ec6017bc5f649380a0
LearnedPositionalEmbedding
import torch import torch.nn as nn import torch.nn.functional as F class LearnedPositionalEmbedding(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. Padding ids are ignored by either offsetting based on padding_idx or by setting padding_idx to None and ensuring that the appropriate position ids are passed to the forward function. """ def __init__(self, num_embeddings: 'int', embedding_dim: 'int', padding_idx: 'int'): if padding_idx is not None: num_embeddings_ = num_embeddings + padding_idx + 1 else: num_embeddings_ = num_embeddings super().__init__(num_embeddings_, embedding_dim, padding_idx) self.max_positions = num_embeddings def forward(self, input: 'torch.Tensor'): """Input is expected to be of size [bsz x seqlen].""" if input.size(1) > self.max_positions: raise ValueError( f'Sequence length {input.size(1)} above maximum sequence length of {self.max_positions}' ) mask = input.ne(self.padding_idx).int() positions = (torch.cumsum(mask, dim=1).type_as(mask) * mask).long( ) + self.padding_idx return F.embedding(positions, self.weight, self.padding_idx, self. max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_embeddings': 4, 'embedding_dim': 4, 'padding_idx': 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 @triton.jit def _triton_helper_fn_add0(arg0_0, arg1_0): tmp0 = arg0_0 + arg1_0 return tmp0 @triton.jit def triton_per_fused__to_copy_cumsum_ne_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 64 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) r2 = rindex x0 = xindex % 16 x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), xmask, other=0.0) tmp1 = 4.0 tmp2 = tmp0 != tmp1 tmp3 = tmp2.to(tl.int32) tmp4 = tmp3.to(tl.int64) tmp5 = tmp4.to(tl.int64) tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tmp7, = tl.associative_scan((tmp6,), 1, _triton_helper_fn_add0) tl.store(out_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp7, xmask) @triton.jit def triton_poi_fused__to_copy_add_mul_ne_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 x0 = xindex tmp0 = tl.load(in_out_ptr0 + x0, xmask) tmp2 = tl.load(in_ptr0 + x0, xmask) tmp1 = tmp0.to(tl.int32) tmp3 = 4.0 tmp4 = tmp2 != tmp3 tmp5 = tmp4.to(tl.int32) tmp6 = tmp1 * tmp5 tmp7 = tmp6.to(tl.int64) tmp8 = tl.full([1], 4, tl.int64) tmp9 = tmp7 + tmp8 tl.store(in_out_ptr0 + x0, tmp9, xmask) @triton.jit def triton_poi_fused_embedding_2(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 x1 = xindex // 4 x0 = xindex % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp1 = tl.full([XBLOCK], 9, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tl.device_assert((0 <= tmp4) & (tmp4 < 9) | ~xmask, 'index out of bounds: 0 <= tmp4 < 9') tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask) tl.store(out_ptr0 + x2, tmp6, 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, (9, 4), (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.int64) get_raw_stream(0) triton_per_fused__to_copy_cumsum_ne_0[grid(64)](primals_1, buf0, 64, 4, XBLOCK=32, num_warps=2, num_stages=1) buf1 = buf0 del buf0 triton_poi_fused__to_copy_add_mul_ne_1[grid(256)](buf1, primals_1, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_poi_fused_embedding_2[grid(1024)](buf1, primals_2, buf2, 1024, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 return buf2, buf1 class LearnedPositionalEmbeddingNew(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. Padding ids are ignored by either offsetting based on padding_idx or by setting padding_idx to None and ensuring that the appropriate position ids are passed to the forward function. """ def __init__(self, num_embeddings: 'int', embedding_dim: 'int', padding_idx: 'int'): if padding_idx is not None: num_embeddings_ = num_embeddings + padding_idx + 1 else: num_embeddings_ = num_embeddings super().__init__(num_embeddings_, embedding_dim, padding_idx) self.max_positions = num_embeddings def forward(self, input_0): primals_2 = self.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
leeharry92/esm
LearnedPositionalEmbedding
false
12,702
[ "MIT" ]
0
7d0feccf03ebbdeba4e7ba0f21d934099a0223ce
https://github.com/leeharry92/esm/tree/7d0feccf03ebbdeba4e7ba0f21d934099a0223ce
MSELoss2d
import torch import torch.nn as nn class MSELoss2d(nn.Module): def __init__(self, size_average=None, reduce=None, reduction='mean', ignore_index=255): super(MSELoss2d, self).__init__() self.MSE = nn.MSELoss(size_average=size_average, reduce=reduce, reduction=reduction) def forward(self, output, target): loss = self.MSE(torch.softmax(output, dim=1), target) return loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel 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_per_fused__softmax_mse_loss_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) 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' ) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr1 + r3, None) tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tmp10 = tmp8 - tmp9 tmp11 = tmp10 * 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 = 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__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK= 256, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused__softmax_mse_loss_1[grid(1)](buf2, buf0, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg1_1 del buf0 return buf2, class MSELoss2dNew(nn.Module): def __init__(self, size_average=None, reduce=None, reduction='mean', ignore_index=255): super(MSELoss2dNew, self).__init__() self.MSE = nn.MSELoss(size_average=size_average, reduce=reduce, 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]
leo-hao/DACS
MSELoss2d
false
12,703
[ "MIT" ]
0
9fe9bc077a9a0e0fd2b118bfc2d522c2b6fb624e
https://github.com/leo-hao/DACS/tree/9fe9bc077a9a0e0fd2b118bfc2d522c2b6fb624e
ShiftedConv
import math import torch import torch.nn as nn from numpy import prod def getLayerNormalizationFactor(x): """ Get He's constant for the given layer https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf """ size = x.weight.size() fan_in = prod(size[1:]) return math.sqrt(2.0 / fan_in) class ConstrainedLayer(nn.Module): """ A handy refactor that allows the user to: - initialize one layer's bias to zero - apply He's initialization at runtime """ def __init__(self, module, equalized=True, lrMul=1.0, initBiasToZero=True): """ equalized (bool): if true, the layer's weight should evolve within the range (-1, 1) initBiasToZero (bool): if true, bias will be initialized to zero """ super(ConstrainedLayer, self).__init__() self.module = module self.equalized = equalized if initBiasToZero and module.bias is not None: self.module.bias.data.fill_(0) if self.equalized: self.module.weight.data.normal_(0, 1) self.weight = getLayerNormalizationFactor(self.module) * lrMul def forward(self, x): x = self.module(x) if self.equalized: x *= self.weight return x class EqualizedConv1d(ConstrainedLayer): def __init__(self, nChannelsPrevious, nChannels, kernelSize, padding=0, bias=True, stride=1, **kwargs): """ A nn.Conv2d module with specific constraints Args: nChannelsPrevious (int): number of channels in the previous layer nChannels (int): number of channels of the current layer kernelSize (int): size of the convolutional kernel padding (int): convolution's padding bias (bool): with bias ? """ ConstrainedLayer.__init__(self, nn.Conv1d(nChannelsPrevious, nChannels, kernelSize, padding=padding, bias=bias, stride= stride), **kwargs) class ShiftedConv(nn.Module): def __init__(self, dimOutputAR, dimOutputEncoder, kernelSize): super(ShiftedConv, self).__init__() self.module = EqualizedConv1d(dimOutputAR, dimOutputEncoder, kernelSize, equalized=True, padding=0) self.kernelSize = kernelSize def forward(self, x): N, _S, C = x.size() x = x.permute(0, 2, 1) padding = torch.zeros(N, C, self.kernelSize - 1, device=x.device) x = torch.cat([padding, x], dim=2) x = self.module(x) x = x.permute(0, 2, 1) return x def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'dimOutputAR': 4, 'dimOutputEncoder': 4, 'kernelSize': 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 from numpy import prod 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, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 112 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 7 x1 = xindex // 7 % 4 x2 = xindex // 28 x3 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 3, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = 0.0 tmp6 = tl.full(tmp5.shape, 0.0, tmp5.dtype) tmp7 = tl.where(tmp4, tmp5, tmp6) tmp8 = tmp0 >= tmp3 tl.full([1], 7, tl.int64) tmp11 = tl.load(in_ptr0 + (x1 + 4 * (-3 + x0) + 16 * x2), tmp8 & xmask, eviction_policy='evict_last', other=0.0) tmp12 = tl.where(tmp4, tmp7, tmp11) tl.store(out_ptr0 + x3, tmp12, xmask) @triton.jit def triton_poi_fused_convolution_mul_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 = 0.3535533905932738 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x3, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 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, 4, 7), (28, 7, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(112)](primals_1, buf0, 112, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf1, (4, 4, 4), (16, 4, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_mul_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, buf0 def getLayerNormalizationFactor(x): """ Get He's constant for the given layer https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf """ size = x.weight.size() fan_in = prod(size[1:]) return math.sqrt(2.0 / fan_in) class ConstrainedLayer(nn.Module): """ A handy refactor that allows the user to: - initialize one layer's bias to zero - apply He's initialization at runtime """ def __init__(self, module, equalized=True, lrMul=1.0, initBiasToZero=True): """ equalized (bool): if true, the layer's weight should evolve within the range (-1, 1) initBiasToZero (bool): if true, bias will be initialized to zero """ super(ConstrainedLayer, self).__init__() self.module = module self.equalized = equalized if initBiasToZero and module.bias is not None: self.module.bias.data.fill_(0) if self.equalized: self.module.weight.data.normal_(0, 1) self.weight = getLayerNormalizationFactor(self.module) * lrMul def forward(self, x): x = self.module(x) if self.equalized: x *= self.weight return x class EqualizedConv1d(ConstrainedLayer): def __init__(self, nChannelsPrevious, nChannels, kernelSize, padding=0, bias=True, stride=1, **kwargs): """ A nn.Conv2d module with specific constraints Args: nChannelsPrevious (int): number of channels in the previous layer nChannels (int): number of channels of the current layer kernelSize (int): size of the convolutional kernel padding (int): convolution's padding bias (bool): with bias ? """ ConstrainedLayer.__init__(self, nn.Conv1d(nChannelsPrevious, nChannels, kernelSize, padding=padding, bias=bias, stride= stride), **kwargs) class ShiftedConvNew(nn.Module): def __init__(self, dimOutputAR, dimOutputEncoder, kernelSize): super(ShiftedConvNew, self).__init__() self.module = EqualizedConv1d(dimOutputAR, dimOutputEncoder, kernelSize, equalized=True, padding=0) self.kernelSize = kernelSize def forward(self, input_0): primals_1 = self.module.module.weight primals_3 = self.module.module.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
leo19941227/CPC_audio
ShiftedConv
false
12,704
[ "MIT" ]
0
2d0051915f4b4a5f773e4510cd5535e1fcb433d8
https://github.com/leo19941227/CPC_audio/tree/2d0051915f4b4a5f773e4510cd5535e1fcb433d8
_Hsigmoid
import torch import torch.nn as nn class _Hsigmoid(nn.Module): def __init__(self, inplace=True): super(_Hsigmoid, self).__init__() self.relu6 = nn.ReLU6(inplace) def forward(self, x): return self.relu6(x + 3.0) / 6.0 def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_div_hardtanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = 0.16666666666666666 tmp8 = tmp6 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_hardtanh_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class _HsigmoidNew(nn.Module): def __init__(self, inplace=True): super(_HsigmoidNew, self).__init__() self.relu6 = nn.ReLU6(inplace) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
hzwangjl/Lightweight-Segmentation
_Hsigmoid
false
12,705
[ "Apache-2.0" ]
0
3a476719bdfee653ac1e1617c22714b7ee932cef
https://github.com/hzwangjl/Lightweight-Segmentation/tree/3a476719bdfee653ac1e1617c22714b7ee932cef
TransposedConvModel
import torch import torch.nn import torch.utils.data import torch.utils.tensorboard._pytorch_graph import torch.onnx.symbolic_caffe2 class TransposedConvModel(torch.nn.Module): def __init__(self): super(TransposedConvModel, self).__init__() self.conv1 = torch.nn.ConvTranspose2d(10, 10, 3) self.relu1 = torch.nn.ReLU() self.conv2 = torch.nn.ConvTranspose2d(10, 10, 3) def forward(self, x): x = self.conv1(x) x = self.relu1(x) x = self.conv2(x) return x def get_inputs(): return [torch.rand([4, 10, 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 import torch.utils.data import torch.utils.tensorboard._pytorch_graph import torch.onnx.symbolic_caffe2 assert_size_stride = torch._C._dynamo.guards.assert_size_stride @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1440 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 36 % 10 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 2560 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 64 % 10 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 = args args.clear() assert_size_stride(primals_1, (10, 10, 3, 3), (90, 9, 3, 1)) assert_size_stride(primals_2, (10,), (1,)) assert_size_stride(primals_3, (4, 10, 4, 4), (160, 16, 4, 1)) assert_size_stride(primals_4, (10, 10, 3, 3), (90, 9, 3, 1)) assert_size_stride(primals_5, (10,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 10, 6, 6), (360, 36, 6, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(1440)](buf1, primals_2, 1440, XBLOCK=128, 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=True, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 10, 8, 8), (640, 64, 8, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_1[grid(2560)](buf3, primals_5, 2560, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 return buf3, primals_1, primals_3, primals_4, buf1 class TransposedConvModelNew(torch.nn.Module): def __init__(self): super(TransposedConvModelNew, self).__init__() self.conv1 = torch.nn.ConvTranspose2d(10, 10, 3) self.relu1 = torch.nn.ReLU() self.conv2 = torch.nn.ConvTranspose2d(10, 10, 3) def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
arjunsuresh/aimet
TransposedConvModel
false
12,706
[ "BSD-3-Clause" ]
0
f6e09cb07a91eed3a5e6b8e19e6b065303af5a39
https://github.com/arjunsuresh/aimet/tree/f6e09cb07a91eed3a5e6b8e19e6b065303af5a39
ln_mod
import torch import torch.nn as nn from torch.nn.parameter import Parameter class ln_mod(nn.Module): def __init__(self, nx, eps=1e-05): super().__init__() self.eps = eps self.weight = Parameter(torch.Tensor(nx)) def forward(self, x): return x / torch.sqrt(torch.std(x, axis=-1, unbiased=False, keepdim =True) ** 2 + self.eps) * self.weight.data[..., :] def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'nx': 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 import torch.nn as nn from torch.nn.parameter import Parameter 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_sqrt_std_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 = tmp1 - tmp9 tmp11 = tmp10 * tmp10 tmp12 = tmp2 - tmp9 tmp13 = tmp12 * tmp12 tmp14 = tmp11 + tmp13 tmp15 = tmp4 - tmp9 tmp16 = tmp15 * tmp15 tmp17 = tmp14 + tmp16 tmp18 = tmp6 - tmp9 tmp19 = tmp18 * tmp18 tmp20 = tmp17 + tmp19 tmp21 = tmp20 / tmp8 tmp22 = libdevice.sqrt(tmp21) tmp23 = tmp22 * tmp22 tmp24 = 1e-05 tmp25 = tmp23 + tmp24 tmp26 = libdevice.sqrt(tmp25) tmp27 = tmp0 / tmp26 tmp29 = tmp27 * tmp28 tl.store(out_ptr0 + x2, tmp29, 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,), (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_sqrt_std_0[grid(256)](arg0_1, arg1_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del arg1_1 return buf0, class ln_modNew(nn.Module): def __init__(self, nx, eps=1e-05): super().__init__() self.eps = eps self.weight = Parameter(torch.Tensor(nx)) def forward(self, input_0): arg1_1 = self.weight arg0_1 = input_0 output = call([arg0_1, arg1_1]) return output[0]
lienghongky/image-gpt2
ln_mod
false
12,707
[ "MIT" ]
0
ef9f3c61d4a09cbb75114dd067d0014948e82d7b
https://github.com/lienghongky/image-gpt2/tree/ef9f3c61d4a09cbb75114dd067d0014948e82d7b
TemperatureHolder
import torch from torch import nn class TemperatureHolder(nn.Module): """Module that holds a temperature as a learnable value. Args: initial_log_temperature (float): Initial value of log(temperature). """ def __init__(self, initial_log_temperature=0): super().__init__() self.log_temperature = nn.Parameter(torch.tensor( initial_log_temperature, dtype=torch.float32)) def forward(self): """Return a temperature as a torch.Tensor.""" return torch.exp(self.log_temperature) def get_inputs(): return [] 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_poi_fused_exp_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 = tl_math.exp(tmp1) tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp2, None) def call(args): primals_1, = args args.clear() assert_size_stride(primals_1, (), ()) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_poi_fused_exp_0[grid(1)](primals_1, buf0, 1, XBLOCK=1, num_warps=1, num_stages=1) del primals_1 return buf0, buf0 class TemperatureHolderNew(nn.Module): """Module that holds a temperature as a learnable value. Args: initial_log_temperature (float): Initial value of log(temperature). """ def __init__(self, initial_log_temperature=0): super().__init__() self.log_temperature = nn.Parameter(torch.tensor( initial_log_temperature, dtype=torch.float32)) def forward(self): primals_1 = self.log_temperature output = call([primals_1]) return output[0]
lin826/pfrl
TemperatureHolder
false
12,708
[ "MIT" ]
0
62d7f13b854f1879211a386fd870a7db982cc8ec
https://github.com/lin826/pfrl/tree/62d7f13b854f1879211a386fd870a7db982cc8ec
InnerProductNetwork
import torch import torch.utils.data class InnerProductNetwork(torch.nn.Module): def forward(self, x): """ :param x: Float tensor of size ``(batch_size, num_fields, embed_dim)`` """ num_fields = x.shape[1] row, col = list(), list() for i in range(num_fields - 1): for j in range(i + 1, num_fields): row.append(i), col.append(j) return torch.sum(x[:, row] * x[:, col], dim=2) 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.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_index_mul_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 96 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 6 x0 = xindex % 4 x2 = xindex // 24 x3 = xindex tmp0 = x1 tmp1 = tl.full([1], 3, tl.int64) tmp2 = tmp0 < tmp1 tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.full([1], 2, tl.int64) tmp6 = tmp0 < tmp5 tmp7 = tl.full([1], 0, tl.int64) tmp8 = tl.where(tmp6, tmp7, tmp7) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tl.full([1], 4, tl.int64) tmp11 = tmp0 < tmp10 tmp12 = tl.full([1], 5, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tl.where(tmp13, tmp3, tmp5) tmp15 = tl.where(tmp11, tmp3, tmp14) tmp16 = tl.where(tmp2, tmp9, tmp15) tmp17 = tl.load(in_ptr0 + (x0 + 16 * tmp16 + 64 * x2), xmask) tmp18 = tl.where(tmp6, tmp5, tmp1) tmp19 = tl.where(tmp4, tmp3, tmp18) tmp20 = tl.where(tmp13, tmp1, tmp1) tmp21 = tl.where(tmp11, tmp5, tmp20) tmp22 = tl.where(tmp2, tmp19, tmp21) tmp23 = tl.load(in_ptr0 + (x0 + 16 * tmp22 + 64 * x2), xmask) tmp24 = tmp17 * tmp23 tmp25 = tl.load(in_ptr0 + (4 + x0 + 16 * tmp16 + 64 * x2), xmask) tmp26 = tl.load(in_ptr0 + (4 + x0 + 16 * tmp22 + 64 * x2), xmask) tmp27 = tmp25 * tmp26 tmp28 = tmp24 + tmp27 tmp29 = tl.load(in_ptr0 + (8 + x0 + 16 * tmp16 + 64 * x2), xmask) tmp30 = tl.load(in_ptr0 + (8 + x0 + 16 * tmp22 + 64 * x2), xmask) tmp31 = tmp29 * tmp30 tmp32 = tmp28 + tmp31 tmp33 = tl.load(in_ptr0 + (12 + x0 + 16 * tmp16 + 64 * x2), xmask) tmp34 = tl.load(in_ptr0 + (12 + x0 + 16 * tmp22 + 64 * x2), xmask) tmp35 = tmp33 * tmp34 tmp36 = tmp32 + tmp35 tl.store(out_ptr0 + x3, tmp36, 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, 6, 4), (24, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_index_mul_sum_0[grid(96)](arg0_1, buf0, 96, XBLOCK =128, num_warps=4, num_stages=1) del arg0_1 return buf0, class InnerProductNetworkNew(torch.nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
lipmedusea/pytorch
InnerProductNetwork
false
12,709
[ "MIT" ]
0
5d94694b9e1193a93dd7f75ea2042b5a1cf178bc
https://github.com/lipmedusea/pytorch/tree/5d94694b9e1193a93dd7f75ea2042b5a1cf178bc
FCLateActionSAQFunction
import torch import numpy as np from torch import nn from abc import ABCMeta from abc import abstractmethod import torch.nn.functional as F def init_lecun_normal(tensor, scale=1.0): """Initializes the tensor with LeCunNormal.""" fan_in = torch.nn.init._calculate_correct_fan(tensor, 'fan_in') std = scale * np.sqrt(1.0 / fan_in) with torch.no_grad(): return tensor.normal_(0, std) @torch.no_grad() def init_chainer_default(layer): """Initializes the layer with the chainer default. weights with LeCunNormal(scale=1.0) and zeros as biases """ assert isinstance(layer, nn.Module) if isinstance(layer, (nn.Linear, nn.Conv2d)): init_lecun_normal(layer.weight) if layer.bias is not None: nn.init.zeros_(layer.bias) return layer class MLP(nn.Module): """Multi-Layer Perceptron""" def __init__(self, in_size, out_size, hidden_sizes, nonlinearity=F.relu, last_wscale=1): self.in_size = in_size self.out_size = out_size self.hidden_sizes = hidden_sizes self.nonlinearity = nonlinearity super().__init__() if hidden_sizes: self.hidden_layers = nn.ModuleList() self.hidden_layers.append(nn.Linear(in_size, hidden_sizes[0])) for hin, hout in zip(hidden_sizes, hidden_sizes[1:]): self.hidden_layers.append(nn.Linear(hin, hout)) self.hidden_layers.apply(init_chainer_default) self.output = nn.Linear(hidden_sizes[-1], out_size) else: self.output = nn.Linear(in_size, out_size) init_lecun_normal(self.output.weight, scale=last_wscale) nn.init.zeros_(self.output.bias) def forward(self, x): h = x if self.hidden_sizes: for l in self.hidden_layers: h = self.nonlinearity(l(h)) return self.output(h) class StateActionQFunction(object, metaclass=ABCMeta): """Abstract Q-function with state and action input.""" @abstractmethod def __call__(self, x, a): """Evaluates Q-function Args: x (ndarray): state input a (ndarray): action input Returns: Q-value for state x and action a """ raise NotImplementedError() class FCLateActionSAQFunction(nn.Module, StateActionQFunction): """Fully-connected (s,a)-input Q-function with late action input. Actions are not included until the second hidden layer and not normalized. This architecture is used in the DDPG paper: http://arxiv.org/abs/1509.02971 Args: n_dim_obs (int): Number of dimensions of observation space. n_dim_action (int): Number of dimensions of action space. n_hidden_channels (int): Number of hidden channels. n_hidden_layers (int): Number of hidden layers. It must be greater than or equal to 1. nonlinearity (callable): Nonlinearity between layers. It must accept a Variable as an argument and return a Variable with the same shape. Nonlinearities with learnable parameters such as PReLU are not supported. last_wscale (float): Scale of weight initialization of the last layer. """ def __init__(self, n_dim_obs, n_dim_action, n_hidden_channels, n_hidden_layers, nonlinearity=F.relu, last_wscale=1.0): assert n_hidden_layers >= 1 self.n_input_channels = n_dim_obs + n_dim_action self.n_hidden_layers = n_hidden_layers self.n_hidden_channels = n_hidden_channels self.nonlinearity = nonlinearity super().__init__() self.obs_mlp = MLP(in_size=n_dim_obs, out_size=n_hidden_channels, hidden_sizes=[]) self.mlp = MLP(in_size=n_hidden_channels + n_dim_action, out_size=1, hidden_sizes=[self.n_hidden_channels] * (self.n_hidden_layers - 1), nonlinearity=nonlinearity, last_wscale=last_wscale) self.output = self.mlp.output def forward(self, state, action): h = self.nonlinearity(self.obs_mlp(state)) h = torch.cat((h, action), dim=1) return self.mlp(h) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'n_dim_obs': 4, 'n_dim_action': 4, 'n_hidden_channels': 4, 'n_hidden_layers': 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 from torch._inductor.runtime import triton_helpers import numpy as np from torch import nn from abc import ABCMeta from abc import abstractmethod 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, in_ptr2, 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 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full([1], 0, tl.int32) tmp9 = triton_helpers.maximum(tmp8, tmp7) tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp4, tmp9, tmp10) tmp12 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp15 = tl.load(in_ptr2 + (4 * x1 + (-4 + x0)), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.where(tmp4, tmp11, tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (1, 8), (8, 1)) assert_size_stride(primals_6, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0) del primals_2 buf1 = empty_strided_cuda((4, 8), (8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(32)](buf0, primals_3, primals_4, buf1, 32, XBLOCK=32, num_warps=1, num_stages=1) del primals_4 buf3 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_6, buf1, reinterpret_tensor(primals_5, (8, 1), (1, 8), 0), alpha=1, beta=1, out=buf3) del primals_6 buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(16)](buf0, primals_3, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf0 del primals_3 return buf3, primals_1, buf1, primals_5, buf4 def init_lecun_normal(tensor, scale=1.0): """Initializes the tensor with LeCunNormal.""" fan_in = torch.nn.init._calculate_correct_fan(tensor, 'fan_in') std = scale * np.sqrt(1.0 / fan_in) with torch.no_grad(): return tensor.normal_(0, std) @torch.no_grad() def init_chainer_default(layer): """Initializes the layer with the chainer default. weights with LeCunNormal(scale=1.0) and zeros as biases """ assert isinstance(layer, nn.Module) if isinstance(layer, (nn.Linear, nn.Conv2d)): init_lecun_normal(layer.weight) if layer.bias is not None: nn.init.zeros_(layer.bias) return layer class MLP(nn.Module): """Multi-Layer Perceptron""" def __init__(self, in_size, out_size, hidden_sizes, nonlinearity=F.relu, last_wscale=1): self.in_size = in_size self.out_size = out_size self.hidden_sizes = hidden_sizes self.nonlinearity = nonlinearity super().__init__() if hidden_sizes: self.hidden_layers = nn.ModuleList() self.hidden_layers.append(nn.Linear(in_size, hidden_sizes[0])) for hin, hout in zip(hidden_sizes, hidden_sizes[1:]): self.hidden_layers.append(nn.Linear(hin, hout)) self.hidden_layers.apply(init_chainer_default) self.output = nn.Linear(hidden_sizes[-1], out_size) else: self.output = nn.Linear(in_size, out_size) init_lecun_normal(self.output.weight, scale=last_wscale) nn.init.zeros_(self.output.bias) def forward(self, x): h = x if self.hidden_sizes: for l in self.hidden_layers: h = self.nonlinearity(l(h)) return self.output(h) class StateActionQFunction(object, metaclass=ABCMeta): """Abstract Q-function with state and action input.""" @abstractmethod def __call__(self, x, a): """Evaluates Q-function Args: x (ndarray): state input a (ndarray): action input Returns: Q-value for state x and action a """ raise NotImplementedError() class FCLateActionSAQFunctionNew(nn.Module, StateActionQFunction): """Fully-connected (s,a)-input Q-function with late action input. Actions are not included until the second hidden layer and not normalized. This architecture is used in the DDPG paper: http://arxiv.org/abs/1509.02971 Args: n_dim_obs (int): Number of dimensions of observation space. n_dim_action (int): Number of dimensions of action space. n_hidden_channels (int): Number of hidden channels. n_hidden_layers (int): Number of hidden layers. It must be greater than or equal to 1. nonlinearity (callable): Nonlinearity between layers. It must accept a Variable as an argument and return a Variable with the same shape. Nonlinearities with learnable parameters such as PReLU are not supported. last_wscale (float): Scale of weight initialization of the last layer. """ def __init__(self, n_dim_obs, n_dim_action, n_hidden_channels, n_hidden_layers, nonlinearity=F.relu, last_wscale=1.0): assert n_hidden_layers >= 1 self.n_input_channels = n_dim_obs + n_dim_action self.n_hidden_layers = n_hidden_layers self.n_hidden_channels = n_hidden_channels self.nonlinearity = nonlinearity super().__init__() self.obs_mlp = MLP(in_size=n_dim_obs, out_size=n_hidden_channels, hidden_sizes=[]) self.mlp = MLP(in_size=n_hidden_channels + n_dim_action, out_size=1, hidden_sizes=[self.n_hidden_channels] * (self.n_hidden_layers - 1), nonlinearity=nonlinearity, last_wscale=last_wscale) self.output = self.mlp.output def forward(self, input_0, input_1): primals_1 = self.obs_mlp.output.weight primals_3 = self.obs_mlp.output.bias primals_5 = self.mlp.output.weight primals_6 = self.mlp.output.bias primals_2 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
lin826/pfrl
FCLateActionSAQFunction
false
12,710
[ "MIT" ]
0
62d7f13b854f1879211a386fd870a7db982cc8ec
https://github.com/lin826/pfrl/tree/62d7f13b854f1879211a386fd870a7db982cc8ec
TimeEncode
import torch import numpy as np class TimeEncode(torch.nn.Module): def __init__(self, dimension): super(TimeEncode, self).__init__() self.dimension = dimension self.w = torch.nn.Linear(1, dimension) self.w.weight = torch.nn.Parameter(torch.from_numpy(1 / 10 ** np. linspace(0, 9, dimension)).float().reshape(dimension, -1)) self.w.bias = torch.nn.Parameter(torch.zeros(dimension).float()) def forward(self, t): t = t.unsqueeze(dim=2) output = torch.cos(self.w(t)) return output def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'dimension': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import math as tl_math import numpy as np 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_cos_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 tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl_math.cos(tmp0) tl.store(out_ptr0 + x0, tmp1, 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), (1, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (16, 1), (1, 1), 0), reinterpret_tensor(primals_2, (1, 4), (1, 1), 0 ), alpha=1, beta=1, out=buf0) del primals_2 del primals_3 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cos_0[grid(64)](buf0, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) return buf1, reinterpret_tensor(primals_1, (16, 1), (1, 1), 0), buf0 class TimeEncodeNew(torch.nn.Module): def __init__(self, dimension): super(TimeEncodeNew, self).__init__() self.dimension = dimension self.w = torch.nn.Linear(1, dimension) self.w.weight = torch.nn.Parameter(torch.from_numpy(1 / 10 ** np. linspace(0, 9, dimension)).float().reshape(dimension, -1)) self.w.bias = torch.nn.Parameter(torch.zeros(dimension).float()) def forward(self, input_0): primals_2 = self.w.weight primals_3 = self.w.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
linhthi/tgn
TimeEncode
false
12,711
[ "Apache-2.0" ]
0
bb83f82d89aba07d07da3b173803fb0df32ebbbc
https://github.com/linhthi/tgn/tree/bb83f82d89aba07d07da3b173803fb0df32ebbbc
MergeLayer
import torch class MergeLayer(torch.nn.Module): def __init__(self, dim1, dim2, dim3, dim4): super().__init__() self.fc1 = torch.nn.Linear(dim1 + dim2, dim3) self.fc2 = torch.nn.Linear(dim3, dim4) self.act = torch.nn.ReLU() torch.nn.init.xavier_normal_(self.fc1.weight) torch.nn.init.xavier_normal_(self.fc2.weight) def forward(self, x1, x2): x = torch.cat([x1, x2], dim=1) h = self.act(self.fc1(x)) return self.fc2(h) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'dim1': 4, 'dim2': 4, 'dim3': 4, 'dim4': 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 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 = 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,)) 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.addmm(primals_6, buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_6 return buf3, buf0, buf2, primals_5 class MergeLayerNew(torch.nn.Module): def __init__(self, dim1, dim2, dim3, dim4): super().__init__() self.fc1 = torch.nn.Linear(dim1 + dim2, dim3) self.fc2 = torch.nn.Linear(dim3, dim4) self.act = torch.nn.ReLU() torch.nn.init.xavier_normal_(self.fc1.weight) torch.nn.init.xavier_normal_(self.fc2.weight) def forward(self, input_0, input_1): primals_3 = self.fc1.weight primals_4 = self.fc1.bias primals_1 = self.fc2.weight primals_6 = self.fc2.bias primals_2 = input_0 primals_5 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
linhthi/tgn
MergeLayer
false
12,712
[ "Apache-2.0" ]
0
bb83f82d89aba07d07da3b173803fb0df32ebbbc
https://github.com/linhthi/tgn/tree/bb83f82d89aba07d07da3b173803fb0df32ebbbc
MLP
import torch class MLP(torch.nn.Module): def __init__(self, dim, drop=0.3): super().__init__() self.fc_1 = torch.nn.Linear(dim, 80) self.fc_2 = torch.nn.Linear(80, 10) self.fc_3 = torch.nn.Linear(10, 1) self.act = torch.nn.ReLU() self.dropout = torch.nn.Dropout(p=drop, inplace=False) def forward(self, x): x = self.act(self.fc_1(x)) x = self.dropout(x) x = self.act(self.fc_2(x)) x = self.dropout(x) return self.fc_3(x).squeeze(dim=1) def get_inputs(): return [torch.rand([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 import triton_helpers 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 = 5120 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 80 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 640 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 10 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (80, 4), (4, 1)) assert_size_stride(primals_2, (80,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (10, 80), (80, 1)) assert_size_stride(primals_5, (10,), (1,)) assert_size_stride(primals_6, (1, 10), (10, 1)) assert_size_stride(primals_7, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 80), (80, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 80), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 80), (1280, 320, 80, 1), 0) del buf0 buf7 = empty_strided_cuda((4, 4, 4, 80), (1280, 320, 80, 1), torch.bool ) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(5120)](buf1, primals_2, buf7, 5120, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 10), (10, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 80), (80, 1), 0), reinterpret_tensor(primals_4, (80, 10), (1, 80), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 10), (160, 40, 10, 1), 0) del buf2 buf6 = empty_strided_cuda((4, 4, 4, 10), (160, 40, 10, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(640)](buf3, primals_5, buf6, 640, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 10), (10, 1), 0), reinterpret_tensor(primals_6, (10, 1), (1, 10), 0), alpha=1, beta=1, out=buf5) del primals_7 return reinterpret_tensor(buf5, (4, 4, 4, 1), (16, 4, 1, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 80), (80, 1), 0), reinterpret_tensor( buf3, (64, 10), (10, 1), 0), primals_6, buf6, primals_4, buf7 class MLPNew(torch.nn.Module): def __init__(self, dim, drop=0.3): super().__init__() self.fc_1 = torch.nn.Linear(dim, 80) self.fc_2 = torch.nn.Linear(80, 10) self.fc_3 = torch.nn.Linear(10, 1) self.act = torch.nn.ReLU() self.dropout = torch.nn.Dropout(p=drop, inplace=False) def forward(self, input_0): primals_1 = self.fc_1.weight primals_2 = self.fc_1.bias primals_4 = self.fc_2.weight primals_5 = self.fc_2.bias primals_6 = self.fc_3.weight primals_7 = self.fc_3.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
linhthi/tgn
MLP
false
12,713
[ "Apache-2.0" ]
0
bb83f82d89aba07d07da3b173803fb0df32ebbbc
https://github.com/linhthi/tgn/tree/bb83f82d89aba07d07da3b173803fb0df32ebbbc
ModuleForDdpCommHook
import torch import torch.nn import torch.utils.data.distributed import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.cuda import torch.cuda.nccl import torch.backends.cudnn import torch.backends.mkl class Task(nn.Module): def __init__(self): super().__init__() self.p = nn.Parameter(torch.ones(2, 2)) def forward(self, x): return self.p + x class ModuleForDdpCommHook(nn.Module): def __init__(self): super().__init__() self.t0 = Task() def forward(self, x, rank): return self.t0(x + rank) def get_inputs(): return [torch.rand([4, 4, 2, 2]), torch.rand([4, 4, 2, 2])] 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 import torch.utils.data.distributed import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.cuda import torch.cuda.nccl import torch.backends.cudnn import torch.backends.mkl 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_0(in_ptr0, in_ptr1, in_ptr2, 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 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) tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tl.store(out_ptr0 + x2, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 2, 2), (16, 4, 2, 1)) assert_size_stride(primals_2, (4, 4, 2, 2), (16, 4, 2, 1)) assert_size_stride(primals_3, (2, 2), (2, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_0[grid(64)](primals_3, primals_1, primals_2, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_2 del primals_3 return buf0, class Task(nn.Module): def __init__(self): super().__init__() self.p = nn.Parameter(torch.ones(2, 2)) def forward(self, x): return self.p + x class ModuleForDdpCommHookNew(nn.Module): def __init__(self): super().__init__() self.t0 = Task() def forward(self, input_0, input_1): primals_3 = self.t0.p primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3]) return output[0]
lipovsek/bagua
ModuleForDdpCommHook
false
12,714
[ "MIT" ]
0
d8b03333ab6cf3745279311b9da76e99d5c2c00a
https://github.com/lipovsek/bagua/tree/d8b03333ab6cf3745279311b9da76e99d5c2c00a
RMSEFeaturesLoss
import torch import torch.nn as nn import torch.utils.data def rmseOnFeatures(feature_difference): gt = torch.zeros_like(feature_difference) return torch.nn.functional.mse_loss(feature_difference, gt, size_average=False) class RMSEFeaturesLoss(nn.Module): def __init__(self): super(RMSEFeaturesLoss, self).__init__() def forward(self, feature_difference): return rmseOnFeatures(feature_difference) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_mse_loss_0(in_ptr0, out_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [RBLOCK]) tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0)) tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp4, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_per_fused_mse_loss_0[grid(1)](arg0_1, buf0, 1, 256, num_warps=2, num_stages=1) del arg0_1 return buf0, def rmseOnFeatures(feature_difference): gt = torch.zeros_like(feature_difference) return torch.nn.functional.mse_loss(feature_difference, gt, size_average=False) class RMSEFeaturesLossNew(nn.Module): def __init__(self): super(RMSEFeaturesLossNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
liruihui/learning3d
RMSEFeaturesLoss
false
12,715
[ "MIT" ]
0
d513fb0956926f92c185594d4e236d26ecc7e81e
https://github.com/liruihui/learning3d/tree/d513fb0956926f92c185594d4e236d26ecc7e81e
LNN
import math import torch import torch.utils.data import torch.nn.functional as F class LNN(torch.nn.Module): """ A pytorch implementation of LNN layer Input shape - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 2D tensor with shape:``(batch_size,LNN_dim*embedding_size)``. Arguments - **in_features** : Embedding of feature. - **num_fields**: int.The field size of feature. - **LNN_dim**: int.The number of Logarithmic neuron. - **bias**: bool.Whether or not use bias in LNN. """ def __init__(self, num_fields, embed_dim, LNN_dim, bias=False): super(LNN, self).__init__() self.num_fields = num_fields self.embed_dim = embed_dim self.LNN_dim = LNN_dim self.lnn_output_dim = LNN_dim * embed_dim self.weight = torch.nn.Parameter(torch.Tensor(LNN_dim, num_fields)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(LNN_dim, embed_dim)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): stdv = 1.0 / math.sqrt(self.weight.size(1)) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def forward(self, x): """ :param x: Long tensor of size ``(batch_size, num_fields, embedding_size)`` """ embed_x_abs = torch.abs(x) embed_x_afn = torch.add(embed_x_abs, 1e-07) embed_x_log = torch.log1p(embed_x_afn) lnn_out = torch.matmul(self.weight, embed_x_log) if self.bias is not None: lnn_out += self.bias lnn_exp = torch.expm1(lnn_out) output = F.relu(lnn_exp).contiguous().view(-1, self.lnn_output_dim) return output def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_fields': 4, 'embed_dim': 4, 'LNN_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 math 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 % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tmp1 = tl_math.abs(tmp0) tmp2 = 1e-07 tmp3 = tmp1 + tmp2 tmp4 = libdevice.log1p(tmp3) tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask) @triton.jit def triton_poi_fused_clone_expm1_relu_threshold_backward_1(in_ptr0, 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 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 = libdevice.expm1(tmp0) tmp2 = tl.full([1, 1], 0, tl.int32) tmp3 = triton_helpers.maximum(tmp2, tmp1) tmp4 = 0.0 tmp5 = tmp3 <= tmp4 tl.store(out_ptr0 + (x2 + 4 * y3), tmp3, xmask & ymask) tl.store(out_ptr1 + (x2 + 4 * y3), tmp5, xmask & ymask) 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, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) del primals_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 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_clone_expm1_relu_threshold_backward_1[grid(64, 4)]( buf1, buf2, buf3, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) return reinterpret_tensor(buf2, (16, 16), (16, 1), 0), reinterpret_tensor( buf0, (64, 4), (4, 1), 0), buf1, buf3 class LNNNew(torch.nn.Module): """ A pytorch implementation of LNN layer Input shape - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 2D tensor with shape:``(batch_size,LNN_dim*embedding_size)``. Arguments - **in_features** : Embedding of feature. - **num_fields**: int.The field size of feature. - **LNN_dim**: int.The number of Logarithmic neuron. - **bias**: bool.Whether or not use bias in LNN. """ def __init__(self, num_fields, embed_dim, LNN_dim, bias=False): super(LNNNew, self).__init__() self.num_fields = num_fields self.embed_dim = embed_dim self.LNN_dim = LNN_dim self.lnn_output_dim = LNN_dim * embed_dim self.weight = torch.nn.Parameter(torch.Tensor(LNN_dim, num_fields)) if bias: self.bias = torch.nn.Parameter(torch.Tensor(LNN_dim, embed_dim)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): stdv = 1.0 / math.sqrt(self.weight.size(1)) self.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) def forward(self, input_0): primals_2 = self.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
lipmedusea/pytorch
LNN
false
12,716
[ "MIT" ]
0
5d94694b9e1193a93dd7f75ea2042b5a1cf178bc
https://github.com/lipmedusea/pytorch/tree/5d94694b9e1193a93dd7f75ea2042b5a1cf178bc
ConvNet
import torch import torch.nn import torch.utils.data.distributed import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.cuda import torch.cuda.nccl import torch.backends.cudnn import torch.backends.mkl class ConvNet(nn.Module): def __init__(self, gpus, layouts, dtypes): super(ConvNet, self).__init__() self.dtypes = dtypes if isinstance(gpus, list): self.layer_gpus = gpus else: gpus = [gpus] * 4 self.conv0 = torch.nn.Conv2d(8, 16, (2, 2)) self.conv1 = torch.nn.Conv2d(16, 32, (2, 2)) self.conv2 = torch.nn.Conv2d(32, 16, (2, 2)) self.conv3 = torch.nn.Conv2d(16, 8, (2, 2)) def forward(self, x): x = x self.layer_gpus if hasattr(self, 'layer_gpus') else [x.device] * 4 x = self.conv0(x) x = self.conv1(x) x = self.conv2(x) return self.conv3(x) def get_inputs(): return [torch.rand([4, 8, 64, 64])] def get_init_inputs(): return [[], {'gpus': False, 'layouts': 4, 'dtypes': torch.float32}]
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 import torch.utils.data.distributed import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.cuda import torch.cuda.nccl import torch.backends.cudnn import torch.backends.mkl 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): xnumel = 254016 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3969 % 16 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_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 492032 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3844 % 32 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_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 238144 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3721 % 16 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_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 115200 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3600 % 8 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) = args args.clear() assert_size_stride(primals_1, (4, 8, 64, 64), (32768, 4096, 64, 1)) assert_size_stride(primals_2, (16, 8, 2, 2), (32, 4, 2, 1)) assert_size_stride(primals_3, (16,), (1,)) assert_size_stride(primals_4, (32, 16, 2, 2), (64, 4, 2, 1)) assert_size_stride(primals_5, (32,), (1,)) assert_size_stride(primals_6, (16, 32, 2, 2), (128, 4, 2, 1)) assert_size_stride(primals_7, (16,), (1,)) assert_size_stride(primals_8, (8, 16, 2, 2), (64, 4, 2, 1)) assert_size_stride(primals_9, (8,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 16, 63, 63), (63504, 3969, 63, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(254016)](buf1, primals_3, 254016, XBLOCK=1024, num_warps=4, num_stages=1) del primals_3 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, 32, 62, 62), (123008, 3844, 62, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_1[grid(492032)](buf3, primals_5, 492032, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 16, 61, 61), (59536, 3721, 61, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_2[grid(238144)](buf5, primals_7, 238144, XBLOCK=512, num_warps=8, num_stages=1) del primals_7 buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 8, 60, 60), (28800, 3600, 60, 1)) buf7 = buf6 del buf6 triton_poi_fused_convolution_3[grid(115200)](buf7, primals_9, 115200, XBLOCK=1024, num_warps=4, num_stages=1) del primals_9 return (buf7, primals_1, primals_2, primals_4, primals_6, primals_8, buf1, buf3, buf5) class ConvNetNew(nn.Module): def __init__(self, gpus, layouts, dtypes): super(ConvNetNew, self).__init__() self.dtypes = dtypes if isinstance(gpus, list): self.layer_gpus = gpus else: gpus = [gpus] * 4 self.conv0 = torch.nn.Conv2d(8, 16, (2, 2)) self.conv1 = torch.nn.Conv2d(16, 32, (2, 2)) self.conv2 = torch.nn.Conv2d(32, 16, (2, 2)) self.conv3 = torch.nn.Conv2d(16, 8, (2, 2)) def forward(self, input_0): primals_2 = self.conv0.weight primals_3 = 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_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]
lipovsek/bagua
ConvNet
false
12,717
[ "MIT" ]
0
d8b03333ab6cf3745279311b9da76e99d5c2c00a
https://github.com/lipovsek/bagua/tree/d8b03333ab6cf3745279311b9da76e99d5c2c00a
Task
import torch import torch.nn import torch.utils.data.distributed import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.cuda import torch.cuda.nccl import torch.backends.cudnn import torch.backends.mkl class Task(nn.Module): def __init__(self): super().__init__() self.p = nn.Parameter(torch.ones(2, 2)) def forward(self, x): return self.p + x def get_inputs(): return [torch.rand([4, 4, 2, 2])] 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 import torch.utils.data.distributed import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.cuda import torch.cuda.nccl import torch.backends.cudnn import torch.backends.mkl 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_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 x2 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask) tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (2, 2), (2, 1)) assert_size_stride(primals_2, (4, 4, 2, 2), (16, 4, 2, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_0[grid(64)](primals_1, primals_2, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_2 return buf0, class TaskNew(nn.Module): def __init__(self): super().__init__() self.p = nn.Parameter(torch.ones(2, 2)) def forward(self, input_0): primals_1 = self.p primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
lipovsek/bagua
Task
false
12,718
[ "MIT" ]
0
d8b03333ab6cf3745279311b9da76e99d5c2c00a
https://github.com/lipovsek/bagua/tree/d8b03333ab6cf3745279311b9da76e99d5c2c00a
EncoderLayer
import math import torch import torch.nn as nn from typing import Optional from typing import List class FeedForward(nn.Module): """ ## FFN module """ def __init__(self, d_model: 'int', d_ff: 'int', dropout: 'float'=0.1, activation=nn.ReLU(), is_gated: 'bool'=False, bias: 'bool'=True, bias_gate: 'bool'=True): """ * d_model is the number of features * d_ff is the number of features in the hidden layer of the FFN * dropout is dropout probability for the hidden layer * is_gated specifies whether the hidden layer is gated * bias1 specified whether the first fully connected layer should have a learnable bias * bias2 specified whether the second fully connected layer should have a learnable bias * bias_gate specified whether the fully connected layer for the gate should have a learnable bias """ super(FeedForward, self).__init__() self.layer1 = nn.Linear(d_model, d_ff, bias=bias) self.layer2 = nn.Linear(d_ff, d_model, bias=bias) self.dropout = nn.Dropout(dropout) self.activation = activation self.is_gated = is_gated if is_gated: self.linear_v = nn.Linear(d_model, d_ff, bias=bias_gate) def forward(self, x: 'torch.Tensor'): g = self.activation(self.layer1(x)) if self.is_gated: x = g * self.linear_v(x) else: x = g x = self.dropout(x) return self.layer2(x) class PrepareForMultiHeadAttention(nn.Module): """ ## Prepare for multi-head attention 这个linear transform作用是把query,key,value映射到同一个低维空间内 This module does a linear transformation and splits the vector into given number of heads for multi-head attention. This is used to transform **key**, **query**, and **value** vectors. """ def __init__(self, d_model: 'int', heads: 'int', d_k: 'int', bias: 'bool'): super(PrepareForMultiHeadAttention, self).__init__() self.linear = nn.Linear(d_model, heads * d_k, bias=bias) self.heads = heads self.d_k = d_k def forward(self, x: 'torch.Tensor'): head_shape = x.shape[:-1] x = self.linear(x) x = x.view(*head_shape, self.heads, self.d_k) return x class MultiHeadAttention(nn.Module): """ This computes scaled multi-headed attention for given query, key and value vectors. compute similatiry between query and key, use this as attention efficient multiply value It uses dot-product of query and key as the indicator of how matching they are. Before taking the $softmax$ the dot-products are scaled by $\\frac{1}{\\sqrt{d_k}}$. This is done to avoid large dot-product values causing softmax to give very small gradients when $d_k$ is large. Softmax is calculated along the axis of of the sequence (or time). """ def __init__(self, heads: 'int', d_model: 'int', dropout_prob: 'float'= 0.1, bias: 'bool'=True): """ * heads is the number of heads. * d_model is the number of features in the query, key and value vectors. """ super(MultiHeadAttention, self).__init__() self.d_k = d_model // heads self.heads = heads self.query = PrepareForMultiHeadAttention(d_model, heads, self.d_k, bias=bias) self.key = PrepareForMultiHeadAttention(d_model, heads, self.d_k, bias=bias) self.value = PrepareForMultiHeadAttention(d_model, heads, self.d_k, bias=True) self.softmax = nn.Softmax(dim=1) self.output = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout_prob) self.scale = 1 / math.sqrt(self.d_k) self.attn = None def get_scores(self, query: 'torch.Tensor', key: 'torch.Tensor'): """ ### Calculate scores between queries and keys,使用的是点积的方法 还可以有cosine,MLP等计算相似度的方法 """ return torch.einsum('ibhd,jbhd->ijbh', query, key) def prepare_mask(self, mask: 'torch.Tensor', query_shape: 'List[int]', key_shape: 'List[int]'): """ mask has shape [seq_len_q, seq_len_k, batch_size], where first dimension is the query dimension. If the query dimension is equal to $1$ it will be broadcasted. """ assert mask.shape[0] == 1 or mask.shape[0] == query_shape[0] assert mask.shape[1] == key_shape[0] assert mask.shape[2] == 1 or mask.shape[2] == query_shape[1] mask = mask.unsqueeze(-1) return mask def forward(self, *, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: Optional[torch.Tensor]=None): seq_len, batch_size, _ = query.shape if mask is not None: mask = self.prepare_mask(mask, query.shape, key.shape) query = self.query(query) key = self.key(key) value = self.value(value) scores = self.get_scores(query, key) scores = scores * self.scale if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) attn = self.softmax(scores) attn = self.dropout(attn) x = torch.einsum('ijbh,jbhd->ibhd', attn, value) self.attn = attn.detach() x = x.reshape(seq_len, batch_size, -1) return self.output(x) class EncoderLayer(nn.Module): def __init__(self, d_model: 'int', d_ff: 'int', heads: 'int', bias: 'bool'=True, is_gated: 'bool'=False, bias_gate: 'bool'=True, activation=nn.ELU(), dropout_prob: 'float'=0.1): super(EncoderLayer, self).__init__() self.attn = MultiHeadAttention(heads, d_model, dropout_prob, bias) self.feed_forward = FeedForward(d_model, d_ff, dropout_prob, activation, is_gated, bias, bias_gate) self.dropout = nn.Dropout(dropout_prob) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) def forward(self, x): z = self.norm1(x) a = self.attn(query=z, key=z, value=z) x = x + self.dropout(a) z = self.norm2(x) a = self.feed_forward(z) x = x + self.dropout(a) return x def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'d_model': 4, 'd_ff': 4, '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 torch.nn as nn from typing import Optional 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_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-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_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__softmax_2(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 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr1 + (16 + x0), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr1 + (32 + x0), xmask, eviction_policy='evict_last') tmp13 = tl.load(in_ptr1 + (48 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tmp6 = tmp0 * tmp5 tmp7 = tmp6 * tmp3 tmp8 = triton_helpers.maximum(tmp4, tmp7) tmp10 = tmp0 * tmp9 tmp11 = tmp10 * tmp3 tmp12 = triton_helpers.maximum(tmp8, tmp11) tmp14 = tmp0 * tmp13 tmp15 = tmp14 * tmp3 tmp16 = triton_helpers.maximum(tmp12, tmp15) tmp17 = tmp4 - tmp16 tmp18 = tmp17 * tmp3 tmp19 = tl_math.exp(tmp18) tmp20 = tmp7 - tmp16 tmp21 = tmp20 * tmp3 tmp22 = tl_math.exp(tmp21) tmp23 = tmp19 + tmp22 tmp24 = tmp11 - tmp16 tmp25 = tmp24 * tmp3 tmp26 = tl_math.exp(tmp25) tmp27 = tmp23 + tmp26 tmp28 = tmp15 - tmp16 tmp29 = tmp28 * tmp3 tmp30 = tl_math.exp(tmp29) tmp31 = tmp27 + tmp30 tl.store(out_ptr0 + x2, tmp16, xmask) tl.store(out_ptr1 + x2, tmp31, xmask) @triton.jit def triton_poi_fused__softmax_3(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 x0 = xindex % 16 x2 = xindex // 64 x3 = xindex % 64 x4 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr3 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 * tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tmp6 = tmp4 - tmp5 tmp7 = tmp6 * tmp3 tmp8 = tl_math.exp(tmp7) tmp10 = tmp8 / tmp9 tl.store(out_ptr0 + x4, tmp10, xmask) @triton.jit def triton_poi_fused_clone_4(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_5(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_6(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-05 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_elu_7(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 + x0, xmask) tmp1 = 0.0 tmp2 = tmp0 > tmp1 tmp3 = 1.0 tmp4 = tmp0 * tmp3 tmp5 = libdevice.expm1(tmp4) tmp6 = tmp5 * tmp3 tmp7 = tl.where(tmp2, tmp4, tmp6) tl.store(out_ptr0 + x0, tmp7, xmask) @triton.jit def triton_poi_fused_add_8(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, primals_15, primals_16, primals_17) = 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, 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, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 4), (4, 1)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (4,), (1,)) assert_size_stride(primals_13, (4,), (1,)) assert_size_stride(primals_14, (4, 4), (4, 1)) assert_size_stride(primals_15, (4,), (1,)) assert_size_stride(primals_16, (4, 4), (4, 1)) assert_size_stride(primals_17, (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((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, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_2 buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (16, 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((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf2, (16, 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((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_9, reinterpret_tensor(buf2, (16, 4), ( 4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf5) del primals_9 buf6 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) buf7 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) triton_poi_fused__softmax_2[grid(64)](buf3, buf4, buf6, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1) buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_3[grid(256)](buf3, buf4, buf6, buf7, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1) buf9 = reinterpret_tensor(buf7, (16, 4, 1), (4, 1, 1), 0) del buf7 extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (1, 64, 16), 0), reinterpret_tensor(buf5, (16, 4, 1), (1, 16, 0), 0), out=buf9) buf10 = reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0) del buf6 triton_poi_fused_clone_4[grid(4, 16)](buf9, buf10, 4, 16, XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1) buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0) del buf9 extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf11) buf12 = buf1 del buf1 buf13 = buf0 del buf0 triton_poi_fused_add_native_layer_norm_5[grid(16)](primals_3, buf11, primals_11, buf12, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1) buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_6[grid(64)](primals_3, buf11, primals_11, buf12, buf13, primals_12, primals_13, buf14, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf12 del buf13 del primals_13 buf15 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_15, reinterpret_tensor(buf14, (16, 4), (4, 1), 0), reinterpret_tensor(primals_14, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf15) del primals_15 buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_elu_7[grid(64)](buf15, buf16, 64, XBLOCK=64, num_warps=1, num_stages=1) buf17 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf16, (16, 4), (4, 1), 0), reinterpret_tensor(primals_16, (4, 4), (1, 4), 0), out=buf17) buf18 = reinterpret_tensor(buf17, (4, 4, 4), (16, 4, 1), 0) del buf17 triton_poi_fused_add_8[grid(64)](buf18, primals_3, buf11, primals_11, primals_17, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_17 return buf18, buf8, primals_3, primals_11, primals_12, reinterpret_tensor( buf2, (16, 4), (4, 1), 0), buf3, buf4, buf8, reinterpret_tensor(buf10, (16, 4), (4, 1), 0), buf11, reinterpret_tensor(buf14, (16, 4), (4, 1), 0), buf15, reinterpret_tensor(buf16, (16, 4), (4, 1), 0 ), primals_16, primals_14, primals_10, reinterpret_tensor(buf5, (16, 1, 4), (1, 1, 16), 0), primals_8, primals_6, primals_4 class FeedForward(nn.Module): """ ## FFN module """ def __init__(self, d_model: 'int', d_ff: 'int', dropout: 'float'=0.1, activation=nn.ReLU(), is_gated: 'bool'=False, bias: 'bool'=True, bias_gate: 'bool'=True): """ * d_model is the number of features * d_ff is the number of features in the hidden layer of the FFN * dropout is dropout probability for the hidden layer * is_gated specifies whether the hidden layer is gated * bias1 specified whether the first fully connected layer should have a learnable bias * bias2 specified whether the second fully connected layer should have a learnable bias * bias_gate specified whether the fully connected layer for the gate should have a learnable bias """ super(FeedForward, self).__init__() self.layer1 = nn.Linear(d_model, d_ff, bias=bias) self.layer2 = nn.Linear(d_ff, d_model, bias=bias) self.dropout = nn.Dropout(dropout) self.activation = activation self.is_gated = is_gated if is_gated: self.linear_v = nn.Linear(d_model, d_ff, bias=bias_gate) def forward(self, x: 'torch.Tensor'): g = self.activation(self.layer1(x)) if self.is_gated: x = g * self.linear_v(x) else: x = g x = self.dropout(x) return self.layer2(x) class PrepareForMultiHeadAttention(nn.Module): """ ## Prepare for multi-head attention 这个linear transform作用是把query,key,value映射到同一个低维空间内 This module does a linear transformation and splits the vector into given number of heads for multi-head attention. This is used to transform **key**, **query**, and **value** vectors. """ def __init__(self, d_model: 'int', heads: 'int', d_k: 'int', bias: 'bool'): super(PrepareForMultiHeadAttention, self).__init__() self.linear = nn.Linear(d_model, heads * d_k, bias=bias) self.heads = heads self.d_k = d_k def forward(self, x: 'torch.Tensor'): head_shape = x.shape[:-1] x = self.linear(x) x = x.view(*head_shape, self.heads, self.d_k) return x class MultiHeadAttention(nn.Module): """ This computes scaled multi-headed attention for given query, key and value vectors. compute similatiry between query and key, use this as attention efficient multiply value It uses dot-product of query and key as the indicator of how matching they are. Before taking the $softmax$ the dot-products are scaled by $\\frac{1}{\\sqrt{d_k}}$. This is done to avoid large dot-product values causing softmax to give very small gradients when $d_k$ is large. Softmax is calculated along the axis of of the sequence (or time). """ def __init__(self, heads: 'int', d_model: 'int', dropout_prob: 'float'= 0.1, bias: 'bool'=True): """ * heads is the number of heads. * d_model is the number of features in the query, key and value vectors. """ super(MultiHeadAttention, self).__init__() self.d_k = d_model // heads self.heads = heads self.query = PrepareForMultiHeadAttention(d_model, heads, self.d_k, bias=bias) self.key = PrepareForMultiHeadAttention(d_model, heads, self.d_k, bias=bias) self.value = PrepareForMultiHeadAttention(d_model, heads, self.d_k, bias=True) self.softmax = nn.Softmax(dim=1) self.output = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout_prob) self.scale = 1 / math.sqrt(self.d_k) self.attn = None def get_scores(self, query: 'torch.Tensor', key: 'torch.Tensor'): """ ### Calculate scores between queries and keys,使用的是点积的方法 还可以有cosine,MLP等计算相似度的方法 """ return torch.einsum('ibhd,jbhd->ijbh', query, key) def prepare_mask(self, mask: 'torch.Tensor', query_shape: 'List[int]', key_shape: 'List[int]'): """ mask has shape [seq_len_q, seq_len_k, batch_size], where first dimension is the query dimension. If the query dimension is equal to $1$ it will be broadcasted. """ assert mask.shape[0] == 1 or mask.shape[0] == query_shape[0] assert mask.shape[1] == key_shape[0] assert mask.shape[2] == 1 or mask.shape[2] == query_shape[1] mask = mask.unsqueeze(-1) return mask def forward(self, *, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: Optional[torch.Tensor]=None): seq_len, batch_size, _ = query.shape if mask is not None: mask = self.prepare_mask(mask, query.shape, key.shape) query = self.query(query) key = self.key(key) value = self.value(value) scores = self.get_scores(query, key) scores = scores * self.scale if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) attn = self.softmax(scores) attn = self.dropout(attn) x = torch.einsum('ijbh,jbhd->ibhd', attn, value) self.attn = attn.detach() x = x.reshape(seq_len, batch_size, -1) return self.output(x) class EncoderLayerNew(nn.Module): def __init__(self, d_model: 'int', d_ff: 'int', heads: 'int', bias: 'bool'=True, is_gated: 'bool'=False, bias_gate: 'bool'=True, activation=nn.ELU(), dropout_prob: 'float'=0.1): super(EncoderLayerNew, self).__init__() self.attn = MultiHeadAttention(heads, d_model, dropout_prob, bias) self.feed_forward = FeedForward(d_model, d_ff, dropout_prob, activation, is_gated, bias, bias_gate) self.dropout = nn.Dropout(dropout_prob) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) def forward(self, input_0): primals_4 = self.attn.query.linear.weight primals_1 = self.attn.query.linear.bias primals_6 = self.attn.key.linear.weight primals_2 = self.attn.key.linear.bias primals_8 = self.attn.value.linear.weight primals_5 = self.attn.value.linear.bias primals_10 = self.attn.output.weight primals_7 = self.attn.output.bias primals_14 = self.feed_forward.layer1.weight primals_9 = self.feed_forward.layer1.bias primals_16 = self.feed_forward.layer2.weight primals_11 = self.feed_forward.layer2.bias primals_12 = self.norm1.weight primals_13 = self.norm1.bias primals_15 = self.norm2.weight primals_17 = self.norm2.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]
jamesYu365/Transfomer-example
EncoderLayer
false
12,720
[ "MIT" ]
0
a867f72f539de9746668da411f524dab45ddf12f
https://github.com/jamesYu365/Transfomer-example/tree/a867f72f539de9746668da411f524dab45ddf12f
AGRUCell
import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import * class AGRUCell(nn.Module): """ Attention based GRU (AGRU) Reference: - Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018. """ def __init__(self, input_size, hidden_size, bias=True): super(AGRUCell, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.weight_ih = nn.Parameter(torch.Tensor(3 * hidden_size, input_size) ) self.register_parameter('weight_ih', self.weight_ih) self.weight_hh = nn.Parameter(torch.Tensor(3 * hidden_size, hidden_size)) self.register_parameter('weight_hh', self.weight_hh) if bias: self.bias_ih = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_ih', self.bias_ih) self.bias_hh = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_hh', self.bias_hh) for tensor in [self.bias_ih, self.bias_hh]: nn.init.zeros_(tensor) else: self.register_parameter('bias_ih', None) self.register_parameter('bias_hh', None) def forward(self, input, hx, att_score): gi = F.linear(input, self.weight_ih, self.bias_ih) gh = F.linear(hx, self.weight_hh, self.bias_hh) i_r, _i_z, i_n = gi.chunk(3, 1) h_r, _h_z, h_n = gh.chunk(3, 1) reset_gate = torch.sigmoid(i_r + h_r) new_state = torch.tanh(i_n + reset_gate * h_n) att_score = att_score.view(-1, 1) hy = (1.0 - att_score) * hx + att_score * new_state return hy def get_inputs(): return [torch.rand([16, 4]), torch.rand([16, 4]), torch.rand([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.triton_helpers import libdevice import torch.nn as nn from sklearn.metrics import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_add_mul_rsub_sigmoid_tanh_tanh_backward_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 12 * x1), xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + (x0 + 12 * x1), xmask) tmp6 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr4 + x2, xmask) tmp11 = tl.load(in_ptr0 + (8 + x0 + 12 * x1), xmask) tmp12 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last') tmp14 = tl.load(in_ptr2 + (8 + x0 + 12 * x1), xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp5 = tl.sigmoid(tmp4) tmp7 = 1.0 tmp8 = tmp7 - tmp6 tmp10 = tmp8 * tmp9 tmp13 = tmp11 + tmp12 tmp15 = tmp5 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = libdevice.tanh(tmp16) tmp18 = tmp6 * tmp17 tmp19 = tmp10 + tmp18 tmp20 = tmp17 * tmp17 tmp21 = tmp7 - tmp20 tl.store(out_ptr0 + x2, tmp5, xmask) tl.store(out_ptr1 + x2, tmp19, xmask) tl.store(out_ptr2 + x2, tmp21, 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, (12, 4), (4, 1)) assert_size_stride(primals_2, (12,), (1,)) assert_size_stride(primals_3, (16, 4), (4, 1)) assert_size_stride(primals_4, (12, 4), (4, 1)) assert_size_stride(primals_5, (12,), (1,)) assert_size_stride(primals_6, (16, 4), (4, 1)) assert_size_stride(primals_7, (4, 4), (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(primals_3, reinterpret_tensor(primals_1, (4, 12), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 12), (12, 1), torch.float32) extern_kernels.addmm(primals_5, primals_6, reinterpret_tensor( primals_4, (4, 12), (1, 4), 0), alpha=1, beta=1, out=buf1) del primals_4 del primals_5 buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32) buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_rsub_sigmoid_tanh_tanh_backward_0[grid(64)]( buf0, primals_2, buf1, primals_7, primals_6, buf2, buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 del primals_2 return buf3, primals_3, primals_6, primals_7, reinterpret_tensor(buf1, (16, 4), (12, 1), 8), buf2, buf4 class AGRUCellNew(nn.Module): """ Attention based GRU (AGRU) Reference: - Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018. """ def __init__(self, input_size, hidden_size, bias=True): super(AGRUCellNew, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.weight_ih = nn.Parameter(torch.Tensor(3 * hidden_size, input_size) ) self.register_parameter('weight_ih', self.weight_ih) self.weight_hh = nn.Parameter(torch.Tensor(3 * hidden_size, hidden_size)) self.register_parameter('weight_hh', self.weight_hh) if bias: self.bias_ih = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_ih', self.bias_ih) self.bias_hh = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_hh', self.bias_hh) for tensor in [self.bias_ih, self.bias_hh]: nn.init.zeros_(tensor) else: self.register_parameter('bias_ih', None) self.register_parameter('bias_hh', None) def forward(self, input_0, input_1, input_2): primals_1 = self.weight_ih primals_4 = self.weight_hh primals_2 = self.bias_ih primals_5 = self.bias_hh primals_3 = input_0 primals_6 = input_1 primals_7 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
liyunrui/DeepCTR-Torch
AGRUCell
false
12,721
[ "Apache-2.0" ]
0
392fd6d39d9ca0ac854022136cdb4d5c68e3a592
https://github.com/liyunrui/DeepCTR-Torch/tree/392fd6d39d9ca0ac854022136cdb4d5c68e3a592
CosineBasisLinear
import torch import numpy as np from torch import nn def cosine_basis_functions(x, n_basis_functions=64): """Cosine basis functions used to embed quantile thresholds. Args: x (torch.Tensor): Input. n_basis_functions (int): Number of cosine basis functions. Returns: ndarray: Embedding with shape of (x.shape + (n_basis_functions,)). """ i_pi = torch.arange(1, n_basis_functions + 1, dtype=torch.float, device =x.device) * np.pi embedding = torch.cos(x[..., None] * i_pi) assert embedding.shape == x.shape + (n_basis_functions,) return embedding class CosineBasisLinear(nn.Module): """Linear layer following cosine basis functions. Args: n_basis_functions (int): Number of cosine basis functions. out_size (int): Output size. """ def __init__(self, n_basis_functions, out_size): super().__init__() self.linear = nn.Linear(n_basis_functions, out_size) self.n_basis_functions = n_basis_functions self.out_size = out_size def forward(self, x): """Evaluate. Args: x (torch.Tensor): Input. Returns: torch.Tensor: Output with shape of (x.shape + (out_size,)). """ h = cosine_basis_functions(x, self.n_basis_functions) h = h.reshape(-1, self.n_basis_functions) out = self.linear(h) out = out.reshape(*x.shape, self.out_size) return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'n_basis_functions': 4, 'out_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 math as tl_math import numpy as np 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_arange_cos_mul_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 // 4 x0 = xindex % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp1 = 1 + x0 tmp2 = tmp1.to(tl.float32) tmp3 = 3.141592653589793 tmp4 = tmp2 * tmp3 tmp5 = tmp0 * tmp4 tmp6 = tl_math.cos(tmp5) tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 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, 4, 4), (256, 64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_arange_cos_mul_0[grid(1024)](primals_1, buf0, 1024, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((256, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (256, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1) del primals_2 del primals_3 return reinterpret_tensor(buf1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0 ), reinterpret_tensor(buf0, (256, 4), (4, 1), 0) def cosine_basis_functions(x, n_basis_functions=64): """Cosine basis functions used to embed quantile thresholds. Args: x (torch.Tensor): Input. n_basis_functions (int): Number of cosine basis functions. Returns: ndarray: Embedding with shape of (x.shape + (n_basis_functions,)). """ i_pi = torch.arange(1, n_basis_functions + 1, dtype=torch.float, device =x.device) * np.pi embedding = torch.cos(x[..., None] * i_pi) assert embedding.shape == x.shape + (n_basis_functions,) return embedding class CosineBasisLinearNew(nn.Module): """Linear layer following cosine basis functions. Args: n_basis_functions (int): Number of cosine basis functions. out_size (int): Output size. """ def __init__(self, n_basis_functions, out_size): super().__init__() self.linear = nn.Linear(n_basis_functions, out_size) self.n_basis_functions = n_basis_functions self.out_size = out_size def forward(self, input_0): primals_2 = self.linear.weight primals_3 = self.linear.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
lin826/pfrl
CosineBasisLinear
false
12,722
[ "MIT" ]
0
62d7f13b854f1879211a386fd870a7db982cc8ec
https://github.com/lin826/pfrl/tree/62d7f13b854f1879211a386fd870a7db982cc8ec
FM
import torch import torch.nn as nn from sklearn.metrics import * class FM(nn.Module): """Factorization Machine models pairwise (order-2) feature interactions without linear term and bias. Input shape - 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 2D tensor with shape: ``(batch_size, 1)``. References - [Factorization Machines](https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf) """ def __init__(self): super(FM, self).__init__() def forward(self, inputs): fm_input = inputs square_of_sum = torch.pow(torch.sum(fm_input, dim=1, keepdim=True), 2) sum_of_square = torch.sum(fm_input * fm_input, dim=1, keepdim=True) cross_term = square_of_sum - sum_of_square cross_term = 0.5 * torch.sum(cross_term, dim=2, keepdim=False) return cross_term 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 from sklearn.metrics import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_mul_pow_sub_sum_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 % 4 x1 = xindex // 4 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) tmp16 = tl.load(in_ptr0 + (4 + x0 + 64 * x1), xmask) tmp17 = tl.load(in_ptr0 + (20 + x0 + 64 * x1), xmask) tmp19 = tl.load(in_ptr0 + (36 + x0 + 64 * x1), xmask) tmp21 = tl.load(in_ptr0 + (52 + x0 + 64 * x1), xmask) tmp33 = tl.load(in_ptr0 + (8 + x0 + 64 * x1), xmask) tmp34 = tl.load(in_ptr0 + (24 + x0 + 64 * x1), xmask) tmp36 = tl.load(in_ptr0 + (40 + x0 + 64 * x1), xmask) tmp38 = tl.load(in_ptr0 + (56 + x0 + 64 * x1), xmask) tmp50 = tl.load(in_ptr0 + (12 + x0 + 64 * x1), xmask) tmp51 = tl.load(in_ptr0 + (28 + x0 + 64 * x1), xmask) tmp53 = tl.load(in_ptr0 + (44 + x0 + 64 * x1), xmask) tmp55 = tl.load(in_ptr0 + (60 + x0 + 64 * x1), xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = tmp6 * tmp6 tmp8 = tmp0 * tmp0 tmp9 = tmp1 * tmp1 tmp10 = tmp8 + tmp9 tmp11 = tmp3 * tmp3 tmp12 = tmp10 + tmp11 tmp13 = tmp5 * tmp5 tmp14 = tmp12 + tmp13 tmp15 = tmp7 - tmp14 tmp18 = tmp16 + tmp17 tmp20 = tmp18 + tmp19 tmp22 = tmp20 + tmp21 tmp23 = tmp22 * tmp22 tmp24 = tmp16 * tmp16 tmp25 = tmp17 * tmp17 tmp26 = tmp24 + tmp25 tmp27 = tmp19 * tmp19 tmp28 = tmp26 + tmp27 tmp29 = tmp21 * tmp21 tmp30 = tmp28 + tmp29 tmp31 = tmp23 - tmp30 tmp32 = tmp15 + tmp31 tmp35 = tmp33 + tmp34 tmp37 = tmp35 + tmp36 tmp39 = tmp37 + tmp38 tmp40 = tmp39 * tmp39 tmp41 = tmp33 * tmp33 tmp42 = tmp34 * tmp34 tmp43 = tmp41 + tmp42 tmp44 = tmp36 * tmp36 tmp45 = tmp43 + tmp44 tmp46 = tmp38 * tmp38 tmp47 = tmp45 + tmp46 tmp48 = tmp40 - tmp47 tmp49 = tmp32 + tmp48 tmp52 = tmp50 + tmp51 tmp54 = tmp52 + tmp53 tmp56 = tmp54 + tmp55 tmp57 = tmp56 * tmp56 tmp58 = tmp50 * tmp50 tmp59 = tmp51 * tmp51 tmp60 = tmp58 + tmp59 tmp61 = tmp53 * tmp53 tmp62 = tmp60 + tmp61 tmp63 = tmp55 * tmp55 tmp64 = tmp62 + tmp63 tmp65 = tmp57 - tmp64 tmp66 = tmp49 + tmp65 tmp67 = 0.5 tmp68 = tmp66 * tmp67 tl.store(in_out_ptr0 + x2, tmp68, 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, 4), (4, 16, 1), torch.float32) buf1 = reinterpret_tensor(buf0, (4, 1, 4), (4, 4, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_mul_pow_sub_sum_0[grid(16)](buf1, arg0_1, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return buf1, class FMNew(nn.Module): """Factorization Machine models pairwise (order-2) feature interactions without linear term and bias. Input shape - 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 2D tensor with shape: ``(batch_size, 1)``. References - [Factorization Machines](https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf) """ def __init__(self): super(FMNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
liyunrui/DeepCTR-Torch
FM
false
12,723
[ "Apache-2.0" ]
0
392fd6d39d9ca0ac854022136cdb4d5c68e3a592
https://github.com/liyunrui/DeepCTR-Torch/tree/392fd6d39d9ca0ac854022136cdb4d5c68e3a592
CrossEntropyLossLabelSmoothing
import torch import torch.utils.data from torch import nn import torch.nn.functional as F def _is_long(x): if hasattr(x, 'data'): x = x.data return isinstance(x, torch.LongTensor) or isinstance(x, torch.LongTensor) def onehot(indexes, N=None, ignore_index=None): """ Creates a one-representation of indexes with N possible entries if N is not specified, it will suit the maximum index appearing. indexes is a long-tensor of indexes ignore_index will be zero in onehot representation """ if N is None: N = indexes.max() + 1 sz = list(indexes.size()) output = indexes.new().byte().resize_(*sz, N).zero_() output.scatter_(-1, indexes.unsqueeze(-1), 1) if ignore_index is not None and ignore_index >= 0: output.masked_fill_(indexes.eq(ignore_index).unsqueeze(-1), 0) return output def cross_entropy_label_smoothing(inputs, target, weight=None, ignore_index =-100, reduction='mean', smooth_eps=None, smooth_dist=None, from_logits =True): """cross entropy loss, with support for target distributions and label smoothing https://arxiv.org/abs/1512.00567""" smooth_eps = smooth_eps or 0 if _is_long(target) and smooth_eps == 0: if from_logits: return F.cross_entropy(inputs, target, weight, ignore_index= ignore_index, reduction=reduction) else: return F.nll_loss(inputs, target, weight, ignore_index= ignore_index, reduction=reduction) if from_logits: lsm = F.log_softmax(inputs, dim=-1) else: lsm = inputs masked_indices = None num_classes = inputs.size(-1) if _is_long(target) and ignore_index >= 0: masked_indices = target.eq(ignore_index) if smooth_eps > 0 and smooth_dist is not None: if _is_long(target): target = onehot(target, num_classes).type_as(inputs) if smooth_dist.dim() < target.dim(): smooth_dist = smooth_dist.unsqueeze(0) target.lerp_(smooth_dist, smooth_eps) if weight is not None: lsm = lsm * weight.unsqueeze(0) if _is_long(target): eps_sum = smooth_eps / num_classes eps_nll = 1.0 - eps_sum - smooth_eps likelihood = lsm.gather(dim=-1, index=target.unsqueeze(-1)).squeeze(-1) loss = -(eps_nll * likelihood + eps_sum * lsm.sum(-1)) else: loss = -(target * lsm).sum(-1) if masked_indices is not None: loss.masked_fill_(masked_indices, 0) if reduction == 'sum': loss = loss.sum() elif reduction == 'mean': if masked_indices is None: loss = loss.mean() else: loss = loss.sum() / float(loss.size(0) - masked_indices.sum()) return loss class CrossEntropyLossLabelSmoothing(nn.CrossEntropyLoss): """CrossEntropyLoss - with ability to recieve distrbution as targets, and optional label smoothing""" def __init__(self, weight=None, ignore_index=-100, reduction='mean', smooth_eps=None, smooth_dist=None, from_logits=True): super(CrossEntropyLossLabelSmoothing, self).__init__(weight=weight, ignore_index=ignore_index, reduction=reduction) self.smooth_eps = smooth_eps self.smooth_dist = smooth_dist self.from_logits = from_logits def forward(self, input, target, smooth_dist=None): if smooth_dist is None: smooth_dist = self.smooth_dist return cross_entropy_label_smoothing(input, target, weight=self. weight, ignore_index=self.ignore_index, reduction=self. reduction, smooth_eps=self.smooth_eps, smooth_dist=smooth_dist, from_logits=self.from_logits) 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 from torch import nn import torch.nn.functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @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 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 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_mean_mul_neg_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last') tmp3 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last') tmp6 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last') tmp9 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last') tmp15 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last') tmp19 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last') tmp23 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last') 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 = tmp1 - tmp12 tmp14 = tmp0 * tmp13 tmp16 = tmp3 - tmp12 tmp17 = tmp15 * tmp16 tmp18 = tmp14 + tmp17 tmp20 = tmp6 - tmp12 tmp21 = tmp19 * tmp20 tmp22 = tmp18 + tmp21 tmp24 = tmp9 - tmp12 tmp25 = tmp23 * tmp24 tmp26 = tmp22 + tmp25 tmp27 = -tmp26 tmp28 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK]) tmp30 = tl.sum(tmp28, 1)[:, None] tmp31 = 64.0 tmp32 = tmp30 / tmp31 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused__log_softmax_mean_mul_neg_sum_1[grid(1)](buf2, arg1_1, buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg1_1 del buf0 return buf2, def _is_long(x): if hasattr(x, 'data'): x = x.data return isinstance(x, torch.LongTensor) or isinstance(x, torch.LongTensor) def onehot(indexes, N=None, ignore_index=None): """ Creates a one-representation of indexes with N possible entries if N is not specified, it will suit the maximum index appearing. indexes is a long-tensor of indexes ignore_index will be zero in onehot representation """ if N is None: N = indexes.max() + 1 sz = list(indexes.size()) output = indexes.new().byte().resize_(*sz, N).zero_() output.scatter_(-1, indexes.unsqueeze(-1), 1) if ignore_index is not None and ignore_index >= 0: output.masked_fill_(indexes.eq(ignore_index).unsqueeze(-1), 0) return output def cross_entropy_label_smoothing(inputs, target, weight=None, ignore_index =-100, reduction='mean', smooth_eps=None, smooth_dist=None, from_logits =True): """cross entropy loss, with support for target distributions and label smoothing https://arxiv.org/abs/1512.00567""" smooth_eps = smooth_eps or 0 if _is_long(target) and smooth_eps == 0: if from_logits: return F.cross_entropy(inputs, target, weight, ignore_index= ignore_index, reduction=reduction) else: return F.nll_loss(inputs, target, weight, ignore_index= ignore_index, reduction=reduction) if from_logits: lsm = F.log_softmax(inputs, dim=-1) else: lsm = inputs masked_indices = None num_classes = inputs.size(-1) if _is_long(target) and ignore_index >= 0: masked_indices = target.eq(ignore_index) if smooth_eps > 0 and smooth_dist is not None: if _is_long(target): target = onehot(target, num_classes).type_as(inputs) if smooth_dist.dim() < target.dim(): smooth_dist = smooth_dist.unsqueeze(0) target.lerp_(smooth_dist, smooth_eps) if weight is not None: lsm = lsm * weight.unsqueeze(0) if _is_long(target): eps_sum = smooth_eps / num_classes eps_nll = 1.0 - eps_sum - smooth_eps likelihood = lsm.gather(dim=-1, index=target.unsqueeze(-1)).squeeze(-1) loss = -(eps_nll * likelihood + eps_sum * lsm.sum(-1)) else: loss = -(target * lsm).sum(-1) if masked_indices is not None: loss.masked_fill_(masked_indices, 0) if reduction == 'sum': loss = loss.sum() elif reduction == 'mean': if masked_indices is None: loss = loss.mean() else: loss = loss.sum() / float(loss.size(0) - masked_indices.sum()) return loss class CrossEntropyLossLabelSmoothingNew(nn.CrossEntropyLoss): """CrossEntropyLoss - with ability to recieve distrbution as targets, and optional label smoothing""" def __init__(self, weight=None, ignore_index=-100, reduction='mean', smooth_eps=None, smooth_dist=None, from_logits=True): super(CrossEntropyLossLabelSmoothingNew, self).__init__(weight= weight, ignore_index=ignore_index, reduction=reduction) self.smooth_eps = smooth_eps self.smooth_dist = smooth_dist self.from_logits = from_logits def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
litvinich/detectron2
CrossEntropyLossLabelSmoothing
false
12,724
[ "Apache-2.0" ]
0
ac622e22eb0f13c9b5838a1e45b046212f22f814
https://github.com/litvinich/detectron2/tree/ac622e22eb0f13c9b5838a1e45b046212f22f814
PointLoss
import torch import torch.nn.parallel import torch.utils.data import torch.nn as nn def array2samples_distance(array1, array2): """ arguments: array1: the array, size: (num_point, num_feature) array2: the samples, size: (num_point, num_feature) returns: distances: each entry is the distance from a sample to array1 """ num_point1, _num_features1 = array1.shape num_point2, num_features2 = array2.shape expanded_array1 = array1.repeat(num_point2, 1) expanded_array2 = torch.reshape(torch.unsqueeze(array2, 1).repeat(1, num_point1, 1), (-1, num_features2)) distances = (expanded_array1 - expanded_array2) * (expanded_array1 - expanded_array2) distances = torch.sum(distances, dim=1) distances = torch.reshape(distances, (num_point2, num_point1)) distances = torch.min(distances, dim=1)[0] distances = torch.mean(distances) return distances def chamfer_distance_numpy(array1, array2): batch_size, _num_point, _num_features = array1.shape dist = 0 for i in range(batch_size): av_dist1 = array2samples_distance(array1[i], array2[i]) av_dist2 = array2samples_distance(array2[i], array1[i]) dist = dist + (0.5 * av_dist1 + 0.5 * av_dist2) / batch_size return dist * 100 class PointLoss(nn.Module): def __init__(self): super(PointLoss, self).__init__() def forward(self, array1, array2): return chamfer_distance_numpy(array1, array2) def get_inputs(): return [torch.rand([4, 4, 4]), 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.parallel import torch.utils.data 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_div_mean_min_mul_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + 4 * (4 * r0 % 4), None, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (1 + 4 * (4 * r0 % 4)), None, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (2 + 4 * (4 * r0 % 4)), None, eviction_policy= 'evict_last') tmp10 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last') tmp14 = tl.load(in_ptr0 + (3 + 4 * (4 * r0 % 4)), None, eviction_policy ='evict_last') tmp15 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last') tmp19 = tl.load(in_ptr0 + 4) tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK]) tmp23 = tl.load(in_ptr0 + 5) tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK]) tmp28 = tl.load(in_ptr0 + 6) tmp29 = tl.broadcast_to(tmp28, [XBLOCK, RBLOCK]) tmp33 = tl.load(in_ptr0 + 7) tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK]) tmp39 = tl.load(in_ptr0 + 8) tmp40 = tl.broadcast_to(tmp39, [XBLOCK, RBLOCK]) tmp43 = tl.load(in_ptr0 + 9) tmp44 = tl.broadcast_to(tmp43, [XBLOCK, RBLOCK]) tmp48 = tl.load(in_ptr0 + 10) tmp49 = tl.broadcast_to(tmp48, [XBLOCK, RBLOCK]) tmp53 = tl.load(in_ptr0 + 11) tmp54 = tl.broadcast_to(tmp53, [XBLOCK, RBLOCK]) tmp59 = tl.load(in_ptr0 + 12) tmp60 = tl.broadcast_to(tmp59, [XBLOCK, RBLOCK]) tmp63 = tl.load(in_ptr0 + 13) tmp64 = tl.broadcast_to(tmp63, [XBLOCK, RBLOCK]) tmp68 = tl.load(in_ptr0 + 14) tmp69 = tl.broadcast_to(tmp68, [XBLOCK, RBLOCK]) tmp73 = tl.load(in_ptr0 + 15) tmp74 = tl.broadcast_to(tmp73, [XBLOCK, RBLOCK]) tmp82 = tl.load(in_ptr1 + 4 * (4 * r0 % 4), None, eviction_policy= 'evict_last') tmp83 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last') tmp86 = tl.load(in_ptr1 + (1 + 4 * (4 * r0 % 4)), None, eviction_policy ='evict_last') tmp87 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last') tmp91 = tl.load(in_ptr1 + (2 + 4 * (4 * r0 % 4)), None, eviction_policy ='evict_last') tmp92 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last') tmp96 = tl.load(in_ptr1 + (3 + 4 * (4 * r0 % 4)), None, eviction_policy ='evict_last') tmp97 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last') tmp101 = tl.load(in_ptr1 + 4) tmp102 = tl.broadcast_to(tmp101, [XBLOCK, RBLOCK]) tmp105 = tl.load(in_ptr1 + 5) tmp106 = tl.broadcast_to(tmp105, [XBLOCK, RBLOCK]) tmp110 = tl.load(in_ptr1 + 6) tmp111 = tl.broadcast_to(tmp110, [XBLOCK, RBLOCK]) tmp115 = tl.load(in_ptr1 + 7) tmp116 = tl.broadcast_to(tmp115, [XBLOCK, RBLOCK]) tmp121 = tl.load(in_ptr1 + 8) tmp122 = tl.broadcast_to(tmp121, [XBLOCK, RBLOCK]) tmp125 = tl.load(in_ptr1 + 9) tmp126 = tl.broadcast_to(tmp125, [XBLOCK, RBLOCK]) tmp130 = tl.load(in_ptr1 + 10) tmp131 = tl.broadcast_to(tmp130, [XBLOCK, RBLOCK]) tmp135 = tl.load(in_ptr1 + 11) tmp136 = tl.broadcast_to(tmp135, [XBLOCK, RBLOCK]) tmp141 = tl.load(in_ptr1 + 12) tmp142 = tl.broadcast_to(tmp141, [XBLOCK, RBLOCK]) tmp145 = tl.load(in_ptr1 + 13) tmp146 = tl.broadcast_to(tmp145, [XBLOCK, RBLOCK]) tmp150 = tl.load(in_ptr1 + 14) tmp151 = tl.broadcast_to(tmp150, [XBLOCK, RBLOCK]) tmp155 = tl.load(in_ptr1 + 15) tmp156 = tl.broadcast_to(tmp155, [XBLOCK, RBLOCK]) tmp164 = tl.load(in_ptr0 + (16 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp165 = tl.load(in_ptr1 + (16 + 4 * r0), None, eviction_policy= 'evict_last') tmp168 = tl.load(in_ptr0 + (17 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp169 = tl.load(in_ptr1 + (17 + 4 * r0), None, eviction_policy= 'evict_last') tmp173 = tl.load(in_ptr0 + (18 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp174 = tl.load(in_ptr1 + (18 + 4 * r0), None, eviction_policy= 'evict_last') tmp178 = tl.load(in_ptr0 + (19 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp179 = tl.load(in_ptr1 + (19 + 4 * r0), None, eviction_policy= 'evict_last') tmp183 = tl.load(in_ptr0 + 20) tmp184 = tl.broadcast_to(tmp183, [XBLOCK, RBLOCK]) tmp187 = tl.load(in_ptr0 + 21) tmp188 = tl.broadcast_to(tmp187, [XBLOCK, RBLOCK]) tmp192 = tl.load(in_ptr0 + 22) tmp193 = tl.broadcast_to(tmp192, [XBLOCK, RBLOCK]) tmp197 = tl.load(in_ptr0 + 23) tmp198 = tl.broadcast_to(tmp197, [XBLOCK, RBLOCK]) tmp203 = tl.load(in_ptr0 + 24) tmp204 = tl.broadcast_to(tmp203, [XBLOCK, RBLOCK]) tmp207 = tl.load(in_ptr0 + 25) tmp208 = tl.broadcast_to(tmp207, [XBLOCK, RBLOCK]) tmp212 = tl.load(in_ptr0 + 26) tmp213 = tl.broadcast_to(tmp212, [XBLOCK, RBLOCK]) tmp217 = tl.load(in_ptr0 + 27) tmp218 = tl.broadcast_to(tmp217, [XBLOCK, RBLOCK]) tmp223 = tl.load(in_ptr0 + 28) tmp224 = tl.broadcast_to(tmp223, [XBLOCK, RBLOCK]) tmp227 = tl.load(in_ptr0 + 29) tmp228 = tl.broadcast_to(tmp227, [XBLOCK, RBLOCK]) tmp232 = tl.load(in_ptr0 + 30) tmp233 = tl.broadcast_to(tmp232, [XBLOCK, RBLOCK]) tmp237 = tl.load(in_ptr0 + 31) tmp238 = tl.broadcast_to(tmp237, [XBLOCK, RBLOCK]) tmp246 = tl.load(in_ptr1 + (16 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp247 = tl.load(in_ptr0 + (16 + 4 * r0), None, eviction_policy= 'evict_last') tmp250 = tl.load(in_ptr1 + (17 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp251 = tl.load(in_ptr0 + (17 + 4 * r0), None, eviction_policy= 'evict_last') tmp255 = tl.load(in_ptr1 + (18 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp256 = tl.load(in_ptr0 + (18 + 4 * r0), None, eviction_policy= 'evict_last') tmp260 = tl.load(in_ptr1 + (19 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp261 = tl.load(in_ptr0 + (19 + 4 * r0), None, eviction_policy= 'evict_last') tmp265 = tl.load(in_ptr1 + 20) tmp266 = tl.broadcast_to(tmp265, [XBLOCK, RBLOCK]) tmp269 = tl.load(in_ptr1 + 21) tmp270 = tl.broadcast_to(tmp269, [XBLOCK, RBLOCK]) tmp274 = tl.load(in_ptr1 + 22) tmp275 = tl.broadcast_to(tmp274, [XBLOCK, RBLOCK]) tmp279 = tl.load(in_ptr1 + 23) tmp280 = tl.broadcast_to(tmp279, [XBLOCK, RBLOCK]) tmp285 = tl.load(in_ptr1 + 24) tmp286 = tl.broadcast_to(tmp285, [XBLOCK, RBLOCK]) tmp289 = tl.load(in_ptr1 + 25) tmp290 = tl.broadcast_to(tmp289, [XBLOCK, RBLOCK]) tmp294 = tl.load(in_ptr1 + 26) tmp295 = tl.broadcast_to(tmp294, [XBLOCK, RBLOCK]) tmp299 = tl.load(in_ptr1 + 27) tmp300 = tl.broadcast_to(tmp299, [XBLOCK, RBLOCK]) tmp305 = tl.load(in_ptr1 + 28) tmp306 = tl.broadcast_to(tmp305, [XBLOCK, RBLOCK]) tmp309 = tl.load(in_ptr1 + 29) tmp310 = tl.broadcast_to(tmp309, [XBLOCK, RBLOCK]) tmp314 = tl.load(in_ptr1 + 30) tmp315 = tl.broadcast_to(tmp314, [XBLOCK, RBLOCK]) tmp319 = tl.load(in_ptr1 + 31) tmp320 = tl.broadcast_to(tmp319, [XBLOCK, RBLOCK]) tmp328 = tl.load(in_ptr0 + (48 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp329 = tl.load(in_ptr1 + (48 + 4 * r0), None, eviction_policy= 'evict_last') tmp332 = tl.load(in_ptr0 + (49 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp333 = tl.load(in_ptr1 + (49 + 4 * r0), None, eviction_policy= 'evict_last') tmp337 = tl.load(in_ptr0 + (50 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp338 = tl.load(in_ptr1 + (50 + 4 * r0), None, eviction_policy= 'evict_last') tmp342 = tl.load(in_ptr0 + (51 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp343 = tl.load(in_ptr1 + (51 + 4 * r0), None, eviction_policy= 'evict_last') tmp347 = tl.load(in_ptr0 + 52) tmp348 = tl.broadcast_to(tmp347, [XBLOCK, RBLOCK]) tmp351 = tl.load(in_ptr0 + 53) tmp352 = tl.broadcast_to(tmp351, [XBLOCK, RBLOCK]) tmp356 = tl.load(in_ptr0 + 54) tmp357 = tl.broadcast_to(tmp356, [XBLOCK, RBLOCK]) tmp361 = tl.load(in_ptr0 + 55) tmp362 = tl.broadcast_to(tmp361, [XBLOCK, RBLOCK]) tmp367 = tl.load(in_ptr0 + 56) tmp368 = tl.broadcast_to(tmp367, [XBLOCK, RBLOCK]) tmp371 = tl.load(in_ptr0 + 57) tmp372 = tl.broadcast_to(tmp371, [XBLOCK, RBLOCK]) tmp376 = tl.load(in_ptr0 + 58) tmp377 = tl.broadcast_to(tmp376, [XBLOCK, RBLOCK]) tmp381 = tl.load(in_ptr0 + 59) tmp382 = tl.broadcast_to(tmp381, [XBLOCK, RBLOCK]) tmp387 = tl.load(in_ptr0 + 60) tmp388 = tl.broadcast_to(tmp387, [XBLOCK, RBLOCK]) tmp391 = tl.load(in_ptr0 + 61) tmp392 = tl.broadcast_to(tmp391, [XBLOCK, RBLOCK]) tmp396 = tl.load(in_ptr0 + 62) tmp397 = tl.broadcast_to(tmp396, [XBLOCK, RBLOCK]) tmp401 = tl.load(in_ptr0 + 63) tmp402 = tl.broadcast_to(tmp401, [XBLOCK, RBLOCK]) tmp410 = tl.load(in_ptr0 + (32 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp411 = tl.load(in_ptr1 + (32 + 4 * r0), None, eviction_policy= 'evict_last') tmp414 = tl.load(in_ptr0 + (33 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp415 = tl.load(in_ptr1 + (33 + 4 * r0), None, eviction_policy= 'evict_last') tmp419 = tl.load(in_ptr0 + (34 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp420 = tl.load(in_ptr1 + (34 + 4 * r0), None, eviction_policy= 'evict_last') tmp424 = tl.load(in_ptr0 + (35 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp425 = tl.load(in_ptr1 + (35 + 4 * r0), None, eviction_policy= 'evict_last') tmp429 = tl.load(in_ptr0 + 36) tmp430 = tl.broadcast_to(tmp429, [XBLOCK, RBLOCK]) tmp433 = tl.load(in_ptr0 + 37) tmp434 = tl.broadcast_to(tmp433, [XBLOCK, RBLOCK]) tmp438 = tl.load(in_ptr0 + 38) tmp439 = tl.broadcast_to(tmp438, [XBLOCK, RBLOCK]) tmp443 = tl.load(in_ptr0 + 39) tmp444 = tl.broadcast_to(tmp443, [XBLOCK, RBLOCK]) tmp449 = tl.load(in_ptr0 + 40) tmp450 = tl.broadcast_to(tmp449, [XBLOCK, RBLOCK]) tmp453 = tl.load(in_ptr0 + 41) tmp454 = tl.broadcast_to(tmp453, [XBLOCK, RBLOCK]) tmp458 = tl.load(in_ptr0 + 42) tmp459 = tl.broadcast_to(tmp458, [XBLOCK, RBLOCK]) tmp463 = tl.load(in_ptr0 + 43) tmp464 = tl.broadcast_to(tmp463, [XBLOCK, RBLOCK]) tmp469 = tl.load(in_ptr0 + 44) tmp470 = tl.broadcast_to(tmp469, [XBLOCK, RBLOCK]) tmp473 = tl.load(in_ptr0 + 45) tmp474 = tl.broadcast_to(tmp473, [XBLOCK, RBLOCK]) tmp478 = tl.load(in_ptr0 + 46) tmp479 = tl.broadcast_to(tmp478, [XBLOCK, RBLOCK]) tmp483 = tl.load(in_ptr0 + 47) tmp484 = tl.broadcast_to(tmp483, [XBLOCK, RBLOCK]) tmp492 = tl.load(in_ptr1 + (48 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp493 = tl.load(in_ptr0 + (48 + 4 * r0), None, eviction_policy= 'evict_last') tmp496 = tl.load(in_ptr1 + (49 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp497 = tl.load(in_ptr0 + (49 + 4 * r0), None, eviction_policy= 'evict_last') tmp501 = tl.load(in_ptr1 + (50 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp502 = tl.load(in_ptr0 + (50 + 4 * r0), None, eviction_policy= 'evict_last') tmp506 = tl.load(in_ptr1 + (51 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp507 = tl.load(in_ptr0 + (51 + 4 * r0), None, eviction_policy= 'evict_last') tmp511 = tl.load(in_ptr1 + 52) tmp512 = tl.broadcast_to(tmp511, [XBLOCK, RBLOCK]) tmp515 = tl.load(in_ptr1 + 53) tmp516 = tl.broadcast_to(tmp515, [XBLOCK, RBLOCK]) tmp520 = tl.load(in_ptr1 + 54) tmp521 = tl.broadcast_to(tmp520, [XBLOCK, RBLOCK]) tmp525 = tl.load(in_ptr1 + 55) tmp526 = tl.broadcast_to(tmp525, [XBLOCK, RBLOCK]) tmp531 = tl.load(in_ptr1 + 56) tmp532 = tl.broadcast_to(tmp531, [XBLOCK, RBLOCK]) tmp535 = tl.load(in_ptr1 + 57) tmp536 = tl.broadcast_to(tmp535, [XBLOCK, RBLOCK]) tmp540 = tl.load(in_ptr1 + 58) tmp541 = tl.broadcast_to(tmp540, [XBLOCK, RBLOCK]) tmp545 = tl.load(in_ptr1 + 59) tmp546 = tl.broadcast_to(tmp545, [XBLOCK, RBLOCK]) tmp551 = tl.load(in_ptr1 + 60) tmp552 = tl.broadcast_to(tmp551, [XBLOCK, RBLOCK]) tmp555 = tl.load(in_ptr1 + 61) tmp556 = tl.broadcast_to(tmp555, [XBLOCK, RBLOCK]) tmp560 = tl.load(in_ptr1 + 62) tmp561 = tl.broadcast_to(tmp560, [XBLOCK, RBLOCK]) tmp565 = tl.load(in_ptr1 + 63) tmp566 = tl.broadcast_to(tmp565, [XBLOCK, RBLOCK]) tmp574 = tl.load(in_ptr1 + (32 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp575 = tl.load(in_ptr0 + (32 + 4 * r0), None, eviction_policy= 'evict_last') tmp578 = tl.load(in_ptr1 + (33 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp579 = tl.load(in_ptr0 + (33 + 4 * r0), None, eviction_policy= 'evict_last') tmp583 = tl.load(in_ptr1 + (34 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp584 = tl.load(in_ptr0 + (34 + 4 * r0), None, eviction_policy= 'evict_last') tmp588 = tl.load(in_ptr1 + (35 + 4 * (4 * r0 % 4)), None, eviction_policy='evict_last') tmp589 = tl.load(in_ptr0 + (35 + 4 * r0), None, eviction_policy= 'evict_last') tmp593 = tl.load(in_ptr1 + 36) tmp594 = tl.broadcast_to(tmp593, [XBLOCK, RBLOCK]) tmp597 = tl.load(in_ptr1 + 37) tmp598 = tl.broadcast_to(tmp597, [XBLOCK, RBLOCK]) tmp602 = tl.load(in_ptr1 + 38) tmp603 = tl.broadcast_to(tmp602, [XBLOCK, RBLOCK]) tmp607 = tl.load(in_ptr1 + 39) tmp608 = tl.broadcast_to(tmp607, [XBLOCK, RBLOCK]) tmp613 = tl.load(in_ptr1 + 40) tmp614 = tl.broadcast_to(tmp613, [XBLOCK, RBLOCK]) tmp617 = tl.load(in_ptr1 + 41) tmp618 = tl.broadcast_to(tmp617, [XBLOCK, RBLOCK]) tmp622 = tl.load(in_ptr1 + 42) tmp623 = tl.broadcast_to(tmp622, [XBLOCK, RBLOCK]) tmp627 = tl.load(in_ptr1 + 43) tmp628 = tl.broadcast_to(tmp627, [XBLOCK, RBLOCK]) tmp633 = tl.load(in_ptr1 + 44) tmp634 = tl.broadcast_to(tmp633, [XBLOCK, RBLOCK]) tmp637 = tl.load(in_ptr1 + 45) tmp638 = tl.broadcast_to(tmp637, [XBLOCK, RBLOCK]) tmp642 = tl.load(in_ptr1 + 46) tmp643 = tl.broadcast_to(tmp642, [XBLOCK, RBLOCK]) tmp647 = tl.load(in_ptr1 + 47) tmp648 = tl.broadcast_to(tmp647, [XBLOCK, RBLOCK]) 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 tmp21 = tmp20 - tmp1 tmp22 = tmp21 * tmp21 tmp25 = tmp24 - tmp5 tmp26 = tmp25 * tmp25 tmp27 = tmp22 + tmp26 tmp30 = tmp29 - tmp10 tmp31 = tmp30 * tmp30 tmp32 = tmp27 + tmp31 tmp35 = tmp34 - tmp15 tmp36 = tmp35 * tmp35 tmp37 = tmp32 + tmp36 tmp38 = triton_helpers.minimum(tmp18, tmp37) tmp41 = tmp40 - tmp1 tmp42 = tmp41 * tmp41 tmp45 = tmp44 - tmp5 tmp46 = tmp45 * tmp45 tmp47 = tmp42 + tmp46 tmp50 = tmp49 - tmp10 tmp51 = tmp50 * tmp50 tmp52 = tmp47 + tmp51 tmp55 = tmp54 - tmp15 tmp56 = tmp55 * tmp55 tmp57 = tmp52 + tmp56 tmp58 = triton_helpers.minimum(tmp38, tmp57) tmp61 = tmp60 - tmp1 tmp62 = tmp61 * tmp61 tmp65 = tmp64 - tmp5 tmp66 = tmp65 * tmp65 tmp67 = tmp62 + tmp66 tmp70 = tmp69 - tmp10 tmp71 = tmp70 * tmp70 tmp72 = tmp67 + tmp71 tmp75 = tmp74 - tmp15 tmp76 = tmp75 * tmp75 tmp77 = tmp72 + tmp76 tmp78 = triton_helpers.minimum(tmp58, tmp77) tmp79 = tl.broadcast_to(tmp78, [XBLOCK, RBLOCK]) tmp81 = tl.sum(tmp79, 1)[:, None] tmp84 = tmp82 - tmp83 tmp85 = tmp84 * tmp84 tmp88 = tmp86 - tmp87 tmp89 = tmp88 * tmp88 tmp90 = tmp85 + tmp89 tmp93 = tmp91 - tmp92 tmp94 = tmp93 * tmp93 tmp95 = tmp90 + tmp94 tmp98 = tmp96 - tmp97 tmp99 = tmp98 * tmp98 tmp100 = tmp95 + tmp99 tmp103 = tmp102 - tmp83 tmp104 = tmp103 * tmp103 tmp107 = tmp106 - tmp87 tmp108 = tmp107 * tmp107 tmp109 = tmp104 + tmp108 tmp112 = tmp111 - tmp92 tmp113 = tmp112 * tmp112 tmp114 = tmp109 + tmp113 tmp117 = tmp116 - tmp97 tmp118 = tmp117 * tmp117 tmp119 = tmp114 + tmp118 tmp120 = triton_helpers.minimum(tmp100, tmp119) tmp123 = tmp122 - tmp83 tmp124 = tmp123 * tmp123 tmp127 = tmp126 - tmp87 tmp128 = tmp127 * tmp127 tmp129 = tmp124 + tmp128 tmp132 = tmp131 - tmp92 tmp133 = tmp132 * tmp132 tmp134 = tmp129 + tmp133 tmp137 = tmp136 - tmp97 tmp138 = tmp137 * tmp137 tmp139 = tmp134 + tmp138 tmp140 = triton_helpers.minimum(tmp120, tmp139) tmp143 = tmp142 - tmp83 tmp144 = tmp143 * tmp143 tmp147 = tmp146 - tmp87 tmp148 = tmp147 * tmp147 tmp149 = tmp144 + tmp148 tmp152 = tmp151 - tmp92 tmp153 = tmp152 * tmp152 tmp154 = tmp149 + tmp153 tmp157 = tmp156 - tmp97 tmp158 = tmp157 * tmp157 tmp159 = tmp154 + tmp158 tmp160 = triton_helpers.minimum(tmp140, tmp159) tmp161 = tl.broadcast_to(tmp160, [XBLOCK, RBLOCK]) tmp163 = tl.sum(tmp161, 1)[:, None] tmp166 = tmp164 - tmp165 tmp167 = tmp166 * tmp166 tmp170 = tmp168 - tmp169 tmp171 = tmp170 * tmp170 tmp172 = tmp167 + tmp171 tmp175 = tmp173 - tmp174 tmp176 = tmp175 * tmp175 tmp177 = tmp172 + tmp176 tmp180 = tmp178 - tmp179 tmp181 = tmp180 * tmp180 tmp182 = tmp177 + tmp181 tmp185 = tmp184 - tmp165 tmp186 = tmp185 * tmp185 tmp189 = tmp188 - tmp169 tmp190 = tmp189 * tmp189 tmp191 = tmp186 + tmp190 tmp194 = tmp193 - tmp174 tmp195 = tmp194 * tmp194 tmp196 = tmp191 + tmp195 tmp199 = tmp198 - tmp179 tmp200 = tmp199 * tmp199 tmp201 = tmp196 + tmp200 tmp202 = triton_helpers.minimum(tmp182, tmp201) tmp205 = tmp204 - tmp165 tmp206 = tmp205 * tmp205 tmp209 = tmp208 - tmp169 tmp210 = tmp209 * tmp209 tmp211 = tmp206 + tmp210 tmp214 = tmp213 - tmp174 tmp215 = tmp214 * tmp214 tmp216 = tmp211 + tmp215 tmp219 = tmp218 - tmp179 tmp220 = tmp219 * tmp219 tmp221 = tmp216 + tmp220 tmp222 = triton_helpers.minimum(tmp202, tmp221) tmp225 = tmp224 - tmp165 tmp226 = tmp225 * tmp225 tmp229 = tmp228 - tmp169 tmp230 = tmp229 * tmp229 tmp231 = tmp226 + tmp230 tmp234 = tmp233 - tmp174 tmp235 = tmp234 * tmp234 tmp236 = tmp231 + tmp235 tmp239 = tmp238 - tmp179 tmp240 = tmp239 * tmp239 tmp241 = tmp236 + tmp240 tmp242 = triton_helpers.minimum(tmp222, tmp241) tmp243 = tl.broadcast_to(tmp242, [XBLOCK, RBLOCK]) tmp245 = tl.sum(tmp243, 1)[:, None] tmp248 = tmp246 - tmp247 tmp249 = tmp248 * tmp248 tmp252 = tmp250 - tmp251 tmp253 = tmp252 * tmp252 tmp254 = tmp249 + tmp253 tmp257 = tmp255 - tmp256 tmp258 = tmp257 * tmp257 tmp259 = tmp254 + tmp258 tmp262 = tmp260 - tmp261 tmp263 = tmp262 * tmp262 tmp264 = tmp259 + tmp263 tmp267 = tmp266 - tmp247 tmp268 = tmp267 * tmp267 tmp271 = tmp270 - tmp251 tmp272 = tmp271 * tmp271 tmp273 = tmp268 + tmp272 tmp276 = tmp275 - tmp256 tmp277 = tmp276 * tmp276 tmp278 = tmp273 + tmp277 tmp281 = tmp280 - tmp261 tmp282 = tmp281 * tmp281 tmp283 = tmp278 + tmp282 tmp284 = triton_helpers.minimum(tmp264, tmp283) tmp287 = tmp286 - tmp247 tmp288 = tmp287 * tmp287 tmp291 = tmp290 - tmp251 tmp292 = tmp291 * tmp291 tmp293 = tmp288 + tmp292 tmp296 = tmp295 - tmp256 tmp297 = tmp296 * tmp296 tmp298 = tmp293 + tmp297 tmp301 = tmp300 - tmp261 tmp302 = tmp301 * tmp301 tmp303 = tmp298 + tmp302 tmp304 = triton_helpers.minimum(tmp284, tmp303) tmp307 = tmp306 - tmp247 tmp308 = tmp307 * tmp307 tmp311 = tmp310 - tmp251 tmp312 = tmp311 * tmp311 tmp313 = tmp308 + tmp312 tmp316 = tmp315 - tmp256 tmp317 = tmp316 * tmp316 tmp318 = tmp313 + tmp317 tmp321 = tmp320 - tmp261 tmp322 = tmp321 * tmp321 tmp323 = tmp318 + tmp322 tmp324 = triton_helpers.minimum(tmp304, tmp323) tmp325 = tl.broadcast_to(tmp324, [XBLOCK, RBLOCK]) tmp327 = tl.sum(tmp325, 1)[:, None] tmp330 = tmp328 - tmp329 tmp331 = tmp330 * tmp330 tmp334 = tmp332 - tmp333 tmp335 = tmp334 * tmp334 tmp336 = tmp331 + tmp335 tmp339 = tmp337 - tmp338 tmp340 = tmp339 * tmp339 tmp341 = tmp336 + tmp340 tmp344 = tmp342 - tmp343 tmp345 = tmp344 * tmp344 tmp346 = tmp341 + tmp345 tmp349 = tmp348 - tmp329 tmp350 = tmp349 * tmp349 tmp353 = tmp352 - tmp333 tmp354 = tmp353 * tmp353 tmp355 = tmp350 + tmp354 tmp358 = tmp357 - tmp338 tmp359 = tmp358 * tmp358 tmp360 = tmp355 + tmp359 tmp363 = tmp362 - tmp343 tmp364 = tmp363 * tmp363 tmp365 = tmp360 + tmp364 tmp366 = triton_helpers.minimum(tmp346, tmp365) tmp369 = tmp368 - tmp329 tmp370 = tmp369 * tmp369 tmp373 = tmp372 - tmp333 tmp374 = tmp373 * tmp373 tmp375 = tmp370 + tmp374 tmp378 = tmp377 - tmp338 tmp379 = tmp378 * tmp378 tmp380 = tmp375 + tmp379 tmp383 = tmp382 - tmp343 tmp384 = tmp383 * tmp383 tmp385 = tmp380 + tmp384 tmp386 = triton_helpers.minimum(tmp366, tmp385) tmp389 = tmp388 - tmp329 tmp390 = tmp389 * tmp389 tmp393 = tmp392 - tmp333 tmp394 = tmp393 * tmp393 tmp395 = tmp390 + tmp394 tmp398 = tmp397 - tmp338 tmp399 = tmp398 * tmp398 tmp400 = tmp395 + tmp399 tmp403 = tmp402 - tmp343 tmp404 = tmp403 * tmp403 tmp405 = tmp400 + tmp404 tmp406 = triton_helpers.minimum(tmp386, tmp405) tmp407 = tl.broadcast_to(tmp406, [XBLOCK, RBLOCK]) tmp409 = tl.sum(tmp407, 1)[:, None] tmp412 = tmp410 - tmp411 tmp413 = tmp412 * tmp412 tmp416 = tmp414 - tmp415 tmp417 = tmp416 * tmp416 tmp418 = tmp413 + tmp417 tmp421 = tmp419 - tmp420 tmp422 = tmp421 * tmp421 tmp423 = tmp418 + tmp422 tmp426 = tmp424 - tmp425 tmp427 = tmp426 * tmp426 tmp428 = tmp423 + tmp427 tmp431 = tmp430 - tmp411 tmp432 = tmp431 * tmp431 tmp435 = tmp434 - tmp415 tmp436 = tmp435 * tmp435 tmp437 = tmp432 + tmp436 tmp440 = tmp439 - tmp420 tmp441 = tmp440 * tmp440 tmp442 = tmp437 + tmp441 tmp445 = tmp444 - tmp425 tmp446 = tmp445 * tmp445 tmp447 = tmp442 + tmp446 tmp448 = triton_helpers.minimum(tmp428, tmp447) tmp451 = tmp450 - tmp411 tmp452 = tmp451 * tmp451 tmp455 = tmp454 - tmp415 tmp456 = tmp455 * tmp455 tmp457 = tmp452 + tmp456 tmp460 = tmp459 - tmp420 tmp461 = tmp460 * tmp460 tmp462 = tmp457 + tmp461 tmp465 = tmp464 - tmp425 tmp466 = tmp465 * tmp465 tmp467 = tmp462 + tmp466 tmp468 = triton_helpers.minimum(tmp448, tmp467) tmp471 = tmp470 - tmp411 tmp472 = tmp471 * tmp471 tmp475 = tmp474 - tmp415 tmp476 = tmp475 * tmp475 tmp477 = tmp472 + tmp476 tmp480 = tmp479 - tmp420 tmp481 = tmp480 * tmp480 tmp482 = tmp477 + tmp481 tmp485 = tmp484 - tmp425 tmp486 = tmp485 * tmp485 tmp487 = tmp482 + tmp486 tmp488 = triton_helpers.minimum(tmp468, tmp487) tmp489 = tl.broadcast_to(tmp488, [XBLOCK, RBLOCK]) tmp491 = tl.sum(tmp489, 1)[:, None] tmp494 = tmp492 - tmp493 tmp495 = tmp494 * tmp494 tmp498 = tmp496 - tmp497 tmp499 = tmp498 * tmp498 tmp500 = tmp495 + tmp499 tmp503 = tmp501 - tmp502 tmp504 = tmp503 * tmp503 tmp505 = tmp500 + tmp504 tmp508 = tmp506 - tmp507 tmp509 = tmp508 * tmp508 tmp510 = tmp505 + tmp509 tmp513 = tmp512 - tmp493 tmp514 = tmp513 * tmp513 tmp517 = tmp516 - tmp497 tmp518 = tmp517 * tmp517 tmp519 = tmp514 + tmp518 tmp522 = tmp521 - tmp502 tmp523 = tmp522 * tmp522 tmp524 = tmp519 + tmp523 tmp527 = tmp526 - tmp507 tmp528 = tmp527 * tmp527 tmp529 = tmp524 + tmp528 tmp530 = triton_helpers.minimum(tmp510, tmp529) tmp533 = tmp532 - tmp493 tmp534 = tmp533 * tmp533 tmp537 = tmp536 - tmp497 tmp538 = tmp537 * tmp537 tmp539 = tmp534 + tmp538 tmp542 = tmp541 - tmp502 tmp543 = tmp542 * tmp542 tmp544 = tmp539 + tmp543 tmp547 = tmp546 - tmp507 tmp548 = tmp547 * tmp547 tmp549 = tmp544 + tmp548 tmp550 = triton_helpers.minimum(tmp530, tmp549) tmp553 = tmp552 - tmp493 tmp554 = tmp553 * tmp553 tmp557 = tmp556 - tmp497 tmp558 = tmp557 * tmp557 tmp559 = tmp554 + tmp558 tmp562 = tmp561 - tmp502 tmp563 = tmp562 * tmp562 tmp564 = tmp559 + tmp563 tmp567 = tmp566 - tmp507 tmp568 = tmp567 * tmp567 tmp569 = tmp564 + tmp568 tmp570 = triton_helpers.minimum(tmp550, tmp569) tmp571 = tl.broadcast_to(tmp570, [XBLOCK, RBLOCK]) tmp573 = tl.sum(tmp571, 1)[:, None] tmp576 = tmp574 - tmp575 tmp577 = tmp576 * tmp576 tmp580 = tmp578 - tmp579 tmp581 = tmp580 * tmp580 tmp582 = tmp577 + tmp581 tmp585 = tmp583 - tmp584 tmp586 = tmp585 * tmp585 tmp587 = tmp582 + tmp586 tmp590 = tmp588 - tmp589 tmp591 = tmp590 * tmp590 tmp592 = tmp587 + tmp591 tmp595 = tmp594 - tmp575 tmp596 = tmp595 * tmp595 tmp599 = tmp598 - tmp579 tmp600 = tmp599 * tmp599 tmp601 = tmp596 + tmp600 tmp604 = tmp603 - tmp584 tmp605 = tmp604 * tmp604 tmp606 = tmp601 + tmp605 tmp609 = tmp608 - tmp589 tmp610 = tmp609 * tmp609 tmp611 = tmp606 + tmp610 tmp612 = triton_helpers.minimum(tmp592, tmp611) tmp615 = tmp614 - tmp575 tmp616 = tmp615 * tmp615 tmp619 = tmp618 - tmp579 tmp620 = tmp619 * tmp619 tmp621 = tmp616 + tmp620 tmp624 = tmp623 - tmp584 tmp625 = tmp624 * tmp624 tmp626 = tmp621 + tmp625 tmp629 = tmp628 - tmp589 tmp630 = tmp629 * tmp629 tmp631 = tmp626 + tmp630 tmp632 = triton_helpers.minimum(tmp612, tmp631) tmp635 = tmp634 - tmp575 tmp636 = tmp635 * tmp635 tmp639 = tmp638 - tmp579 tmp640 = tmp639 * tmp639 tmp641 = tmp636 + tmp640 tmp644 = tmp643 - tmp584 tmp645 = tmp644 * tmp644 tmp646 = tmp641 + tmp645 tmp649 = tmp648 - tmp589 tmp650 = tmp649 * tmp649 tmp651 = tmp646 + tmp650 tmp652 = triton_helpers.minimum(tmp632, tmp651) tmp653 = tl.broadcast_to(tmp652, [XBLOCK, RBLOCK]) tmp655 = tl.sum(tmp653, 1)[:, None] tmp656 = 4.0 tmp657 = tmp81 / tmp656 tmp658 = 0.5 tmp659 = tmp657 * tmp658 tmp660 = tmp163 / tmp656 tmp661 = tmp660 * tmp658 tmp662 = tmp659 + tmp661 tmp663 = 0.25 tmp664 = tmp662 * tmp663 tmp665 = 0.0 tmp666 = tmp664 + tmp665 tmp667 = tmp245 / tmp656 tmp668 = tmp667 * tmp658 tmp669 = tmp327 / tmp656 tmp670 = tmp669 * tmp658 tmp671 = tmp668 + tmp670 tmp672 = tmp671 * tmp663 tmp673 = tmp666 + tmp672 tmp674 = tmp491 / tmp656 tmp675 = tmp674 * tmp658 tmp676 = tmp655 / tmp656 tmp677 = tmp676 * tmp658 tmp678 = tmp675 + tmp677 tmp679 = tmp678 * tmp663 tmp680 = tmp673 + tmp679 tmp681 = tmp409 / tmp656 tmp682 = tmp681 * tmp658 tmp683 = tmp573 / tmp656 tmp684 = tmp683 * tmp658 tmp685 = tmp682 + tmp684 tmp686 = tmp685 * tmp663 tmp687 = tmp680 + tmp686 tmp688 = 100.0 tmp689 = tmp687 * tmp688 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp689, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4), (16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf10 = empty_strided_cuda((), (), torch.float32) buf14 = buf10 del buf10 buf17 = buf14 del buf14 get_raw_stream(0) triton_per_fused_add_div_mean_min_mul_0[grid(1)](buf17, arg0_1, arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf17, def array2samples_distance(array1, array2): """ arguments: array1: the array, size: (num_point, num_feature) array2: the samples, size: (num_point, num_feature) returns: distances: each entry is the distance from a sample to array1 """ num_point1, _num_features1 = array1.shape num_point2, num_features2 = array2.shape expanded_array1 = array1.repeat(num_point2, 1) expanded_array2 = torch.reshape(torch.unsqueeze(array2, 1).repeat(1, num_point1, 1), (-1, num_features2)) distances = (expanded_array1 - expanded_array2) * (expanded_array1 - expanded_array2) distances = torch.sum(distances, dim=1) distances = torch.reshape(distances, (num_point2, num_point1)) distances = torch.min(distances, dim=1)[0] distances = torch.mean(distances) return distances def chamfer_distance_numpy(array1, array2): batch_size, _num_point, _num_features = array1.shape dist = 0 for i in range(batch_size): av_dist1 = array2samples_distance(array1[i], array2[i]) av_dist2 = array2samples_distance(array2[i], array1[i]) dist = dist + (0.5 * av_dist1 + 0.5 * av_dist2) / batch_size return dist * 100 class PointLossNew(nn.Module): def __init__(self): super(PointLossNew, 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]
liuyuex97/PF-Net-Point-Fractal-Network
PointLoss
false
12,725
[ "MIT" ]
0
97f248a03bcd33828e8e2175ec79bbe8c791952d
https://github.com/liuyuex97/PF-Net-Point-Fractal-Network/tree/97f248a03bcd33828e8e2175ec79bbe8c791952d
InteractingLayer
import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import * class InteractingLayer(nn.Module): """A Layer used in AutoInt that model the correlations between different feature fields by multi-head self-attention mechanism. Input shape - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 3D tensor with shape:``(batch_size,field_size,att_embedding_size * head_num)``. Arguments - **in_features** : Positive integer, dimensionality of input features. - **att_embedding_size**: int.The embedding size in multi-head self-attention network. - **head_num**: int.The head number in multi-head self-attention network. - **use_res**: bool.Whether or not use standard residual connections before output. - **seed**: A Python integer to use as random seed. References - [Song W, Shi C, Xiao Z, et al. AutoInt: Automatic Feature Interaction Learning via Self-Attentive Neural Networks[J]. arXiv preprint arXiv:1810.11921, 2018.](https://arxiv.org/abs/1810.11921) """ def __init__(self, in_features, att_embedding_size=8, head_num=2, use_res=True, scaling=False, seed=1024, device='cpu'): super(InteractingLayer, self).__init__() if head_num <= 0: raise ValueError('head_num must be a int > 0') self.att_embedding_size = att_embedding_size self.head_num = head_num self.use_res = use_res self.scaling = scaling self.seed = seed embedding_size = in_features self.W_Query = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) self.W_key = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) self.W_Value = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) if self.use_res: self.W_Res = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) for tensor in self.parameters(): nn.init.normal_(tensor, mean=0.0, std=0.05) self def forward(self, inputs): if len(inputs.shape) != 3: raise ValueError( 'Unexpected inputs dimensions %d, expect to be 3 dimensions' % len(inputs.shape)) querys = torch.tensordot(inputs, self.W_Query, dims=([-1], [0])) keys = torch.tensordot(inputs, self.W_key, dims=([-1], [0])) values = torch.tensordot(inputs, self.W_Value, dims=([-1], [0])) querys = torch.stack(torch.split(querys, self.att_embedding_size, dim=2)) keys = torch.stack(torch.split(keys, self.att_embedding_size, dim=2)) values = torch.stack(torch.split(values, self.att_embedding_size, dim=2)) inner_product = torch.einsum('bnik,bnjk->bnij', querys, keys) if self.scaling: inner_product /= self.att_embedding_size ** 0.5 self.normalized_att_scores = F.softmax(inner_product, dim=-1) result = torch.matmul(self.normalized_att_scores, values) result = torch.cat(torch.split(result, 1), dim=-1) result = torch.squeeze(result, dim=0) if self.use_res: result += torch.tensordot(inputs, self.W_Res, dims=([-1], [0])) result = F.relu(result) return result def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'in_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 math as tl_math import torch.nn as nn from sklearn.metrics import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_stack_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex // 32 x0 = xindex % 8 x1 = xindex // 8 % 4 x3 = xindex tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr0 + (8 + x0 + 16 * x1 + 64 * (-4 + x2)), tmp6 & xmask, other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x3, tmp10, xmask) @triton.jit def triton_poi_fused__softmax_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 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 = 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_relu_threshold_backward_3(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 % 16 x1 = xindex // 16 x2 = xindex tmp11 = tl.load(in_out_ptr0 + x2, xmask) tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 8, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (8 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 16, tl.int64) tmp9 = tl.load(in_ptr0 + (128 + 8 * x1 + (-8 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tmp12 = tmp10 + tmp11 tmp13 = tl.full([1], 0, tl.int32) tmp14 = triton_helpers.maximum(tmp13, tmp12) tmp15 = 0.0 tmp16 = tmp14 <= tmp15 tl.store(in_out_ptr0 + x2, tmp14, xmask) tl.store(out_ptr0 + x2, tmp16, 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, 16), (16, 1)) assert_size_stride(primals_3, (4, 16), (16, 1)) assert_size_stride(primals_4, (4, 16), (16, 1)) assert_size_stride(primals_5, (4, 16), (16, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), primals_2, out=buf0) del primals_2 buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), primals_3, out=buf1) del primals_3 buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), primals_4, out=buf2) del primals_4 buf3 = empty_strided_cuda((8, 4, 8), (32, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_stack_0[grid(256)](buf0, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) buf4 = reinterpret_tensor(buf0, (8, 4, 8), (32, 8, 1), 0) del buf0 triton_poi_fused_stack_0[grid(256)](buf1, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) buf5 = empty_strided_cuda((8, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf3, reinterpret_tensor(buf4, (8, 8, 4), (32, 1, 8), 0), out=buf5) buf6 = empty_strided_cuda((2, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(128)](buf5, buf6, 128, XBLOCK=128, num_warps=4, num_stages=1) buf7 = reinterpret_tensor(buf5, (2, 4, 4, 4), (64, 16, 4, 1), 0) del buf5 triton_poi_fused__softmax_2[grid(128)](buf6, buf7, 128, XBLOCK=128, num_warps=4, num_stages=1) del buf6 buf8 = reinterpret_tensor(buf1, (8, 4, 8), (32, 8, 1), 0) del buf1 triton_poi_fused_stack_0[grid(256)](buf2, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1) buf9 = reinterpret_tensor(buf2, (8, 4, 8), (32, 8, 1), 0) del buf2 extern_kernels.bmm(reinterpret_tensor(buf7, (8, 4, 4), (16, 4, 1), 0), buf8, out=buf9) buf10 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), primals_5, out=buf10) del primals_5 buf11 = reinterpret_tensor(buf10, (4, 4, 16), (64, 16, 1), 0) del buf10 buf12 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.bool) triton_poi_fused_relu_threshold_backward_3[grid(256)](buf11, buf9, buf12, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf9 return buf11, buf7, buf7, buf12, reinterpret_tensor(primals_1, (4, 16), (1, 4), 0), reinterpret_tensor(buf8, (8, 8, 4), (32, 1, 8), 0 ), reinterpret_tensor(buf3, (8, 8, 4), (32, 1, 8), 0), buf4 class InteractingLayerNew(nn.Module): """A Layer used in AutoInt that model the correlations between different feature fields by multi-head self-attention mechanism. Input shape - A 3D tensor with shape: ``(batch_size,field_size,embedding_size)``. Output shape - 3D tensor with shape:``(batch_size,field_size,att_embedding_size * head_num)``. Arguments - **in_features** : Positive integer, dimensionality of input features. - **att_embedding_size**: int.The embedding size in multi-head self-attention network. - **head_num**: int.The head number in multi-head self-attention network. - **use_res**: bool.Whether or not use standard residual connections before output. - **seed**: A Python integer to use as random seed. References - [Song W, Shi C, Xiao Z, et al. AutoInt: Automatic Feature Interaction Learning via Self-Attentive Neural Networks[J]. arXiv preprint arXiv:1810.11921, 2018.](https://arxiv.org/abs/1810.11921) """ def __init__(self, in_features, att_embedding_size=8, head_num=2, use_res=True, scaling=False, seed=1024, device='cpu'): super(InteractingLayerNew, self).__init__() if head_num <= 0: raise ValueError('head_num must be a int > 0') self.att_embedding_size = att_embedding_size self.head_num = head_num self.use_res = use_res self.scaling = scaling self.seed = seed embedding_size = in_features self.W_Query = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) self.W_key = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) self.W_Value = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) if self.use_res: self.W_Res = nn.Parameter(torch.Tensor(embedding_size, self. att_embedding_size * self.head_num)) for tensor in self.parameters(): nn.init.normal_(tensor, mean=0.0, std=0.05) self def forward(self, input_0): primals_2 = self.W_Query primals_3 = self.W_key primals_4 = self.W_Value primals_5 = self.W_Res primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
liyunrui/DeepCTR-Torch
InteractingLayer
false
12,726
[ "Apache-2.0" ]
0
392fd6d39d9ca0ac854022136cdb4d5c68e3a592
https://github.com/liyunrui/DeepCTR-Torch/tree/392fd6d39d9ca0ac854022136cdb4d5c68e3a592
DownConv
import torch import torch.nn as nn import torch.nn.functional as F def conv3x3(in_channels, out_channels, stride=1, padding=1, bias=True, groups=1 ): return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride= stride, padding=padding, bias=bias, groups=groups) class DownConv(nn.Module): """ A helper Module that performs 2 convolutions and 1 MaxPool. A ReLU activation follows each convolution. """ def __init__(self, in_channels, out_channels, pooling=True): super(DownConv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.pooling = pooling self.conv1 = conv3x3(self.in_channels, self.out_channels) self.conv2 = conv3x3(self.out_channels, self.out_channels) if self.pooling: self.pool = nn.MaxPool2d(kernel_size=2, stride=2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) before_pool = x if self.pooling: x = self.pool(x) return x, before_pool def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn 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 = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, 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 % 2 x1 = xindex // 2 x2 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), 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 + x2, tmp6, xmask) tl.store(out_ptr1 + x2, tmp16, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = 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(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_2, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_0[grid(256)](buf3, primals_5, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) buf5 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_1[grid(64)](buf3, buf4, buf5, 64, XBLOCK=64, num_warps=1, num_stages=1) return buf4, buf3, primals_1, primals_3, primals_4, buf1, buf3, buf5 def conv3x3(in_channels, out_channels, stride=1, padding=1, bias=True, groups=1 ): return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride= stride, padding=padding, bias=bias, groups=groups) class DownConvNew(nn.Module): """ A helper Module that performs 2 convolutions and 1 MaxPool. A ReLU activation follows each convolution. """ def __init__(self, in_channels, out_channels, pooling=True): super(DownConvNew, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.pooling = pooling self.conv1 = conv3x3(self.in_channels, self.out_channels) self.conv2 = conv3x3(self.out_channels, self.out_channels) if self.pooling: self.pool = nn.MaxPool2d(kernel_size=2, stride=2) def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1]
loftiskg/unet-pytorch
DownConv
false
12,727
[ "MIT" ]
0
38ddc3ddc3b00bfd575212484e05df1745504e5c
https://github.com/loftiskg/unet-pytorch/tree/38ddc3ddc3b00bfd575212484e05df1745504e5c
TransformerLayer
import math import torch import uuid from torch import Tensor import torch.nn as nn from typing import Tuple import torch.nn.functional as F from typing import Optional from typing import Dict from torch.nn import Parameter def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def utils_softmax(x, dim: 'int', onnx_trace: 'bool'=False): if onnx_trace: return F.softmax(x.float(), dim=dim) else: return F.softmax(x, dim=dim, dtype=torch.float32) def with_incremental_state(cls): cls.__bases__ = (FairseqIncrementalState,) + tuple(b for b in cls. __bases__ if b != FairseqIncrementalState) return cls class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int ) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = self.weight * x + self.bias return x class FairseqIncrementalState(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_incremental_state() def init_incremental_state(self): self._incremental_state_id = str(uuid.uuid4()) def _get_full_incremental_state_key(self, key: 'str') ->str: return '{}.{}'.format(self._incremental_state_id, key) def get_incremental_state(self, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]', key: 'str' ) ->Optional[Dict[str, Optional[Tensor]]]: """Helper for getting incremental state for an nn.Module.""" full_key = self._get_full_incremental_state_key(key) if incremental_state is None or full_key not in incremental_state: return None return incremental_state[full_key] def set_incremental_state(self, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]', key: 'str', value: 'Dict[str, Optional[Tensor]]') ->Optional[Dict[str, Dict[str, Optional[Tensor]]]]: """Helper for setting incremental state for an nn.Module.""" if incremental_state is not None: full_key = self._get_full_incremental_state_key(key) incremental_state[full_key] = value return incremental_state @with_incremental_state class MultiheadAttention(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout= 0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False): super().__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_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads' self.scaling = self.head_dim ** -0.5 self.self_attention = self_attention self.encoder_decoder_attention = encoder_decoder_attention assert not self.self_attention or self.qkv_same_dim, 'Self-attention requires query, key and value to be of the same size' self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias) self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) if add_bias_kv: self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim)) self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim)) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn self.reset_parameters() self.onnx_trace = False self.enable_torch_version = False if hasattr(F, 'multi_head_attention_forward'): self.enable_torch_version = True else: self.enable_torch_version = False def prepare_for_onnx_export_(self): self.onnx_trace = True def reset_parameters(self): if self.qkv_same_dim: nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2)) else: nn.init.xavier_uniform_(self.k_proj.weight) nn.init.xavier_uniform_(self.v_proj.weight) nn.init.xavier_uniform_(self.q_proj.weight) nn.init.xavier_uniform_(self.out_proj.weight) if self.out_proj.bias is not None: nn.init.constant_(self.out_proj.bias, 0.0) if self.bias_k is not None: nn.init.xavier_normal_(self.bias_k) if self.bias_v is not None: nn.init.xavier_normal_(self.bias_v) def forward(self, query, key: 'Optional[Tensor]', value: 'Optional[Tensor]', key_padding_mask: 'Optional[Tensor]'=None, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]'=None, need_weights: 'bool'=True, static_kv: 'bool'=False, attn_mask: 'Optional[Tensor]'=None, before_softmax: 'bool'=False, need_head_weights: 'bool'=False) ->Tuple[Tensor, Optional[Tensor]]: """Input shape: Time x Batch x Channel Args: key_padding_mask (ByteTensor, optional): mask to exclude keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s. need_weights (bool, optional): return the attention weights, averaged over heads (default: False). attn_mask (ByteTensor, optional): typically used to implement causal attention, where the mask prevents the attention from looking forward in time (default: None). before_softmax (bool, optional): return the raw attention weights and values before the attention softmax. need_head_weights (bool, optional): return the attention weights for each head. Implies *need_weights*. Default: return the average attention weights over all heads. """ if need_head_weights: need_weights = True tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] if (self.enable_torch_version and not self.onnx_trace and incremental_state is None and not static_kv and not torch.jit. is_scripting() and not need_head_weights): assert key is not None and value is not None return F.multi_head_attention_forward(query, key, value, self. embed_dim, self.num_heads, torch.empty([0]), torch.cat(( self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)), self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, self.training, key_padding_mask, need_weights, 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) if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if saved_state is not None and 'prev_key' in saved_state: if static_kv: assert self.encoder_decoder_attention and not self.self_attention key = value = None else: saved_state = None if self.self_attention: q = self.q_proj(query) k = self.k_proj(query) v = self.v_proj(query) elif self.encoder_decoder_attention: q = self.q_proj(query) if key is None: assert value is None k = v = None else: k = self.k_proj(key) v = self.v_proj(key) else: assert key is not None and value is not None q = self.q_proj(query) k = self.k_proj(key) v = self.v_proj(value) q *= self.scaling if self.bias_k is not None: assert self.bias_v is not None k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)]) v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)]) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros( attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat([key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1) ], dim=1) q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim ).transpose(0, 1) if k is not None: k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim ).transpose(0, 1) if v is not None: v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim ).transpose(0, 1) if saved_state is not None: if 'prev_key' in saved_state: _prev_key = saved_state['prev_key'] assert _prev_key is not None prev_key = _prev_key.view(bsz * self.num_heads, -1, self. head_dim) if static_kv: k = prev_key else: assert k is not None k = torch.cat([prev_key, k], dim=1) if 'prev_value' in saved_state: _prev_value = saved_state['prev_value'] assert _prev_value is not None prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim) if static_kv: v = prev_value else: assert v is not None v = torch.cat([prev_value, v], dim=1) prev_key_padding_mask: 'Optional[Tensor]' = None if 'prev_key_padding_mask' in saved_state: prev_key_padding_mask = saved_state['prev_key_padding_mask'] assert k is not None and v is not None key_padding_mask = (MultiheadAttention. _append_prev_key_padding_mask(key_padding_mask= key_padding_mask, prev_key_padding_mask= prev_key_padding_mask, batch_size=bsz, src_len=k.size(1), static_kv=static_kv)) saved_state['prev_key'] = k.view(bsz, self.num_heads, -1, self. head_dim) saved_state['prev_value'] = v.view(bsz, self.num_heads, -1, self.head_dim) saved_state['prev_key_padding_mask'] = key_padding_mask assert incremental_state is not None incremental_state = self._set_input_buffer(incremental_state, saved_state) assert k is not None src_len = k.size(1) if key_padding_mask is not None and key_padding_mask.dim() == 0: key_padding_mask = None if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len if self.add_zero_attn: assert v is not None src_len += 1 k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1) v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros( attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat([key_padding_mask, torch.zeros (key_padding_mask.size(0), 1).type_as(key_padding_mask) ], dim=1) attn_weights = torch.bmm(q, k.transpose(1, 2)) attn_weights = MultiheadAttention.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz) assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] if attn_mask is not None: attn_mask = attn_mask.unsqueeze(0) if self.onnx_trace: attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1) attn_weights += attn_mask if key_padding_mask is not None: attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill(key_padding_mask. unsqueeze(1).unsqueeze(2), float('-inf')) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) if before_softmax: return attn_weights, v attn_weights_float = utils_softmax(attn_weights, dim=-1, onnx_trace =self.onnx_trace) attn_weights = attn_weights_float.type_as(attn_weights) attn_probs = F.dropout(attn_weights_float.type_as(attn_weights), p= self.dropout, training=self.training) assert v is not None attn = torch.bmm(attn_probs, v) assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self. head_dim] if self.onnx_trace and attn.size(1) == 1: attn = attn.contiguous().view(tgt_len, bsz, embed_dim) else: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn = self.out_proj(attn) attn_weights: 'Optional[Tensor]' = None if need_weights: attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0) if not need_head_weights: attn_weights = attn_weights.mean(dim=0) return attn, attn_weights @staticmethod def _append_prev_key_padding_mask(key_padding_mask: 'Optional[Tensor]', prev_key_padding_mask: 'Optional[Tensor]', batch_size: 'int', src_len: 'int', static_kv: 'bool') ->Optional[Tensor]: if prev_key_padding_mask is not None and static_kv: new_key_padding_mask = prev_key_padding_mask elif prev_key_padding_mask is not None and key_padding_mask is not None: new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), key_padding_mask.float()], dim=1) elif prev_key_padding_mask is not None: filler = torch.zeros((batch_size, src_len - prev_key_padding_mask.size(1)), device= prev_key_padding_mask.device) new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), filler.float()], dim=1) elif key_padding_mask is not None: filler = torch.zeros((batch_size, src_len - key_padding_mask. size(1)), device=key_padding_mask.device) new_key_padding_mask = torch.cat([filler.float(), key_padding_mask.float()], dim=1) else: new_key_padding_mask = prev_key_padding_mask return new_key_padding_mask @torch.jit.export def reorder_incremental_state(self, incremental_state: 'Dict[str, Dict[str, Optional[Tensor]]]', new_order: 'Tensor'): """Reorder buffered internal state (for incremental generation).""" input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer_k = input_buffer[k] if input_buffer_k is not None: if self.encoder_decoder_attention and input_buffer_k.size(0 ) == new_order.size(0): break input_buffer[k] = input_buffer_k.index_select(0, new_order) incremental_state = self._set_input_buffer(incremental_state, input_buffer) return incremental_state def _get_input_buffer(self, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]') ->Dict[str, Optional[Tensor]]: result = self.get_incremental_state(incremental_state, 'attn_state') if result is not None: return result else: empty_result: 'Dict[str, Optional[Tensor]]' = {} return empty_result def _set_input_buffer(self, incremental_state: 'Dict[str, Dict[str, Optional[Tensor]]]', buffer: 'Dict[str, Optional[Tensor]]'): return self.set_incremental_state(incremental_state, 'attn_state', buffer) def apply_sparse_mask(attn_weights, tgt_len: 'int', src_len: 'int', bsz: 'int'): return attn_weights def upgrade_state_dict_named(self, state_dict, name): prefix = name + '.' if name != '' else '' items_to_add = {} keys_to_remove = [] for k in state_dict.keys(): if k.endswith(prefix + 'in_proj_weight'): dim = int(state_dict[k].shape[0] / 3) items_to_add[prefix + 'q_proj.weight'] = state_dict[k][:dim] items_to_add[prefix + 'k_proj.weight'] = state_dict[k][dim: 2 * dim] items_to_add[prefix + 'v_proj.weight'] = state_dict[k][2 * dim: ] keys_to_remove.append(k) k_bias = prefix + 'in_proj_bias' if k_bias in state_dict.keys(): dim = int(state_dict[k].shape[0] / 3) items_to_add[prefix + 'q_proj.bias'] = state_dict[k_bias][: dim] items_to_add[prefix + 'k_proj.bias'] = state_dict[k_bias][ dim:2 * dim] items_to_add[prefix + 'v_proj.bias'] = state_dict[k_bias][ 2 * dim:] keys_to_remove.append(prefix + 'in_proj_bias') for k in keys_to_remove: del state_dict[k] for key, value in items_to_add.items(): state_dict[key] = value class TransformerLayer(nn.Module): """Transformer layer block.""" def __init__(self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self._init_submodules(add_bias_kv, use_esm1b_layer_norm) def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = (ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm) self.self_attn = MultiheadAttention(self.embed_dim, self. attention_heads, add_bias_kv=add_bias_kv, add_zero_attn=False) self.self_attn_layer_norm = BertLayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, self.ffn_embed_dim) self.fc2 = nn.Linear(self.ffn_embed_dim, self.embed_dim) self.final_layer_norm = BertLayerNorm(self.embed_dim) def forward(self, x, self_attn_mask=None, self_attn_padding_mask=None, need_head_weights=False): residual = x x = self.self_attn_layer_norm(x) x, attn = self.self_attn(query=x, key=x, value=x, key_padding_mask= self_attn_padding_mask, need_weights=True, need_head_weights= need_head_weights, attn_mask=self_attn_mask) x = residual + x residual = x x = self.final_layer_norm(x) x = gelu(self.fc1(x)) x = self.fc2(x) x = residual + x return x, attn def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'embed_dim': 4, 'ffn_embed_dim': 4, 'attention_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 uuid from torch import Tensor import torch.nn as nn from typing import Tuple import torch.nn.functional as F from typing import Optional from typing import Dict from torch.nn import Parameter assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_mean_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) 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 = 4.0 tmp9 = tmp7 / tmp8 tmp10 = tmp0 - tmp9 tl.store(out_ptr0 + x2, tmp10, xmask) @triton.jit def triton_poi_fused_add_div_mean_mul_pow_sqrt_1(in_ptr0, in_ptr1, in_ptr2, 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_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp20 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp2 * tmp2 tmp5 = tmp4 * tmp4 tmp6 = tmp3 + tmp5 tmp8 = tmp7 * tmp7 tmp9 = tmp6 + tmp8 tmp11 = tmp10 * tmp10 tmp12 = tmp9 + tmp11 tmp13 = 4.0 tmp14 = tmp12 / tmp13 tmp15 = 1e-12 tmp16 = tmp14 + tmp15 tmp17 = libdevice.sqrt(tmp16) tmp18 = tmp1 / tmp17 tmp19 = tmp0 * tmp18 tmp21 = tmp19 + tmp20 tl.store(out_ptr0 + x2, tmp21, xmask) @triton.jit def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 12 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + 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 + x0), tmp9 & xmask, eviction_policy= 'evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tl.full([1], 12, tl.int64) tmp14 = tl.load(in_ptr2 + (-8 + x0), tmp11 & xmask, eviction_policy= 'evict_last', other=0.0) tmp15 = tl.where(tmp9, tmp10, tmp14) tmp16 = tl.where(tmp4, tmp5, tmp15) tl.store(out_ptr0 + x0, tmp16, xmask) @triton.jit def triton_poi_fused_cat_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 80 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 tmp0 = x2 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x3 + 16 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 5, tl.int64) tmp9 = tl.load(in_ptr1 + 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_mul_4(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 % 16 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = x2 % 4 tl.full([1], 0, tl.int64) tmp4 = tl.full([1], 4, tl.int64) tmp5 = tmp1 < tmp4 tmp6 = tl.load(in_ptr0 + x0 % 4, tmp5 & xmask, eviction_policy= 'evict_last', other=0.0) tmp7 = tmp1 >= tmp4 tmp8 = tl.full([1], 8, tl.int64) tmp9 = tmp1 < tmp8 tmp10 = tmp7 & tmp9 tmp11 = tl.load(in_ptr1 + (-4 + x0 % 4), tmp10 & xmask, eviction_policy ='evict_last', other=0.0) tmp12 = tmp1 >= tmp8 tl.full([1], 12, tl.int64) tmp15 = tl.load(in_ptr2 + (-8 + x0 % 4), tmp12 & xmask, eviction_policy ='evict_last', other=0.0) tmp16 = tl.where(tmp10, tmp11, tmp15) tmp17 = tl.where(tmp5, tmp6, tmp16) tmp18 = tmp0 + tmp17 tmp19 = 1.0 tmp20 = tmp18 * tmp19 tl.store(in_out_ptr0 + x2, tmp20, xmask) @triton.jit def triton_poi_fused__softmax_5(in_ptr0, 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 tmp0 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 5 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 5 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 5 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (4 + 5 * x0), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp0, tmp1) tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp6 = triton_helpers.maximum(tmp4, tmp5) tmp8 = triton_helpers.maximum(tmp6, tmp7) tmp9 = tmp0 - tmp8 tmp10 = tl_math.exp(tmp9) tmp11 = tmp1 - tmp8 tmp12 = tl_math.exp(tmp11) tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tl_math.exp(tmp14) tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tl_math.exp(tmp17) tmp19 = tmp16 + tmp18 tmp20 = tmp7 - tmp8 tmp21 = tl_math.exp(tmp20) tmp22 = tmp19 + tmp21 tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp22, xmask) @triton.jit def triton_poi_fused__softmax_6(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 320 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 5 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp3 = tl_math.exp(tmp2) tmp5 = tmp3 / tmp4 tl.store(in_out_ptr0 + x2, tmp5, xmask) @triton.jit def triton_poi_fused_clone_7(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_mean_8(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 80 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 20 x1 = xindex // 20 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 80 * x1), xmask) tmp1 = tl.load(in_ptr0 + (20 + x0 + 80 * x1), xmask) tmp3 = tl.load(in_ptr0 + (40 + x0 + 80 * x1), xmask) tmp5 = tl.load(in_ptr0 + (60 + x0 + 80 * 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_add_mean_pow_sub_9(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_10(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) @triton.jit def triton_poi_fused_add_div_erf_mul_11(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 + x0, xmask) tmp1 = 0.5 tmp2 = tmp0 * tmp1 tmp3 = 0.7071067811865475 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_12(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, primals_19) = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (1, 1, 4), (4, 4, 1)) assert_size_stride(primals_8, (1, 1, 4), (4, 4, 1)) assert_size_stride(primals_9, (4, 4), (4, 1)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (4, 4), (4, 1)) assert_size_stride(primals_12, (4, 4), (4, 1)) assert_size_stride(primals_13, (4, 4), (4, 1)) assert_size_stride(primals_14, (4,), (1,)) assert_size_stride(primals_15, (4,), (1,)) assert_size_stride(primals_16, (4, 4), (4, 1)) assert_size_stride(primals_17, (4,), (1,)) assert_size_stride(primals_18, (4, 4), (4, 1)) assert_size_stride(primals_19, (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_mean_sub_0[grid(64)](primals_1, buf0, 64, XBLOCK= 64, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_div_mean_mul_pow_sqrt_1[grid(64)](primals_2, buf0, primals_3, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_2 del primals_3 buf2 = reinterpret_tensor(buf0, (16, 4), (4, 1), 0) del buf0 extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf2) buf3 = empty_strided_cuda((12,), (1,), torch.float32) triton_poi_fused_cat_2[grid(12)](primals_4, primals_5, primals_6, buf3, 12, XBLOCK=16, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(buf3, (4,), (1,), 4), reinterpret_tensor(buf1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_12, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf4) buf5 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(buf3, (4,), (1,), 8), reinterpret_tensor(buf1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf5) del buf3 buf6 = empty_strided_cuda((5, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_cat_3[grid(80)](buf5, primals_8, buf6, 80, XBLOCK= 128, num_warps=4, num_stages=1) del primals_8 buf7 = reinterpret_tensor(buf2, (16, 4, 1), (1, 16, 64), 0) del buf2 triton_poi_fused_mul_4[grid(64)](buf7, primals_4, primals_5, primals_6, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_4 del primals_5 del primals_6 buf8 = empty_strided_cuda((5, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_cat_3[grid(80)](buf4, primals_7, buf8, 80, XBLOCK= 128, num_warps=4, num_stages=1) del primals_7 buf9 = empty_strided_cuda((16, 4, 5), (20, 5, 1), torch.float32) extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 1, 5), (1, 0, 16), 0), out=buf9) buf10 = reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 64), 0) del buf4 buf11 = reinterpret_tensor(buf5, (16, 4, 1), (4, 1, 64), 0) del buf5 triton_poi_fused__softmax_5[grid(64)](buf9, buf10, buf11, 64, XBLOCK=64, num_warps=1, num_stages=1) buf12 = buf9 del buf9 triton_poi_fused__softmax_6[grid(320)](buf12, buf10, buf11, 320, XBLOCK=256, num_warps=4, num_stages=1) buf13 = reinterpret_tensor(buf11, (16, 4, 1), (4, 1, 1), 0) del buf11 extern_kernels.bmm(buf12, reinterpret_tensor(buf6, (16, 5, 1), (1, 16, 0), 0), out=buf13) buf14 = reinterpret_tensor(buf10, (4, 16, 1), (16, 1, 1), 0) del buf10 triton_poi_fused_clone_7[grid(4, 16)](buf13, buf14, 4, 16, XBLOCK= 16, YBLOCK=4, num_warps=1, num_stages=1) buf15 = reinterpret_tensor(buf13, (16, 4), (4, 1), 0) del buf13 extern_kernels.addmm(primals_10, reinterpret_tensor(buf14, (16, 4), (4, 1), 0), reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf15) del primals_10 buf16 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32) triton_poi_fused_mean_8[grid(80)](buf12, buf16, 80, XBLOCK=128, num_warps=4, num_stages=1) buf17 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf18 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) triton_poi_fused_add_mean_pow_sub_9[grid(16)](primals_1, buf15, 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_add_div_mean_mul_sqrt_sub_10[grid(64)](primals_14, primals_1, buf15, buf17, buf18, primals_15, buf19, 64, XBLOCK= 64, num_warps=1, num_stages=1) del buf17 del buf18 del primals_15 buf20 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_17, reinterpret_tensor(buf19, (16, 4), (4, 1), 0), reinterpret_tensor(primals_16, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf20) del primals_17 buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_div_erf_mul_11[grid(64)](buf20, buf21, 64, XBLOCK=64, num_warps=1, num_stages=1) buf22 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf21, (16, 4), (4, 1), 0), reinterpret_tensor(primals_18, (4, 4), (1, 4), 0), out=buf22) buf23 = reinterpret_tensor(buf22, (4, 4, 4), (16, 4, 1), 0) del buf22 triton_poi_fused_add_12[grid(64)](buf23, primals_1, buf15, primals_19, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_19 return buf23, buf16, primals_1, primals_14, reinterpret_tensor(buf1, ( 16, 4), (4, 1), 0), buf12, reinterpret_tensor(buf14, (16, 4), (4, 1), 0 ), buf15, reinterpret_tensor(buf19, (16, 4), (4, 1), 0 ), buf20, reinterpret_tensor(buf21, (16, 4), (4, 1), 0 ), primals_18, primals_16, primals_9, reinterpret_tensor(buf6, (16, 1, 5), (1, 1, 16), 0), reinterpret_tensor(buf7, (16, 1, 4), (1, 1, 16), 0), reinterpret_tensor(buf8, (16, 5, 1), (1, 16, 1), 0 ), primals_13, primals_12, primals_11 def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def utils_softmax(x, dim: 'int', onnx_trace: 'bool'=False): if onnx_trace: return F.softmax(x.float(), dim=dim) else: return F.softmax(x, dim=dim, dtype=torch.float32) def with_incremental_state(cls): cls.__bases__ = (FairseqIncrementalState,) + tuple(b for b in cls. __bases__ if b != FairseqIncrementalState) return cls class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int ) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = self.weight * x + self.bias return x class FairseqIncrementalState(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.init_incremental_state() def init_incremental_state(self): self._incremental_state_id = str(uuid.uuid4()) def _get_full_incremental_state_key(self, key: 'str') ->str: return '{}.{}'.format(self._incremental_state_id, key) def get_incremental_state(self, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]', key: 'str' ) ->Optional[Dict[str, Optional[Tensor]]]: """Helper for getting incremental state for an nn.Module.""" full_key = self._get_full_incremental_state_key(key) if incremental_state is None or full_key not in incremental_state: return None return incremental_state[full_key] def set_incremental_state(self, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]', key: 'str', value: 'Dict[str, Optional[Tensor]]') ->Optional[Dict[str, Dict[str, Optional[Tensor]]]]: """Helper for setting incremental state for an nn.Module.""" if incremental_state is not None: full_key = self._get_full_incremental_state_key(key) incremental_state[full_key] = value return incremental_state @with_incremental_state class MultiheadAttention(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout= 0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False): super().__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_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads' self.scaling = self.head_dim ** -0.5 self.self_attention = self_attention self.encoder_decoder_attention = encoder_decoder_attention assert not self.self_attention or self.qkv_same_dim, 'Self-attention requires query, key and value to be of the same size' self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias) self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) if add_bias_kv: self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim)) self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim)) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn self.reset_parameters() self.onnx_trace = False self.enable_torch_version = False if hasattr(F, 'multi_head_attention_forward'): self.enable_torch_version = True else: self.enable_torch_version = False def prepare_for_onnx_export_(self): self.onnx_trace = True def reset_parameters(self): if self.qkv_same_dim: nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2)) nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2)) else: nn.init.xavier_uniform_(self.k_proj.weight) nn.init.xavier_uniform_(self.v_proj.weight) nn.init.xavier_uniform_(self.q_proj.weight) nn.init.xavier_uniform_(self.out_proj.weight) if self.out_proj.bias is not None: nn.init.constant_(self.out_proj.bias, 0.0) if self.bias_k is not None: nn.init.xavier_normal_(self.bias_k) if self.bias_v is not None: nn.init.xavier_normal_(self.bias_v) def forward(self, query, key: 'Optional[Tensor]', value: 'Optional[Tensor]', key_padding_mask: 'Optional[Tensor]'=None, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]'=None, need_weights: 'bool'=True, static_kv: 'bool'=False, attn_mask: 'Optional[Tensor]'=None, before_softmax: 'bool'=False, need_head_weights: 'bool'=False) ->Tuple[Tensor, Optional[Tensor]]: """Input shape: Time x Batch x Channel Args: key_padding_mask (ByteTensor, optional): mask to exclude keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s. need_weights (bool, optional): return the attention weights, averaged over heads (default: False). attn_mask (ByteTensor, optional): typically used to implement causal attention, where the mask prevents the attention from looking forward in time (default: None). before_softmax (bool, optional): return the raw attention weights and values before the attention softmax. need_head_weights (bool, optional): return the attention weights for each head. Implies *need_weights*. Default: return the average attention weights over all heads. """ if need_head_weights: need_weights = True tgt_len, bsz, embed_dim = query.size() assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] if (self.enable_torch_version and not self.onnx_trace and incremental_state is None and not static_kv and not torch.jit. is_scripting() and not need_head_weights): assert key is not None and value is not None return F.multi_head_attention_forward(query, key, value, self. embed_dim, self.num_heads, torch.empty([0]), torch.cat(( self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)), self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, self.training, key_padding_mask, need_weights, 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) if incremental_state is not None: saved_state = self._get_input_buffer(incremental_state) if saved_state is not None and 'prev_key' in saved_state: if static_kv: assert self.encoder_decoder_attention and not self.self_attention key = value = None else: saved_state = None if self.self_attention: q = self.q_proj(query) k = self.k_proj(query) v = self.v_proj(query) elif self.encoder_decoder_attention: q = self.q_proj(query) if key is None: assert value is None k = v = None else: k = self.k_proj(key) v = self.v_proj(key) else: assert key is not None and value is not None q = self.q_proj(query) k = self.k_proj(key) v = self.v_proj(value) q *= self.scaling if self.bias_k is not None: assert self.bias_v is not None k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)]) v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)]) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros( attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat([key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1) ], dim=1) q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim ).transpose(0, 1) if k is not None: k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim ).transpose(0, 1) if v is not None: v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim ).transpose(0, 1) if saved_state is not None: if 'prev_key' in saved_state: _prev_key = saved_state['prev_key'] assert _prev_key is not None prev_key = _prev_key.view(bsz * self.num_heads, -1, self. head_dim) if static_kv: k = prev_key else: assert k is not None k = torch.cat([prev_key, k], dim=1) if 'prev_value' in saved_state: _prev_value = saved_state['prev_value'] assert _prev_value is not None prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim) if static_kv: v = prev_value else: assert v is not None v = torch.cat([prev_value, v], dim=1) prev_key_padding_mask: 'Optional[Tensor]' = None if 'prev_key_padding_mask' in saved_state: prev_key_padding_mask = saved_state['prev_key_padding_mask'] assert k is not None and v is not None key_padding_mask = (MultiheadAttention. _append_prev_key_padding_mask(key_padding_mask= key_padding_mask, prev_key_padding_mask= prev_key_padding_mask, batch_size=bsz, src_len=k.size(1), static_kv=static_kv)) saved_state['prev_key'] = k.view(bsz, self.num_heads, -1, self. head_dim) saved_state['prev_value'] = v.view(bsz, self.num_heads, -1, self.head_dim) saved_state['prev_key_padding_mask'] = key_padding_mask assert incremental_state is not None incremental_state = self._set_input_buffer(incremental_state, saved_state) assert k is not None src_len = k.size(1) if key_padding_mask is not None and key_padding_mask.dim() == 0: key_padding_mask = None if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len if self.add_zero_attn: assert v is not None src_len += 1 k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1) v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1) if attn_mask is not None: attn_mask = torch.cat([attn_mask, attn_mask.new_zeros( attn_mask.size(0), 1)], dim=1) if key_padding_mask is not None: key_padding_mask = torch.cat([key_padding_mask, torch.zeros (key_padding_mask.size(0), 1).type_as(key_padding_mask) ], dim=1) attn_weights = torch.bmm(q, k.transpose(1, 2)) attn_weights = MultiheadAttention.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz) assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len] if attn_mask is not None: attn_mask = attn_mask.unsqueeze(0) if self.onnx_trace: attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1) attn_weights += attn_mask if key_padding_mask is not None: attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill(key_padding_mask. unsqueeze(1).unsqueeze(2), float('-inf')) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) if before_softmax: return attn_weights, v attn_weights_float = utils_softmax(attn_weights, dim=-1, onnx_trace =self.onnx_trace) attn_weights = attn_weights_float.type_as(attn_weights) attn_probs = F.dropout(attn_weights_float.type_as(attn_weights), p= self.dropout, training=self.training) assert v is not None attn = torch.bmm(attn_probs, v) assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self. head_dim] if self.onnx_trace and attn.size(1) == 1: attn = attn.contiguous().view(tgt_len, bsz, embed_dim) else: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim) attn = self.out_proj(attn) attn_weights: 'Optional[Tensor]' = None if need_weights: attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0) if not need_head_weights: attn_weights = attn_weights.mean(dim=0) return attn, attn_weights @staticmethod def _append_prev_key_padding_mask(key_padding_mask: 'Optional[Tensor]', prev_key_padding_mask: 'Optional[Tensor]', batch_size: 'int', src_len: 'int', static_kv: 'bool') ->Optional[Tensor]: if prev_key_padding_mask is not None and static_kv: new_key_padding_mask = prev_key_padding_mask elif prev_key_padding_mask is not None and key_padding_mask is not None: new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), key_padding_mask.float()], dim=1) elif prev_key_padding_mask is not None: filler = torch.zeros((batch_size, src_len - prev_key_padding_mask.size(1)), device= prev_key_padding_mask.device) new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), filler.float()], dim=1) elif key_padding_mask is not None: filler = torch.zeros((batch_size, src_len - key_padding_mask. size(1)), device=key_padding_mask.device) new_key_padding_mask = torch.cat([filler.float(), key_padding_mask.float()], dim=1) else: new_key_padding_mask = prev_key_padding_mask return new_key_padding_mask @torch.jit.export def reorder_incremental_state(self, incremental_state: 'Dict[str, Dict[str, Optional[Tensor]]]', new_order: 'Tensor'): """Reorder buffered internal state (for incremental generation).""" input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer_k = input_buffer[k] if input_buffer_k is not None: if self.encoder_decoder_attention and input_buffer_k.size(0 ) == new_order.size(0): break input_buffer[k] = input_buffer_k.index_select(0, new_order) incremental_state = self._set_input_buffer(incremental_state, input_buffer) return incremental_state def _get_input_buffer(self, incremental_state: 'Optional[Dict[str, Dict[str, Optional[Tensor]]]]') ->Dict[str, Optional[Tensor]]: result = self.get_incremental_state(incremental_state, 'attn_state') if result is not None: return result else: empty_result: 'Dict[str, Optional[Tensor]]' = {} return empty_result def _set_input_buffer(self, incremental_state: 'Dict[str, Dict[str, Optional[Tensor]]]', buffer: 'Dict[str, Optional[Tensor]]'): return self.set_incremental_state(incremental_state, 'attn_state', buffer) def apply_sparse_mask(attn_weights, tgt_len: 'int', src_len: 'int', bsz: 'int'): return attn_weights def upgrade_state_dict_named(self, state_dict, name): prefix = name + '.' if name != '' else '' items_to_add = {} keys_to_remove = [] for k in state_dict.keys(): if k.endswith(prefix + 'in_proj_weight'): dim = int(state_dict[k].shape[0] / 3) items_to_add[prefix + 'q_proj.weight'] = state_dict[k][:dim] items_to_add[prefix + 'k_proj.weight'] = state_dict[k][dim: 2 * dim] items_to_add[prefix + 'v_proj.weight'] = state_dict[k][2 * dim: ] keys_to_remove.append(k) k_bias = prefix + 'in_proj_bias' if k_bias in state_dict.keys(): dim = int(state_dict[k].shape[0] / 3) items_to_add[prefix + 'q_proj.bias'] = state_dict[k_bias][: dim] items_to_add[prefix + 'k_proj.bias'] = state_dict[k_bias][ dim:2 * dim] items_to_add[prefix + 'v_proj.bias'] = state_dict[k_bias][ 2 * dim:] keys_to_remove.append(prefix + 'in_proj_bias') for k in keys_to_remove: del state_dict[k] for key, value in items_to_add.items(): state_dict[key] = value class TransformerLayerNew(nn.Module): """Transformer layer block.""" def __init__(self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self._init_submodules(add_bias_kv, use_esm1b_layer_norm) def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = (ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm) self.self_attn = MultiheadAttention(self.embed_dim, self. attention_heads, add_bias_kv=add_bias_kv, add_zero_attn=False) self.self_attn_layer_norm = BertLayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, self.ffn_embed_dim) self.fc2 = nn.Linear(self.ffn_embed_dim, self.embed_dim) self.final_layer_norm = BertLayerNorm(self.embed_dim) def forward(self, input_0): primals_7 = self.self_attn.bias_k primals_8 = self.self_attn.bias_v primals_9 = self.self_attn.k_proj.weight primals_2 = self.self_attn.k_proj.bias primals_11 = self.self_attn.v_proj.weight primals_3 = self.self_attn.v_proj.bias primals_12 = self.self_attn.q_proj.weight primals_4 = self.self_attn.q_proj.bias primals_13 = self.self_attn.out_proj.weight primals_5 = self.self_attn.out_proj.bias primals_6 = self.self_attn_layer_norm.weight primals_10 = self.self_attn_layer_norm.bias primals_16 = self.fc1.weight primals_14 = self.fc1.bias primals_18 = self.fc2.weight primals_15 = self.fc2.bias primals_17 = self.final_layer_norm.weight primals_19 = self.final_layer_norm.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17, primals_18, primals_19]) return output[0], output[1]
leeharry92/esm
TransformerLayer
false
12,728
[ "MIT" ]
0
7d0feccf03ebbdeba4e7ba0f21d934099a0223ce
https://github.com/leeharry92/esm/tree/7d0feccf03ebbdeba4e7ba0f21d934099a0223ce
CrossNet
import torch import torch.nn as nn from sklearn.metrics import * class CrossNet(nn.Module): """The Cross Network part of Deep&Cross Network model, which leans both low and high degree cross feature. Input shape - 2D tensor with shape: ``(batch_size, units)``. Output shape - 2D tensor with shape: ``(batch_size, units)``. Arguments - **in_features** : Positive integer, dimensionality of input features. - **input_feature_num**: Positive integer, shape(Input tensor)[-1] - **layer_num**: Positive integer, the cross layer number - **parameterization**: string, ``"vector"`` or ``"matrix"`` , way to parameterize the cross network. - **l2_reg**: float between 0 and 1. L2 regularizer strength applied to the kernel weights matrix - **seed**: A Python integer to use as random seed. References - [Wang R, Fu B, Fu G, et al. Deep & cross network for ad click predictions[C]//Proceedings of the ADKDD'17. ACM, 2017: 12.](https://arxiv.org/abs/1708.05123) - [Wang R, Shivanna R, Cheng D Z, et al. DCN-M: Improved Deep & Cross Network for Feature Cross Learning in Web-scale Learning to Rank Systems[J]. 2020.](https://arxiv.org/abs/2008.13535) """ def __init__(self, in_features, layer_num=2, parameterization='vector', seed=1024, device='cpu'): super(CrossNet, self).__init__() self.layer_num = layer_num self.parameterization = parameterization if self.parameterization == 'vector': self.kernels = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1)) elif self.parameterization == 'matrix': self.kernels = nn.Parameter(torch.Tensor(self.layer_num, in_features, in_features)) else: raise ValueError("parameterization should be 'vector' or 'matrix'") self.bias = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1)) for i in range(self.kernels.shape[0]): nn.init.xavier_normal_(self.kernels[i]) for i in range(self.bias.shape[0]): nn.init.zeros_(self.bias[i]) self def forward(self, inputs): x_0 = inputs.unsqueeze(2) x_l = x_0 for i in range(self.layer_num): if self.parameterization == 'vector': xl_w = torch.tensordot(x_l, self.kernels[i], dims=([1], [0])) dot_ = torch.matmul(x_0, xl_w) x_l = dot_ + self.bias[i] + x_l elif self.parameterization == 'matrix': xl_w = torch.matmul(self.kernels[i], x_l) dot_ = xl_w + self.bias[i] x_l = x_0 * dot_ + x_l else: raise ValueError( "parameterization should be 'vector' or 'matrix'") x_l = torch.squeeze(x_l, dim=2) return x_l def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn from sklearn.metrics import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused__unsafe_view_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 x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (16 * x1 + 64 * (y0 // 16) + y0 % 16), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_clone_1(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 x0 = xindex % 16 x2 = xindex // 64 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tl.store(out_ptr0 + x3, tmp0, xmask) @triton.jit def triton_poi_fused_clone_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 % 16 x2 = xindex // 64 x3 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tl.store(out_ptr0 + x3, tmp0, xmask) @triton.jit def triton_poi_fused_clone_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x4 = xindex // 256 x5 = xindex // 16 % 16 x2 = xindex // 16 % 4 x6 = xindex // 4 % 16 x7 = xindex tmp0 = tl.load(in_ptr0 + (x5 + 16 * x0 + 64 * x4), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + (x6 + 16 * x0 + 64 * x4), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tl.store(out_ptr0 + x7, tmp4, xmask) @triton.jit def triton_poi_fused_add_squeeze_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x4 = xindex // 4 x1 = xindex // 4 % 4 x3 = xindex // 64 x6 = xindex % 16 x7 = xindex tmp0 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr3 + (x6 + 16 * x3), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp2 + tmp7 tl.store(out_ptr0 + x7, tmp8, 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, (2, 4, 1), (4, 1, 1)) assert_size_stride(primals_3, (2, 4, 1), (4, 1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__unsafe_view_clone_0[grid(64, 4)](primals_1, buf0, 64, 4, XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1) buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_2, (4, 1), (1, 1 ), 0), out=buf1) buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_poi_fused_clone_1[grid(1024)](primals_1, buf2, 1024, XBLOCK= 128, num_warps=4, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch .float32) triton_poi_fused_clone_2[grid(256)](buf1, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf1 buf4 = empty_strided_cuda((64, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf2, (64, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf3, (64, 4, 1), (4, 1, 0), 0), out=buf4) buf5 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_poi_fused_clone_3[grid(1024)](buf4, primals_3, primals_1, buf5, 1024, XBLOCK=128, num_warps=4, num_stages=1) buf6 = reinterpret_tensor(buf3, (256, 1), (1, 1), 0) del buf3 extern_kernels.mm(reinterpret_tensor(buf5, (256, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 1), (1, 1), 4), out=buf6) buf7 = empty_strided_cuda((64, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf2, (64, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf6, (64, 4, 1), (4, 1, 1), 0), out=buf7) del buf6 buf8 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1), torch.float32) triton_poi_fused_add_squeeze_4[grid(1024)](buf7, primals_3, buf4, primals_1, buf8, 1024, XBLOCK=256, num_warps=4, num_stages=1) del buf4 del buf7 del primals_1 del primals_3 return buf8, reinterpret_tensor(buf2, (64, 4, 4), (16, 1, 4), 0 ), reinterpret_tensor(buf5, (4, 256), (1, 4), 0), reinterpret_tensor( primals_2, (1, 4), (1, 1), 4), reinterpret_tensor(buf0, (4, 64), (1, 4), 0) class CrossNetNew(nn.Module): """The Cross Network part of Deep&Cross Network model, which leans both low and high degree cross feature. Input shape - 2D tensor with shape: ``(batch_size, units)``. Output shape - 2D tensor with shape: ``(batch_size, units)``. Arguments - **in_features** : Positive integer, dimensionality of input features. - **input_feature_num**: Positive integer, shape(Input tensor)[-1] - **layer_num**: Positive integer, the cross layer number - **parameterization**: string, ``"vector"`` or ``"matrix"`` , way to parameterize the cross network. - **l2_reg**: float between 0 and 1. L2 regularizer strength applied to the kernel weights matrix - **seed**: A Python integer to use as random seed. References - [Wang R, Fu B, Fu G, et al. Deep & cross network for ad click predictions[C]//Proceedings of the ADKDD'17. ACM, 2017: 12.](https://arxiv.org/abs/1708.05123) - [Wang R, Shivanna R, Cheng D Z, et al. DCN-M: Improved Deep & Cross Network for Feature Cross Learning in Web-scale Learning to Rank Systems[J]. 2020.](https://arxiv.org/abs/2008.13535) """ def __init__(self, in_features, layer_num=2, parameterization='vector', seed=1024, device='cpu'): super(CrossNetNew, self).__init__() self.layer_num = layer_num self.parameterization = parameterization if self.parameterization == 'vector': self.kernels = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1)) elif self.parameterization == 'matrix': self.kernels = nn.Parameter(torch.Tensor(self.layer_num, in_features, in_features)) else: raise ValueError("parameterization should be 'vector' or 'matrix'") self.bias = nn.Parameter(torch.Tensor(self.layer_num, in_features, 1)) for i in range(self.kernels.shape[0]): nn.init.xavier_normal_(self.kernels[i]) for i in range(self.bias.shape[0]): nn.init.zeros_(self.bias[i]) self def forward(self, input_0): primals_2 = self.kernels primals_3 = self.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
liyunrui/DeepCTR-Torch
CrossNet
false
12,729
[ "Apache-2.0" ]
0
392fd6d39d9ca0ac854022136cdb4d5c68e3a592
https://github.com/liyunrui/DeepCTR-Torch/tree/392fd6d39d9ca0ac854022136cdb4d5c68e3a592
piNetwork
import torch import torch.nn as nn class piNetwork(nn.Module): def __init__(self, input_size, hidden_size1, hidden_size2, action_size): super(piNetwork, self).__init__() self.l1 = nn.Linear(input_size, hidden_size1) self.l2 = nn.Linear(hidden_size1, hidden_size2) self.l3 = nn.Linear(hidden_size2, action_size) def forward(self, x): x = torch.tanh(self.l1(x)) x = torch.tanh(self.l2(x)) x = torch.softmax(self.l3(x), dim=-1) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_size': 4, 'hidden_size1': 4, 'hidden_size2': 4, 'action_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_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__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) 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=256, 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=256, 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__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1) buf6 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf4 triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf5 return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf1, buf3, buf6, primals_6, primals_4 class piNetworkNew(nn.Module): def __init__(self, input_size, hidden_size1, hidden_size2, action_size): super(piNetworkNew, self).__init__() self.l1 = nn.Linear(input_size, hidden_size1) self.l2 = nn.Linear(hidden_size1, hidden_size2) self.l3 = nn.Linear(hidden_size2, action_size) 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]
lolcharles2/TetrisReinforcementLearning
piNetwork
false
12,730
[ "MIT" ]
0
5e3d5035732a19681aca57f025d8378a8fc119e8
https://github.com/lolcharles2/TetrisReinforcementLearning/tree/5e3d5035732a19681aca57f025d8378a8fc119e8
KLDivLossWithLogits
import torch import torch.utils.data import torch from torchvision.transforms import functional as F from torch import nn from torch.nn import functional as F class AbstractConsistencyLoss(nn.Module): def __init__(self, reduction='mean'): super().__init__() self.reduction = reduction def forward(self, logits1, logits2): raise NotImplementedError class KLDivLossWithLogits(AbstractConsistencyLoss): def __init__(self, reduction='mean'): super().__init__(reduction) self.kl_div_loss = nn.KLDivLoss(reduction=reduction) def forward(self, logits1, logits2): return self.kl_div_loss(F.log_softmax(logits1, dim=1), F.softmax( logits2, dim=1)) 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.utils.data import torch from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel 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__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__softmax_mean_mul_sub_xlogy_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' ) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp17 = tl.load(in_ptr1 + r3, None) tmp18 = tl.load(in_ptr1 + (r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp20 = tl.load(in_ptr1 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr1 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp26 = tl.load(in_ptr1 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tmp9 = libdevice.isnan(tmp8).to(tl.int1) tmp10 = 0.0 tmp11 = tmp8 == tmp10 tmp12 = tl_math.log(tmp8) tmp13 = tmp8 * tmp12 tmp14 = tl.where(tmp11, tmp10, tmp13) tmp15 = float('nan') tmp16 = tl.where(tmp9, tmp15, tmp14) tmp19 = tl_math.exp(tmp18) tmp21 = tl_math.exp(tmp20) tmp22 = tmp19 + tmp21 tmp24 = tl_math.exp(tmp23) tmp25 = tmp22 + tmp24 tmp27 = tl_math.exp(tmp26) tmp28 = tmp25 + tmp27 tmp29 = tl_math.log(tmp28) tmp30 = tmp17 - tmp29 tmp31 = tmp8 * tmp30 tmp32 = tmp16 - tmp31 tmp33 = tl.broadcast_to(tmp32, [RBLOCK]) tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0)) tmp36 = 256.0 tmp37 = tmp35 / 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) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK= 256, num_warps=4, num_stages=1) del arg1_1 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__log_softmax_1[grid(256)](arg0_1, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 buf3 = empty_strided_cuda((), (), torch.float32) buf4 = buf3 del buf3 triton_per_fused__log_softmax__softmax_mean_mul_sub_xlogy_2[grid(1)]( buf4, buf0, buf2, 1, 256, num_warps=2, num_stages=1) del buf0 del buf2 return buf4, class AbstractConsistencyLoss(nn.Module): def __init__(self, reduction='mean'): super().__init__() self.reduction = reduction def forward(self, logits1, logits2): raise NotImplementedError class KLDivLossWithLogitsNew(AbstractConsistencyLoss): def __init__(self, reduction='mean'): super().__init__(reduction) self.kl_div_loss = nn.KLDivLoss(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]
lizhenbang56/END-TO-END-TEMPORAL-FEATURE-AGGREGATION-FOR-SIAMESE-TRACKERS
KLDivLossWithLogits
false
12,731
[ "MIT" ]
0
132b2e28b7f66c6ba0719774e9abd9b6515dd7e2
https://github.com/lizhenbang56/END-TO-END-TEMPORAL-FEATURE-AGGREGATION-FOR-SIAMESE-TRACKERS/tree/132b2e28b7f66c6ba0719774e9abd9b6515dd7e2
PreNet
import torch from torch import nn import torch.nn.functional as F class PreNet(nn.Module): def __init__(self, in_dims, fc1_dims=256, fc2_dims=128, dropout=0.5): super().__init__() self.fc1 = nn.Linear(in_dims, fc1_dims) self.fc2 = nn.Linear(fc1_dims, fc2_dims) self.p = dropout def forward(self, x): x = self.fc1(x) x = F.relu(x) x = F.dropout(x, self.p, training=True) x = self.fc2(x) x = F.relu(x) x = F.dropout(x, self.p, training=True) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_dims': 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, 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 % 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 = 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, (128, 256), (256, 1)) assert_size_stride(primals_5, (128,), (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 buf11 = 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, buf11, 16384, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = torch.ops.aten.native_dropout.default(buf1, 0.5, True) del buf1 buf3 = buf2[0] buf4 = buf2[1] del buf2 buf5 = empty_strided_cuda((64, 128), (128, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (64, 256), (256, 1), 0), reinterpret_tensor(primals_4, (256, 128), (1, 256), 0), out=buf5) buf6 = reinterpret_tensor(buf5, (4, 4, 4, 128), (2048, 512, 128, 1), 0) del buf5 buf10 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1), torch.bool) triton_poi_fused_relu_threshold_backward_1[grid(8192)](buf6, primals_5, buf10, 8192, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf7 = torch.ops.aten.native_dropout.default(buf6, 0.5, True) del buf6 buf8 = buf7[0] buf9 = buf7[1] del buf7 return buf8, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf4, reinterpret_tensor(buf3, (64, 256), (256, 1), 0 ), buf9, buf10, primals_4, buf11 class PreNetNew(nn.Module): def __init__(self, in_dims, fc1_dims=256, fc2_dims=128, dropout=0.5): super().__init__() self.fc1 = nn.Linear(in_dims, fc1_dims) self.fc2 = nn.Linear(fc1_dims, fc2_dims) self.p = dropout def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
lsh950919/sv2tts
PreNet
false
12,733
[ "MIT" ]
0
a6ff637ac478b8b3ce4dcc5a776442cab9cbdd67
https://github.com/lsh950919/sv2tts/tree/a6ff637ac478b8b3ce4dcc5a776442cab9cbdd67
AxialPositionalEmbedding
import torch from torch import nn class AxialPositionalEmbedding(nn.Module): def __init__(self, dim, shape, emb_dim_index=1): super().__init__() total_dimensions = len(shape) + 2 ax_dim_indexes = [i for i in range(1, total_dimensions) if i != emb_dim_index] self.num_axials = len(shape) for i, (axial_dim, axial_dim_index) in enumerate(zip(shape, ax_dim_indexes)): shape = [1] * total_dimensions shape[emb_dim_index] = dim shape[axial_dim_index] = axial_dim parameter = nn.Parameter(torch.randn(*shape)) setattr(self, f'param_{i}', parameter) def forward(self, x): for i in range(self.num_axials): x = x + getattr(self, f'param_{i}') return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'dim': 4, 'shape': [4, 4]}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_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 x4 = xindex x5 = xindex // 4 % 16 x0 = xindex % 4 x2 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x4, xmask) tmp1 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tl.store(out_ptr0 + x4, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (1, 4, 4, 1), (16, 4, 1, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (1, 4, 1, 4), (16, 4, 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_0[grid(256)](primals_2, primals_1, primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 del primals_2 del primals_3 return buf0, class AxialPositionalEmbeddingNew(nn.Module): def __init__(self, dim, shape, emb_dim_index=1): super().__init__() total_dimensions = len(shape) + 2 ax_dim_indexes = [i for i in range(1, total_dimensions) if i != emb_dim_index] self.num_axials = len(shape) for i, (axial_dim, axial_dim_index) in enumerate(zip(shape, ax_dim_indexes)): shape = [1] * total_dimensions shape[emb_dim_index] = dim shape[axial_dim_index] = axial_dim parameter = nn.Parameter(torch.randn(*shape)) setattr(self, f'param_{i}', parameter) def forward(self, input_0): primals_1 = self.param_0 primals_3 = self.param_1 primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
lukeleeai/metnet
AxialPositionalEmbedding
false
12,734
[ "MIT" ]
0
1dc0bf11780f413f3d55207866e0fa921b8aa60d
https://github.com/lukeleeai/metnet/tree/1dc0bf11780f413f3d55207866e0fa921b8aa60d
AUGRUCell
import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import * class AUGRUCell(nn.Module): """ Effect of GRU with attentional update gate (AUGRU) Reference: - Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018. """ def __init__(self, input_size, hidden_size, bias=True): super(AUGRUCell, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.weight_ih = nn.Parameter(torch.Tensor(3 * hidden_size, input_size) ) self.register_parameter('weight_ih', self.weight_ih) self.weight_hh = nn.Parameter(torch.Tensor(3 * hidden_size, hidden_size)) self.register_parameter('weight_hh', self.weight_hh) if bias: self.bias_ih = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_ih', self.bias_ih) self.bias_hh = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_ih', self.bias_hh) for tensor in [self.bias_ih, self.bias_hh]: nn.init.zeros_(tensor) else: self.register_parameter('bias_ih', None) self.register_parameter('bias_hh', None) def forward(self, input, hx, att_score): gi = F.linear(input, self.weight_ih, self.bias_ih) gh = F.linear(hx, self.weight_hh, self.bias_hh) i_r, i_z, i_n = gi.chunk(3, 1) h_r, h_z, h_n = gh.chunk(3, 1) reset_gate = torch.sigmoid(i_r + h_r) update_gate = torch.sigmoid(i_z + h_z) new_state = torch.tanh(i_n + reset_gate * h_n) att_score = att_score.view(-1, 1) update_gate = att_score * update_gate hy = (1.0 - update_gate) * hx + update_gate * new_state return hy def get_inputs(): return [torch.rand([64, 4]), torch.rand([64, 4]), torch.rand([16, 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.triton_helpers import libdevice import torch.nn as nn from sklearn.metrics import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_add_mul_rsub_sigmoid_tanh_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2, out_ptr3, 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 + (4 + x0 + 12 * x1), xmask) tmp1 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + (4 + x0 + 12 * x1), xmask) tmp6 = tl.load(in_ptr0 + (x0 + 12 * x1), xmask) tmp7 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr2 + (x0 + 12 * x1), xmask) tmp12 = tl.load(in_ptr0 + (8 + x0 + 12 * x1), xmask) tmp13 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last') tmp15 = tl.load(in_ptr2 + (8 + x0 + 12 * x1), xmask) tmp19 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp23 = tl.load(in_ptr4 + x2, xmask) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp5 = tl.sigmoid(tmp4) tmp8 = tmp6 + tmp7 tmp10 = tmp8 + tmp9 tmp11 = tl.sigmoid(tmp10) tmp14 = tmp12 + tmp13 tmp16 = tmp11 * tmp15 tmp17 = tmp14 + tmp16 tmp18 = libdevice.tanh(tmp17) tmp20 = tmp19 * tmp5 tmp21 = 1.0 tmp22 = tmp21 - tmp20 tmp24 = tmp22 * tmp23 tmp25 = tmp20 * tmp18 tmp26 = tmp24 + tmp25 tl.store(out_ptr0 + x2, tmp5, xmask) tl.store(out_ptr1 + x2, tmp11, xmask) tl.store(out_ptr2 + x2, tmp18, xmask) tl.store(out_ptr3 + x2, tmp26, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args args.clear() assert_size_stride(primals_1, (12, 4), (4, 1)) assert_size_stride(primals_2, (12,), (1,)) assert_size_stride(primals_3, (64, 4), (4, 1)) assert_size_stride(primals_4, (12, 4), (4, 1)) assert_size_stride(primals_5, (64, 4), (4, 1)) assert_size_stride(primals_6, (16, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 12), (12, 1), torch.float32) extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 12), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((64, 12), (12, 1), torch.float32) extern_kernels.addmm(primals_2, primals_5, reinterpret_tensor( primals_4, (4, 12), (1, 4), 0), alpha=1, beta=1, out=buf1) del primals_4 buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32) buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_rsub_sigmoid_tanh_0[grid(256)](buf0, primals_2, buf1, primals_6, primals_5, buf3, buf2, buf4, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del primals_2 return buf5, primals_3, primals_5, primals_6, reinterpret_tensor(buf1, (64, 4), (12, 1), 8), buf2, buf3, buf4 class AUGRUCellNew(nn.Module): """ Effect of GRU with attentional update gate (AUGRU) Reference: - Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018. """ def __init__(self, input_size, hidden_size, bias=True): super(AUGRUCellNew, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bias = bias self.weight_ih = nn.Parameter(torch.Tensor(3 * hidden_size, input_size) ) self.register_parameter('weight_ih', self.weight_ih) self.weight_hh = nn.Parameter(torch.Tensor(3 * hidden_size, hidden_size)) self.register_parameter('weight_hh', self.weight_hh) if bias: self.bias_ih = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_ih', self.bias_ih) self.bias_hh = nn.Parameter(torch.Tensor(3 * hidden_size)) self.register_parameter('bias_ih', self.bias_hh) for tensor in [self.bias_ih, self.bias_hh]: nn.init.zeros_(tensor) else: self.register_parameter('bias_ih', None) self.register_parameter('bias_hh', None) def forward(self, input_0, input_1, input_2): primals_1 = self.weight_ih primals_4 = self.weight_hh primals_2 = self.bias_ih primals_3 = input_0 primals_5 = input_1 primals_6 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
liyunrui/DeepCTR-Torch
AUGRUCell
false
12,735
[ "Apache-2.0" ]
0
392fd6d39d9ca0ac854022136cdb4d5c68e3a592
https://github.com/liyunrui/DeepCTR-Torch/tree/392fd6d39d9ca0ac854022136cdb4d5c68e3a592
SmallMnist
import torch import torch.nn as nn import torch.nn import torch.utils.data import torch.utils.tensorboard._pytorch_graph import torch.onnx.symbolic_caffe2 class SmallMnist(nn.Module): def __init__(self): super(SmallMnist, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.relu1 = nn.ReLU() self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.relu2 = nn.ReLU() self.fc1 = nn.Linear(320, 50) self.relu3 = nn.ReLU() self.dropout = nn.Dropout() self.fc2 = nn.Linear(50, 10) self.log_softmax = nn.LogSoftmax(dim=1) def forward(self, x): x = self.relu1(self.conv1(x)) x = self.conv2(x) x = self.relu2(self.conv2_drop(x)) x = x.view(-1, 320) x = self.relu3(self.fc1(x)) x = self.dropout(x) x = self.fc2(x) return self.log_softmax(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 math as tl_math import torch.nn as nn import torch.nn import torch.utils.data import torch.utils.tensorboard._pytorch_graph import torch.onnx.symbolic_caffe2 assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 144000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3600 % 10 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_threshold_backward_1(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 250880 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x4 = xindex x1 = xindex // 3136 % 20 x0 = xindex % 3136 x3 = xindex // 3136 tmp0 = tl.load(in_out_ptr0 + x4, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x4, tmp4, xmask) tl.store(out_ptr0 + (x0 + 3200 * x3), tmp6, xmask) @triton.jit def triton_poi_fused_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 39200 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 50 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_per_fused__log_softmax_3(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 784 rnumel = 10 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, :] rmask = rindex < rnumel r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 10 * x0), rmask & xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(rmask & 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(rmask & xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tmp11 = tl_math.log(tmp10) tmp12 = tmp5 - tmp11 tl.store(out_ptr2 + (r1 + 10 * x0), tmp12, rmask & xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = args args.clear() assert_size_stride(primals_1, (10, 1, 5, 5), (25, 25, 5, 1)) assert_size_stride(primals_2, (10,), (1,)) assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1)) assert_size_stride(primals_4, (20, 10, 5, 5), (250, 25, 5, 1)) assert_size_stride(primals_5, (20,), (1,)) assert_size_stride(primals_6, (50, 320), (320, 1)) assert_size_stride(primals_7, (50,), (1,)) assert_size_stride(primals_8, (10, 50), (50, 1)) assert_size_stride(primals_9, (10,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 10, 60, 60), (36000, 3600, 60, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(144000)](buf1, primals_2, 144000, 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, 20, 56, 56), (62720, 3136, 56, 1)) buf3 = buf2 del buf2 buf10 = empty_strided_cuda((4, 20, 56, 56), (64000, 3200, 56, 1), torch.bool) triton_poi_fused_convolution_relu_threshold_backward_1[grid(250880)]( buf3, primals_5, buf10, 250880, XBLOCK=512, num_warps=8, num_stages=1) del primals_5 buf4 = empty_strided_cuda((784, 50), (50, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf3, (784, 320), (320, 1), 0), reinterpret_tensor(primals_6, (320, 50), (1, 320), 0), out=buf4) buf5 = buf4 del buf4 triton_poi_fused_relu_2[grid(39200)](buf5, primals_7, 39200, XBLOCK =256, num_warps=4, num_stages=1) del primals_7 buf6 = empty_strided_cuda((784, 10), (10, 1), torch.float32) extern_kernels.addmm(primals_9, buf5, reinterpret_tensor(primals_8, (50, 10), (1, 50), 0), alpha=1, beta=1, out=buf6) del primals_9 buf9 = empty_strided_cuda((784, 10), (10, 1), torch.float32) triton_per_fused__log_softmax_3[grid(784)](buf6, buf9, 784, 10, XBLOCK=128, num_warps=8, num_stages=1) del buf6 return buf9, primals_1, primals_3, primals_4, buf1, reinterpret_tensor(buf3 , (784, 320), (320, 1), 0), buf5, buf9, primals_8, primals_6, buf10 class SmallMnistNew(nn.Module): def __init__(self): super(SmallMnistNew, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.relu1 = nn.ReLU() self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.relu2 = nn.ReLU() self.fc1 = nn.Linear(320, 50) self.relu3 = nn.ReLU() self.dropout = nn.Dropout() self.fc2 = nn.Linear(50, 10) self.log_softmax = nn.LogSoftmax(dim=1) def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_6 = self.fc1.weight primals_7 = self.fc1.bias primals_8 = self.fc2.weight primals_9 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9]) return output[0]
arjunsuresh/aimet
SmallMnist
false
12,736
[ "BSD-3-Clause" ]
0
f6e09cb07a91eed3a5e6b8e19e6b065303af5a39
https://github.com/arjunsuresh/aimet/tree/f6e09cb07a91eed3a5e6b8e19e6b065303af5a39
AFMLayer
import itertools import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import * class AFMLayer(nn.Module): """Attentonal Factorization Machine models pairwise (order-2) feature interactions without linear term and bias. Input shape - A list of 3D tensor with shape: ``(batch_size,1,embedding_size)``. Output shape - 2D tensor with shape: ``(batch_size, 1)``. Arguments - **in_features** : Positive integer, dimensionality of input features. - **attention_factor** : Positive integer, dimensionality of the attention network output space. - **l2_reg_w** : float between 0 and 1. L2 regularizer strength applied to attention network. - **dropout_rate** : float between in [0,1). Fraction of the attention net output units to dropout. - **seed** : A Python integer to use as random seed. References - [Attentional Factorization Machines : Learning the Weight of Feature Interactions via Attention Networks](https://arxiv.org/pdf/1708.04617.pdf) """ def __init__(self, in_features, attention_factor=4, l2_reg_w=0, dropout_rate=0, seed=1024, device='cpu'): super(AFMLayer, self).__init__() self.attention_factor = attention_factor self.l2_reg_w = l2_reg_w self.dropout_rate = dropout_rate self.seed = seed embedding_size = in_features self.attention_W = nn.Parameter(torch.Tensor(embedding_size, self. attention_factor)) self.attention_b = nn.Parameter(torch.Tensor(self.attention_factor)) self.projection_h = nn.Parameter(torch.Tensor(self.attention_factor, 1) ) self.projection_p = nn.Parameter(torch.Tensor(embedding_size, 1)) for tensor in [self.attention_W, self.projection_h, self.projection_p]: nn.init.xavier_normal_(tensor) for tensor in [self.attention_b]: nn.init.zeros_(tensor) self.dropout = nn.Dropout(dropout_rate) self def forward(self, inputs): embeds_vec_list = inputs row = [] col = [] for r, c in itertools.combinations(embeds_vec_list, 2): row.append(r) col.append(c) p = torch.cat(row, dim=1) q = torch.cat(col, dim=1) inner_product = p * q bi_interaction = inner_product attention_temp = F.relu(torch.tensordot(bi_interaction, self. attention_W, dims=([-1], [0])) + self.attention_b) self.normalized_att_score = F.softmax(torch.tensordot( attention_temp, self.projection_h, dims=([-1], [0])), dim=1) attention_output = torch.sum(self.normalized_att_score * bi_interaction, dim=1) attention_output = self.dropout(attention_output) afm_out = torch.tensordot(attention_output, self.projection_p, dims =([-1], [0])) return afm_out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_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 math as tl_math import torch.nn as nn from sklearn.metrics import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_cat_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 384 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 24 x0 = xindex % 4 x2 = xindex // 96 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr0 + (x0 + 4 * (-4 + x1) + 16 * x2), tmp9 & xmask, other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr0 + (x0 + 4 * (-8 + x1) + 16 * x2), tmp14 & xmask, other=0.0) tmp16 = tmp0 >= tmp12 tmp17 = tl.full([1], 16, tl.int64) tmp18 = tmp0 < tmp17 tmp19 = tmp16 & tmp18 tmp20 = tl.load(in_ptr0 + (64 + x0 + 4 * (-12 + x1) + 16 * x2), tmp19 & xmask, other=0.0) tmp21 = tmp0 >= tmp17 tmp22 = tl.full([1], 20, tl.int64) tmp23 = tmp0 < tmp22 tmp24 = tmp21 & tmp23 tmp25 = tl.load(in_ptr0 + (64 + x0 + 4 * (-16 + x1) + 16 * x2), tmp24 & xmask, other=0.0) tmp26 = tmp0 >= tmp22 tl.full([1], 24, tl.int64) tmp29 = tl.load(in_ptr0 + (128 + x0 + 4 * (-20 + x1) + 16 * x2), tmp26 & xmask, other=0.0) tmp30 = tl.where(tmp24, tmp25, tmp29) tmp31 = tl.where(tmp19, tmp20, tmp30) tmp32 = tl.where(tmp14, tmp15, tmp31) tmp33 = tl.where(tmp9, tmp10, tmp32) tmp34 = tl.where(tmp4, tmp5, tmp33) tmp35 = tl.load(in_ptr0 + (64 + x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0) tmp36 = tl.load(in_ptr0 + (128 + x0 + 4 * (-4 + x1) + 16 * x2), tmp9 & xmask, other=0.0) tmp37 = tl.load(in_ptr0 + (192 + x0 + 4 * (-8 + x1) + 16 * x2), tmp14 & xmask, other=0.0) tmp38 = tl.load(in_ptr0 + (128 + x0 + 4 * (-12 + x1) + 16 * x2), tmp19 & xmask, other=0.0) tmp39 = tl.load(in_ptr0 + (192 + x0 + 4 * (-16 + x1) + 16 * x2), tmp24 & xmask, other=0.0) tmp40 = tl.load(in_ptr0 + (192 + x0 + 4 * (-20 + x1) + 16 * x2), tmp26 & xmask, other=0.0) tmp41 = tl.where(tmp24, tmp39, tmp40) tmp42 = tl.where(tmp19, tmp38, tmp41) tmp43 = tl.where(tmp14, tmp37, tmp42) tmp44 = tl.where(tmp9, tmp36, tmp43) tmp45 = tl.where(tmp4, tmp35, tmp44) tmp46 = tmp34 * tmp45 tl.store(in_out_ptr0 + x3, tmp46, xmask) @triton.jit def triton_poi_fused_add_relu_threshold_backward_1(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 384 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_per_fused__softmax_2(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 4 rnumel = 24 RBLOCK: tl.constexpr = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] rmask = rindex < rnumel r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 24 * x0), rmask & xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(rmask & 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(rmask & xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tmp11 = tmp6 / tmp10 tl.store(out_ptr2 + (r1 + 24 * x0), tmp11, rmask & xmask) @triton.jit def triton_per_fused_mul_sum_3(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 rnumel = 24 RBLOCK: tl.constexpr = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] rmask = rindex < rnumel r2 = rindex x1 = xindex // 4 x0 = xindex % 4 x3 = xindex tmp0 = tl.load(in_ptr0 + (r2 + 24 * x1), rmask & xmask, eviction_policy ='evict_last', other=0.0) tmp1 = tl.load(in_ptr1 + (x0 + 4 * r2 + 96 * x1), rmask & xmask, other=0.0) tmp2 = tmp0 * tmp1 tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.where(rmask & xmask, tmp3, 0) tmp6 = tl.sum(tmp5, 1)[:, None] tl.store(out_ptr0 + x3, 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, 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, 1), (1, 1)) assert_size_stride(primals_5, (4, 1), (1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 24, 4), (96, 4, 1), torch.float32) buf2 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_cat_mul_0[grid(384)](buf2, primals_1, 384, XBLOCK= 128, num_warps=4, num_stages=1) del primals_1 buf3 = empty_strided_cuda((96, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf2, (96, 4), (4, 1), 0), primals_2, out=buf3) del primals_2 buf4 = reinterpret_tensor(buf3, (4, 24, 4), (96, 4, 1), 0) del buf3 buf11 = empty_strided_cuda((4, 24, 4), (96, 4, 1), torch.bool) triton_poi_fused_add_relu_threshold_backward_1[grid(384)](buf4, primals_3, buf11, 384, XBLOCK=128, num_warps=4, num_stages=1) del primals_3 buf5 = empty_strided_cuda((96, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf4, (96, 4), (4, 1), 0), primals_4, out=buf5) buf8 = empty_strided_cuda((4, 24, 1), (24, 1, 1), torch.float32) triton_per_fused__softmax_2[grid(4)](buf5, buf8, 4, 24, XBLOCK=1, num_warps=2, num_stages=1) del buf5 buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_per_fused_mul_sum_3[grid(16)](buf8, buf2, buf9, 16, 24, XBLOCK=1, num_warps=2, num_stages=1) buf10 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.mm(buf9, primals_5, out=buf10) return buf10, buf8, buf2, buf8, reinterpret_tensor(buf9, (4, 4), (1, 4), 0 ), reinterpret_tensor(primals_5, (1, 4), (1, 1), 0 ), reinterpret_tensor(buf4, (4, 96), (1, 4), 0), reinterpret_tensor( primals_4, (1, 4), (1, 1), 0), buf11 class AFMLayerNew(nn.Module): """Attentonal Factorization Machine models pairwise (order-2) feature interactions without linear term and bias. Input shape - A list of 3D tensor with shape: ``(batch_size,1,embedding_size)``. Output shape - 2D tensor with shape: ``(batch_size, 1)``. Arguments - **in_features** : Positive integer, dimensionality of input features. - **attention_factor** : Positive integer, dimensionality of the attention network output space. - **l2_reg_w** : float between 0 and 1. L2 regularizer strength applied to attention network. - **dropout_rate** : float between in [0,1). Fraction of the attention net output units to dropout. - **seed** : A Python integer to use as random seed. References - [Attentional Factorization Machines : Learning the Weight of Feature Interactions via Attention Networks](https://arxiv.org/pdf/1708.04617.pdf) """ def __init__(self, in_features, attention_factor=4, l2_reg_w=0, dropout_rate=0, seed=1024, device='cpu'): super(AFMLayerNew, self).__init__() self.attention_factor = attention_factor self.l2_reg_w = l2_reg_w self.dropout_rate = dropout_rate self.seed = seed embedding_size = in_features self.attention_W = nn.Parameter(torch.Tensor(embedding_size, self. attention_factor)) self.attention_b = nn.Parameter(torch.Tensor(self.attention_factor)) self.projection_h = nn.Parameter(torch.Tensor(self.attention_factor, 1) ) self.projection_p = nn.Parameter(torch.Tensor(embedding_size, 1)) for tensor in [self.attention_W, self.projection_h, self.projection_p]: nn.init.xavier_normal_(tensor) for tensor in [self.attention_b]: nn.init.zeros_(tensor) self.dropout = nn.Dropout(dropout_rate) self def forward(self, input_0): primals_2 = self.attention_W primals_3 = self.attention_b primals_4 = self.projection_h primals_5 = self.projection_p primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
liyunrui/DeepCTR-Torch
AFMLayer
false
12,737
[ "Apache-2.0" ]
0
392fd6d39d9ca0ac854022136cdb4d5c68e3a592
https://github.com/liyunrui/DeepCTR-Torch/tree/392fd6d39d9ca0ac854022136cdb4d5c68e3a592
Classifier
import torch import torch.nn.functional as F from torch import nn class Classifier(nn.Module): """ Inherits Class information from the nn.Module and creates a Classifier Class: - Class has these attributes: o fully connected layer with specified number of in_features and out_features o number of hidden layers equivalent to the inputted requirements o dropout parameter for the fully connected layers - Class has a forward method: o Flattens the input data in an input layer for computation o Connects each layer with a relu activation, the defined dropout, and linear regression o Returns outputs from the final hidden layer into an categorical output probability using log_softmax Parameters: - in_features - hidden_layers - out_features """ def __init__(self, in_features, hidden_layers, out_features): super().__init__() self.in_features = in_features self.hidden_layers = hidden_layers self.out_features = out_features self._index = 1 while self._index < self.hidden_layers: setattr(self, 'fc' + str(self._index), nn.Linear(round(self. in_features / 2 ** (self._index - 1)), round(self. in_features / 2 ** self._index))) self._index += 1 setattr(self, 'fc' + str(self._index), nn.Linear(round(self. in_features / 2 ** (self._index - 1)), self.out_features)) self.dropout = nn.Dropout(p=0.3) def forward(self, x): x = x.view(x.shape[0], -1) self._index = 1 while self._index < self.hidden_layers: x = self.dropout(F.relu(getattr(self, 'fc' + str(self._index))(x))) self._index += 1 x = F.log_softmax(getattr(self, 'fc' + str(self._index))(x), dim=1) return x def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'hidden_layers': 1, 'out_features': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream 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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused__log_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') 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 = 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 tl.store(out_ptr0 + x2, tmp13, 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) extern_kernels.addmm(primals_3, primals_1, reinterpret_tensor( primals_2, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf0) del primals_2 del primals_3 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(16)](buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf2 = buf0 del buf0 triton_poi_fused__log_softmax_1[grid(16)](buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf1 return buf2, primals_1, buf2 class ClassifierNew(nn.Module): """ Inherits Class information from the nn.Module and creates a Classifier Class: - Class has these attributes: o fully connected layer with specified number of in_features and out_features o number of hidden layers equivalent to the inputted requirements o dropout parameter for the fully connected layers - Class has a forward method: o Flattens the input data in an input layer for computation o Connects each layer with a relu activation, the defined dropout, and linear regression o Returns outputs from the final hidden layer into an categorical output probability using log_softmax Parameters: - in_features - hidden_layers - out_features """ def __init__(self, in_features, hidden_layers, out_features): super().__init__() self.in_features = in_features self.hidden_layers = hidden_layers self.out_features = out_features self._index = 1 while self._index < self.hidden_layers: setattr(self, 'fc' + str(self._index), nn.Linear(round(self. in_features / 2 ** (self._index - 1)), round(self. in_features / 2 ** self._index))) self._index += 1 setattr(self, 'fc' + str(self._index), nn.Linear(round(self. in_features / 2 ** (self._index - 1)), self.out_features)) self.dropout = nn.Dropout(p=0.3) def forward(self, input_0): primals_1 = self.fc1.weight primals_3 = self.fc1.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
lukeahwilson/udacity-final-project
Classifier
false
12,738
[ "MIT" ]
0
c5df25e2135b1dfdb3458d82c562979432480f5d
https://github.com/lukeahwilson/udacity-final-project/tree/c5df25e2135b1dfdb3458d82c562979432480f5d
SeparableConv1D
import torch from torch import nn class SeparableConv1D(nn.Module): """Depthwise separable 1D convolution. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. kernel_size (int): Size of the convolving kernel. stride (int): Stride of the convolution (default 1). dilation (int): Spacing between kernel elements (default 1). padding (int): Zero-padding added to both sides of the input. padding_mode (str): 'zeros', 'reflect', 'replicate' or 'circular' (default 'zeros'). bias (bool): If True, adds a learnable bias to the output (default: True). """ def __init__(self, in_channels: 'int', out_channels: 'int', kernel_size: 'int', stride: 'int'=1, dilation: 'int'=1, padding: 'int'=0, padding_mode: 'str'='zeros', bias: 'bool'=True): super().__init__() self.depthwise = nn.Conv1d(in_channels, in_channels, kernel_size= kernel_size, stride=stride, dilation=dilation, padding=padding, padding_mode=padding_mode, groups=in_channels, bias=bias) self.pointwise = nn.Conv1d(in_channels, out_channels, kernel_size=1) def forward(self, x): """ Args: x (torch.Tensor): Input tensor (batch, time, channels). Returns: torch.Tensor: Output tensor (batch, time, channels). """ x = x.transpose(1, -1) x = self.pointwise(self.depthwise(x)).transpose(1, -1) return x 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 from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride 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 = 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) 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, 4), (4, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4, 1), (4, 1, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1, 4, 4), (16, 4, 1), 0), primals_2, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=(0,), groups=4, bias=None) assert_size_stride(buf0, (1, 4, 1), (4, 1, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(4)](buf1, primals_3, 4, XBLOCK= 4, num_warps=1, num_stages=1) del primals_3 buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 1 ), (0, 1, 0), 0), primals_4, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=(0,), groups=1, bias=None) assert_size_stride(buf2, (1, 4, 1), (4, 1, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_0[grid(4)](buf3, primals_5, 4, XBLOCK= 4, num_warps=1, num_stages=1) del primals_5 return reinterpret_tensor(buf3, (4, 1), (1, 1), 0 ), primals_2, primals_4, reinterpret_tensor(primals_1, (1, 4, 4), ( 16, 4, 1), 0), buf1 class SeparableConv1DNew(nn.Module): """Depthwise separable 1D convolution. Args: in_channels (int): Number of input channels. out_channels (int): Number of output channels. kernel_size (int): Size of the convolving kernel. stride (int): Stride of the convolution (default 1). dilation (int): Spacing between kernel elements (default 1). padding (int): Zero-padding added to both sides of the input. padding_mode (str): 'zeros', 'reflect', 'replicate' or 'circular' (default 'zeros'). bias (bool): If True, adds a learnable bias to the output (default: True). """ def __init__(self, in_channels: 'int', out_channels: 'int', kernel_size: 'int', stride: 'int'=1, dilation: 'int'=1, padding: 'int'=0, padding_mode: 'str'='zeros', bias: 'bool'=True): super().__init__() self.depthwise = nn.Conv1d(in_channels, in_channels, kernel_size= kernel_size, stride=stride, dilation=dilation, padding=padding, padding_mode=padding_mode, groups=in_channels, bias=bias) self.pointwise = nn.Conv1d(in_channels, out_channels, kernel_size=1) def forward(self, input_0): primals_2 = self.depthwise.weight primals_3 = self.depthwise.bias primals_4 = self.pointwise.weight primals_5 = self.pointwise.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
johnjosephmorgan/snowfall
SeparableConv1D
false
12,739
[ "Apache-2.0" ]
0
604d789c0aed035626d6745e6d7a427168063cae
https://github.com/johnjosephmorgan/snowfall/tree/604d789c0aed035626d6745e6d7a427168063cae
Homography
import torch import torch.nn as nn class Homography(nn.Module): """Homography geometric model to be used together with ImageRegistrator module for the optimization-based image registration.""" def __init__(self) ->None: super().__init__() self.model = nn.Parameter(torch.eye(3)) self.reset_model() def __repr__(self) ->str: return f'{self.__class__.__name__}({self.model})' def reset_model(self): """Initializes the model with identity transform.""" torch.nn.init.eye_(self.model) def forward(self) ->torch.Tensor: """Single-batch homography". Returns: Homography matrix with shape :math:`(1, 3, 3)`. """ return torch.unsqueeze(self.model / self.model[2, 2], dim=0) def forward_inverse(self) ->torch.Tensor: """Interted Single-batch homography". Returns: Homography martix with shape :math:`(1, 3, 3)`. """ return torch.unsqueeze(torch.inverse(self.model), dim=0) def get_inputs(): return [] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda 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 = 9 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_ptr0 + 8) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp3 = tmp0 / tmp2 tl.store(out_ptr0 + x0, tmp3, xmask) def call(args): primals_1, = args args.clear() assert_size_stride(primals_1, (3, 3), (3, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((3, 3), (3, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_0[grid(9)](primals_1, buf0, 9, XBLOCK=16, num_warps=1, num_stages=1) return reinterpret_tensor(buf0, (1, 3, 3), (9, 3, 1), 0), primals_1 class HomographyNew(nn.Module): """Homography geometric model to be used together with ImageRegistrator module for the optimization-based image registration.""" def __init__(self) ->None: super().__init__() self.model = nn.Parameter(torch.eye(3)) self.reset_model() def __repr__(self) ->str: return f'{self.__class__.__name__}({self.model})' def reset_model(self): """Initializes the model with identity transform.""" torch.nn.init.eye_(self.model) def forward_inverse(self) ->torch.Tensor: """Interted Single-batch homography". Returns: Homography martix with shape :math:`(1, 3, 3)`. """ return torch.unsqueeze(torch.inverse(self.model), dim=0) def forward(self): primals_1 = self.model output = call([primals_1]) return output[0]
lyhyl/kornia
Homography
false
12,740
[ "ECL-2.0", "Apache-2.0" ]
0
5bd3aeb0d54dedac01e6eaf8bac37779bab0bec5
https://github.com/lyhyl/kornia/tree/5bd3aeb0d54dedac01e6eaf8bac37779bab0bec5
DCCWeightedELoss
import torch import numpy as np import torch.nn as nn class DCCWeightedELoss(nn.Module): def __init__(self, size_average=True): super(DCCWeightedELoss, self).__init__() self.size_average = size_average def forward(self, inputs, outputs, weights): out = (inputs - outputs).view(len(inputs), -1) out = torch.sum(weights * torch.norm(out, p=2, dim=1) ** 2) assert np.isfinite(out.data.cpu().numpy()).all(), 'Nan found in data' if self.size_average: out = out / inputs.nelement() return out 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 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_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 4 RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0) 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] tl.store(out_ptr0 + x0, tmp7, xmask) @triton.jit def triton_per_fused_div_linalg_vector_norm_mul_pow_sum_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 % 4 tmp0 = tl.load(in_ptr0 + r2, None) tmp1 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last') tmp2 = libdevice.sqrt(tmp1) tmp3 = tmp2 * tmp2 tmp4 = tmp0 * tmp3 tmp5 = tl.broadcast_to(tmp4, [RBLOCK]) tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0)) tmp8 = 0.00390625 tmp9 = tmp7 * tmp8 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, 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,), (1,), torch.float32) get_raw_stream(0) triton_per_fused_linalg_vector_norm_0[grid(4)](arg0_1, arg1_1, buf0, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused_div_linalg_vector_norm_mul_pow_sum_1[grid(1)](buf2, arg2_1, buf0, 1, 256, num_warps=2, num_stages=1) del arg2_1 del buf0 return buf2, class DCCWeightedELossNew(nn.Module): def __init__(self, size_average=True): super(DCCWeightedELossNew, self).__init__() self.size_average = size_average 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]
lbasora/DCC
DCCWeightedELoss
false
12,741
[ "MIT" ]
0
c9abcd7d697cc9e50e874286f1edfb3be93ce6d9
https://github.com/lbasora/DCC/tree/c9abcd7d697cc9e50e874286f1edfb3be93ce6d9
Hflip
import torch import torch.nn as nn def hflip(input: 'torch.Tensor') ->torch.Tensor: """Horizontally flip a tensor image or a batch of tensor images. .. image:: _static/img/hflip.png Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`. Args: input: input tensor. Returns: The horizontally flipped image tensor. """ w = input.shape[-1] return input[..., torch.arange(w - 1, -1, -1, device=input.device)] class Hflip(nn.Module): """Horizontally flip a tensor image or a batch of tensor images. Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`. Args: input: input tensor. Returns: The horizontally flipped image tensor. Examples: >>> hflip = Hflip() >>> input = torch.tensor([[[ ... [0., 0., 0.], ... [0., 0., 0.], ... [0., 1., 1.] ... ]]]) >>> hflip(input) tensor([[[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]]]) """ def forward(self, input: 'torch.Tensor') ->torch.Tensor: return hflip(input) def __repr__(self): return self.__class__.__name__ def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_index_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 x2 = xindex tmp0 = tl.load(in_ptr0 + (3 + -1 * x0 + 4 * x1), xmask, eviction_policy ='evict_last') 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, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_index_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, def hflip(input: 'torch.Tensor') ->torch.Tensor: """Horizontally flip a tensor image or a batch of tensor images. .. image:: _static/img/hflip.png Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`. Args: input: input tensor. Returns: The horizontally flipped image tensor. """ w = input.shape[-1] return input[..., torch.arange(w - 1, -1, -1, device=input.device)] class HflipNew(nn.Module): """Horizontally flip a tensor image or a batch of tensor images. Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`. Args: input: input tensor. Returns: The horizontally flipped image tensor. Examples: >>> hflip = Hflip() >>> input = torch.tensor([[[ ... [0., 0., 0.], ... [0., 0., 0.], ... [0., 1., 1.] ... ]]]) >>> hflip(input) tensor([[[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]]]) """ def __repr__(self): return self.__class__.__name__ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
lyhyl/kornia
Hflip
false
12,742
[ "ECL-2.0", "Apache-2.0" ]
0
5bd3aeb0d54dedac01e6eaf8bac37779bab0bec5
https://github.com/lyhyl/kornia/tree/5bd3aeb0d54dedac01e6eaf8bac37779bab0bec5
ConditionTime
import torch from torch import nn def condition_time(x, i=0, size=(12, 16), seq_len=15): """create one hot encoded time image-layers, i in [1, seq_len]""" assert i < seq_len times = torch.eye(seq_len, dtype=x.dtype, device=x.device)[i].unsqueeze(-1 ).unsqueeze(-1) ones = torch.ones(1, *size, dtype=x.dtype, device=x.device) return times * ones class ConditionTime(nn.Module): """Condition Time on a stack of images, adds `horizon` channels to image""" def __init__(self, horizon, ch_dim=2, num_dims=5): super().__init__() self.horizon = horizon self.ch_dim = ch_dim self.num_dims = num_dims def forward(self, x, fstep=0): """x stack of images, fsteps""" if self.num_dims == 5: bs, seq_len, ch, h, w = x.shape ct = condition_time(x, fstep, (h, w), seq_len=self.horizon).repeat( bs, seq_len, 1, 1, 1) else: bs, h, w, ch = x.shape ct = condition_time(x, fstep, (h, w), seq_len=self.horizon).repeat( bs, 1, 1, 1) ct = ct.permute(0, 2, 3, 1) x = torch.cat([x, ct], dim=self.ch_dim) assert x.shape[self.ch_dim] == ch + self.horizon return x def get_inputs(): return [torch.rand([4, 4, 4, 4, 4])] def get_init_inputs(): return [[], {'horizon': 4}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x1 = xindex // 16 % 8 x0 = xindex % 16 x2 = xindex // 128 x3 = xindex tmp0 = x1 tmp1 = tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = -4 + x1 tmp10 = tmp1 == tmp9 tmp11 = 1.0 tmp12 = 0.0 tmp13 = tl.where(tmp10, tmp11, tmp12) tmp14 = tmp13 * tmp11 tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype) tmp16 = tl.where(tmp6, tmp14, tmp15) tmp17 = tl.where(tmp4, tmp5, tmp16) tl.store(out_ptr0 + x3, tmp17, None) 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, 8, 4, 4), (512, 128, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(2048)](arg0_1, buf0, 2048, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, def condition_time(x, i=0, size=(12, 16), seq_len=15): """create one hot encoded time image-layers, i in [1, seq_len]""" assert i < seq_len times = torch.eye(seq_len, dtype=x.dtype, device=x.device)[i].unsqueeze(-1 ).unsqueeze(-1) ones = torch.ones(1, *size, dtype=x.dtype, device=x.device) return times * ones class ConditionTimeNew(nn.Module): """Condition Time on a stack of images, adds `horizon` channels to image""" def __init__(self, horizon, ch_dim=2, num_dims=5): super().__init__() self.horizon = horizon self.ch_dim = ch_dim self.num_dims = num_dims def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
lukeleeai/metnet
ConditionTime
false
12,743
[ "MIT" ]
0
1dc0bf11780f413f3d55207866e0fa921b8aa60d
https://github.com/lukeleeai/metnet/tree/1dc0bf11780f413f3d55207866e0fa921b8aa60d
DotProductAttention
import math import torch from torch import nn def masked_softmax(X, valid_lens): """Perform softmax operation by masking elements on the last axis.""" if valid_lens is None: return nn.functional.softmax(X, dim=-1) else: shape = X.shape if valid_lens.dim() == 1: valid_lens = torch.repeat_interleave(valid_lens, shape[1]) else: valid_lens = valid_lens.reshape(-1) X = d2l.sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=- 1000000.0) return nn.functional.softmax(X.reshape(shape), dim=-1) class DotProductAttention(nn.Module): """Scaled dot product attention.""" def __init__(self, dropout, **kwargs): super(DotProductAttention, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) def forward(self, queries, keys, values, valid_lens=None): d = queries.shape[-1] scores = torch.bmm(queries, keys.transpose(1, 2)) / math.sqrt(d) self.attention_weights = masked_softmax(scores, valid_lens) return torch.bmm(self.dropout(self.attention_weights), values) def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4]) ] def get_init_inputs(): return [[], {'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 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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp3 * tmp1 tmp6 = tmp5 * tmp1 tmp7 = triton_helpers.maximum(tmp4, tmp6) tmp9 = tmp8 * tmp1 tmp10 = triton_helpers.maximum(tmp7, tmp9) tmp12 = tmp11 * tmp1 tmp13 = triton_helpers.maximum(tmp10, tmp12) tmp14 = tmp2 - tmp13 tmp15 = 0.5 tmp16 = tmp14 * tmp15 tmp17 = tl_math.exp(tmp16) tl.store(out_ptr0 + x2, tmp17, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) 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), (16, 4, 1)) assert_size_stride(arg2_1, (4, 4, 4), (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) extern_kernels.bmm(arg0_1, reinterpret_tensor(arg1_1, (4, 4, 4), ( 16, 1, 4), 0), out=buf0) del arg0_1 del arg1_1 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(64)](buf0, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1) buf2 = buf0 del buf0 triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) buf3 = buf1 del buf1 extern_kernels.bmm(buf2, arg2_1, out=buf3) del arg2_1 return buf3, buf2 def masked_softmax(X, valid_lens): """Perform softmax operation by masking elements on the last axis.""" if valid_lens is None: return nn.functional.softmax(X, dim=-1) else: shape = X.shape if valid_lens.dim() == 1: valid_lens = torch.repeat_interleave(valid_lens, shape[1]) else: valid_lens = valid_lens.reshape(-1) X = d2l.sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=- 1000000.0) return nn.functional.softmax(X.reshape(shape), dim=-1) class DotProductAttentionNew(nn.Module): """Scaled dot product attention.""" def __init__(self, dropout, **kwargs): super(DotProductAttentionNew, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) 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]
lucmertins/CapDeepLearningBook
DotProductAttention
false
12,744
[ "MIT" ]
0
e5959b552c8716e7fc65a21ae9c13c58509544c1
https://github.com/lucmertins/CapDeepLearningBook/tree/e5959b552c8716e7fc65a21ae9c13c58509544c1
PDController
import torch class PDController(torch.nn.Module): def __init__(self): super(PDController, self).__init__() def forward(self, kp, kd, position, velocity, des_position, des_velocity): return kp * (des_position - position) + kd * (des_velocity - velocity) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand( [4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_mul_sub_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask) tmp2 = tl.load(in_ptr2 + x0, xmask) tmp5 = tl.load(in_ptr3 + x0, xmask) tmp6 = tl.load(in_ptr4 + x0, xmask) tmp7 = tl.load(in_ptr5 + x0, xmask) tmp3 = tmp1 - tmp2 tmp4 = tmp0 * tmp3 tmp8 = tmp6 - tmp7 tmp9 = tmp5 * tmp8 tmp10 = tmp4 + tmp9 tl.store(out_ptr0 + x0, tmp10, xmask) def call(args): arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg4_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg5_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_sub_0[grid(256)](arg2_1, arg0_1, arg1_1, arg5_1, arg3_1, arg4_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del arg1_1 del arg2_1 del arg3_1 del arg4_1 del arg5_1 return buf0, class PDControllerNew(torch.nn.Module): def __init__(self): super(PDControllerNew, self).__init__() def forward(self, input_0, input_1, input_2, input_3, input_4, input_5): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 arg3_1 = input_3 arg4_1 = input_4 arg5_1 = input_5 output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1]) return output[0]
machines-in-motion/dg_pytorch
PDController
false
12,745
[ "BSD-3-Clause" ]
0
c8c9bd1ee50b817017a075a60762a5d9678c5c07
https://github.com/machines-in-motion/dg_pytorch/tree/c8c9bd1ee50b817017a075a60762a5d9678c5c07
ConvGRUCell
import torch from torch import nn import torch.nn.functional as F def one_param(m): """First parameter in `m`""" return next(m.parameters()) class ConvGRUCell(nn.Module): def __init__(self, input_dim, hidden_dim, kernel_size=(3, 3), bias=True, activation=F.tanh, batchnorm=False): """ Initialize ConvGRU cell. Parameters ---------- input_dim: int Number of channels of input tensor. hidden_dim: int Number of channels of hidden state. kernel_size: (int, int) Size of the convolutional kernel. bias: bool Whether or not to add the bias. """ super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.kernel_size = kernel_size if isinstance(kernel_size, (tuple, list) ) else [kernel_size] * 2 self.padding = self.kernel_size[0] // 2, self.kernel_size[1] // 2 self.bias = bias self.activation = activation self.batchnorm = batchnorm self.conv_zr = nn.Conv2d(in_channels=self.input_dim + self. hidden_dim, out_channels=2 * self.hidden_dim, kernel_size=self. kernel_size, padding=self.padding, bias=self.bias) self.conv_h1 = nn.Conv2d(in_channels=self.input_dim, out_channels= self.hidden_dim, kernel_size=self.kernel_size, padding=self. padding, bias=self.bias) self.conv_h2 = nn.Conv2d(in_channels=self.hidden_dim, out_channels= self.hidden_dim, kernel_size=self.kernel_size, padding=self. padding, bias=self.bias) self.reset_parameters() def forward(self, input, h_prev=None): if h_prev is None: h_prev = self.init_hidden(input) combined = torch.cat((input, h_prev), dim=1) combined_conv = F.sigmoid(self.conv_zr(combined)) z, r = torch.split(combined_conv, self.hidden_dim, dim=1) h_ = self.activation(self.conv_h1(input) + r * self.conv_h2(h_prev)) h_cur = (1 - z) * h_ + z * h_prev return h_cur def init_hidden(self, input): bs, _ch, h, w = input.shape return one_param(self).new_zeros(bs, self.hidden_dim, h, w) def reset_parameters(self): nn.init.xavier_uniform_(self.conv_zr.weight, gain=nn.init. calculate_gain('tanh')) self.conv_zr.bias.data.zero_() nn.init.xavier_uniform_(self.conv_h1.weight, gain=nn.init. calculate_gain('tanh')) self.conv_h1.bias.data.zero_() nn.init.xavier_uniform_(self.conv_h2.weight, gain=nn.init. calculate_gain('tanh')) self.conv_h2.bias.data.zero_() if self.batchnorm: self.bn1.reset_parameters() self.bn2.reset_parameters() def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'input_dim': 4, 'hidden_dim': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice from torch import nn 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_new_zeros_0(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 = 0.0 tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 16 % 8 x0 = xindex % 16 x2 = xindex // 128 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = 0.0 tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp6, tmp9, tmp10) tmp12 = tl.where(tmp4, tmp5, tmp11) tl.store(out_ptr0 + x3, tmp12, xmask) @triton.jit def triton_poi_fused_convolution_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 8 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(in_out_ptr0 + x3, tmp3, xmask) @triton.jit def triton_poi_fused_add_convolution_mul_rsub_tanh_3(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, 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 x1 = xindex // 16 % 4 x2 = xindex // 64 x3 = xindex % 64 tmp0 = tl.load(in_out_ptr0 + x4, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_out_ptr1 + x4, xmask) tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr2 + (x3 + 128 * x2), xmask) tmp9 = tl.load(in_ptr2 + (64 + x3 + 128 * x2), xmask) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp7 = 1.0 tmp8 = tmp7 - tmp6 tmp10 = tmp9 * tmp5 tmp11 = tmp2 + tmp10 tmp12 = libdevice.tanh(tmp11) tmp13 = tmp8 * tmp12 tmp14 = 0.0 tmp15 = tmp6 * tmp14 tmp16 = tmp13 + tmp15 tl.store(in_out_ptr0 + x4, tmp2, xmask) tl.store(in_out_ptr1 + x4, tmp5, xmask) tl.store(out_ptr0 + x4, tmp8, xmask) tl.store(out_ptr1 + x4, tmp16, 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, (8, 8, 3, 3), (72, 9, 3, 1)) assert_size_stride(primals_3, (8,), (1,)) assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_7, (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_new_zeros_0[grid(256)](buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) buf1 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32) triton_poi_fused_cat_1[grid(512)](primals_1, buf1, 512, XBLOCK=128, num_warps=4, num_stages=1) buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 8, 4, 4), (128, 16, 4, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_sigmoid_2[grid(512)](buf3, primals_3, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_3 buf4 = extern_kernels.convolution(primals_1, primals_4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1)) buf6 = extern_kernels.convolution(buf0, primals_6, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1)) buf5 = buf4 del buf4 buf7 = buf6 del buf6 buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_convolution_mul_rsub_tanh_3[grid(256)](buf5, buf7, primals_5, primals_7, buf3, buf8, buf9, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 del primals_7 return (buf9, primals_1, primals_2, primals_4, primals_6, buf0, buf1, buf3, reinterpret_tensor(buf3, (4, 4, 4, 4), (128, 16, 4, 1), 64), buf5, buf7, buf8) def one_param(m): """First parameter in `m`""" return next(m.parameters()) class ConvGRUCellNew(nn.Module): def __init__(self, input_dim, hidden_dim, kernel_size=(3, 3), bias=True, activation=F.tanh, batchnorm=False): """ Initialize ConvGRU cell. Parameters ---------- input_dim: int Number of channels of input tensor. hidden_dim: int Number of channels of hidden state. kernel_size: (int, int) Size of the convolutional kernel. bias: bool Whether or not to add the bias. """ super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.kernel_size = kernel_size if isinstance(kernel_size, (tuple, list) ) else [kernel_size] * 2 self.padding = self.kernel_size[0] // 2, self.kernel_size[1] // 2 self.bias = bias self.activation = activation self.batchnorm = batchnorm self.conv_zr = nn.Conv2d(in_channels=self.input_dim + self. hidden_dim, out_channels=2 * self.hidden_dim, kernel_size=self. kernel_size, padding=self.padding, bias=self.bias) self.conv_h1 = nn.Conv2d(in_channels=self.input_dim, out_channels= self.hidden_dim, kernel_size=self.kernel_size, padding=self. padding, bias=self.bias) self.conv_h2 = nn.Conv2d(in_channels=self.hidden_dim, out_channels= self.hidden_dim, kernel_size=self.kernel_size, padding=self. padding, bias=self.bias) self.reset_parameters() def init_hidden(self, input): bs, _ch, h, w = input.shape return one_param(self).new_zeros(bs, self.hidden_dim, h, w) def reset_parameters(self): nn.init.xavier_uniform_(self.conv_zr.weight, gain=nn.init. calculate_gain('tanh')) self.conv_zr.bias.data.zero_() nn.init.xavier_uniform_(self.conv_h1.weight, gain=nn.init. calculate_gain('tanh')) self.conv_h1.bias.data.zero_() nn.init.xavier_uniform_(self.conv_h2.weight, gain=nn.init. calculate_gain('tanh')) self.conv_h2.bias.data.zero_() if self.batchnorm: self.bn1.reset_parameters() self.bn2.reset_parameters() def forward(self, input_0): primals_2 = self.conv_zr.weight primals_3 = self.conv_zr.bias primals_4 = self.conv_h1.weight primals_5 = self.conv_h1.bias primals_6 = self.conv_h2.weight primals_7 = self.conv_h2.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
lukeleeai/metnet
ConvGRUCell
false
12,746
[ "MIT" ]
0
1dc0bf11780f413f3d55207866e0fa921b8aa60d
https://github.com/lukeleeai/metnet/tree/1dc0bf11780f413f3d55207866e0fa921b8aa60d
AttentionPool2d
import math import torch import numpy as np import torch.nn import torch as th import torch.nn as nn def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) matmul_ops = 2 * b * num_spatial ** 2 * c model.total_ops += th.DoubleTensor([matmul_ops]) def conv_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D convolution module. """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f'unsupported dimensions: {dims}') class QKVAttention(nn.Module): """ A module which performs QKV attention and splits in a different order. """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.chunk(3, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum('bct,bcs->bts', (q * scale).view(bs * self. n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch, length)) weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum('bts,bcs->bct', weight, v.reshape(bs * self.n_heads, ch, length)) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__(self, spacial_dim: 'int', embed_dim: 'int', num_heads_channels: 'int', output_dim: 'int'=None): super().__init__() self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, x): b, c, *_spatial = x.shape x = x.reshape(b, c, -1) x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) x = x + self.positional_embedding[None, :, :] x = self.qkv_proj(x) x = self.attention(x) x = self.c_proj(x) return x[:, :, 0] def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'spacial_dim': 4, 'embed_dim': 4, 'num_heads_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 math as tl_math import math import numpy as np import torch.nn import torch as th 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_ptr0, 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 tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tl.store(out_ptr0 + x0, tmp4, xmask) @triton.jit def triton_poi_fused_add_cat_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 272 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 17 x3 = xindex // 17 x4 = xindex % 68 x5 = xindex tmp15 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + x3, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = 16.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], 17, tl.int64) tmp13 = tl.load(in_ptr1 + (16 * x3 + (-1 + x0)), tmp10 & xmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.where(tmp4, tmp9, tmp13) tmp16 = tmp14 + tmp15 tl.store(out_ptr0 + x5, tmp16, xmask) @triton.jit def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 272 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex // 68 x3 = xindex % 68 x1 = xindex // 17 % 4 x4 = xindex tmp0 = tl.load(in_ptr0 + (x3 + 204 * x2), xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.7071067811865475 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x4, tmp4, xmask) @triton.jit def triton_poi_fused_mul_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 272 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex // 68 x3 = xindex % 68 x1 = xindex // 17 % 4 x4 = xindex tmp0 = tl.load(in_ptr0 + (68 + x3 + 204 * x2), xmask) tmp1 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.7071067811865475 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x4, tmp4, xmask) @triton.jit def triton_per_fused__softmax_4(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 68 rnumel = 17 RBLOCK: tl.constexpr = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] rmask = rindex < rnumel r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 17 * x0), rmask & xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(rmask & 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(rmask & xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tmp11 = tmp6 / tmp10 tl.store(out_ptr2 + (r1 + 17 * x0), tmp11, rmask & xmask) @triton.jit def triton_poi_fused_convolution_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 816 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 17 % 12 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_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 17 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 + 68 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 17 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_convolution_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 272 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 17 % 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 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 17), (17, 1)) assert_size_stride(primals_3, (12, 4, 1), (4, 1, 1)) assert_size_stride(primals_4, (12,), (1,)) assert_size_stride(primals_5, (4, 4, 1), (4, 1, 1)) assert_size_stride(primals_6, (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_per_fused_mean_0[grid(16)](primals_1, buf0, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) buf1 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32) triton_poi_fused_add_cat_1[grid(272)](buf0, primals_1, primals_2, buf1, 272, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del primals_1 del primals_2 buf2 = extern_kernels.convolution(buf1, primals_3, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf2, (4, 12, 17), (204, 17, 1)) buf3 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32) triton_poi_fused_mul_2[grid(272)](buf2, primals_4, buf3, 272, XBLOCK=256, num_warps=4, num_stages=1) buf4 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32) triton_poi_fused_mul_3[grid(272)](buf2, primals_4, buf4, 272, XBLOCK=128, num_warps=4, num_stages=1) buf5 = empty_strided_cuda((4, 17, 17), (289, 17, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf3, (4, 17, 4), (68, 1, 17), 0), buf4, out=buf5) buf8 = empty_strided_cuda((4, 17, 17), (289, 17, 1), torch.float32) triton_per_fused__softmax_4[grid(68)](buf5, buf8, 68, 17, XBLOCK=1, num_warps=2, num_stages=1) del buf5 buf9 = buf2 del buf2 triton_poi_fused_convolution_5[grid(816)](buf9, primals_4, 816, XBLOCK=128, num_warps=4, num_stages=1) del primals_4 buf10 = empty_strided_cuda((4, 17, 4), (68, 4, 1), torch.float32) extern_kernels.bmm(buf8, reinterpret_tensor(buf9, (4, 17, 4), (204, 1, 17), 136), out=buf10) buf11 = empty_strided_cuda((4, 4, 17), (68, 17, 1), torch.float32) triton_poi_fused_convolution_6[grid(16, 17)](buf10, buf11, 16, 17, XBLOCK=32, YBLOCK=16, num_warps=4, num_stages=1) buf12 = extern_kernels.convolution(buf11, primals_5, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf12, (4, 4, 17), (68, 17, 1)) del buf11 buf13 = buf12 del buf12 triton_poi_fused_convolution_7[grid(272)](buf13, primals_6, 272, XBLOCK=256, num_warps=4, num_stages=1) del primals_6 return reinterpret_tensor(buf13, (4, 4), (68, 17), 0 ), primals_3, primals_5, buf1, buf8, reinterpret_tensor(buf10, (4, 4, 17), (68, 1, 4), 0), reinterpret_tensor(buf9, (4, 4, 17), (204, 17, 1), 136), buf3, reinterpret_tensor(buf4, (4, 17, 4), (68, 1, 17), 0 ) def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) matmul_ops = 2 * b * num_spatial ** 2 * c model.total_ops += th.DoubleTensor([matmul_ops]) def conv_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D convolution module. """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f'unsupported dimensions: {dims}') class QKVAttention(nn.Module): """ A module which performs QKV attention and splits in a different order. """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.chunk(3, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum('bct,bcs->bts', (q * scale).view(bs * self. n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch, length)) weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum('bts,bcs->bct', weight, v.reshape(bs * self.n_heads, ch, length)) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class AttentionPool2dNew(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__(self, spacial_dim: 'int', embed_dim: 'int', num_heads_channels: 'int', output_dim: 'int'=None): super().__init__() self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, input_0): primals_2 = self.positional_embedding primals_3 = self.qkv_proj.weight primals_4 = self.qkv_proj.bias primals_5 = self.c_proj.weight primals_6 = self.c_proj.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
lukaszbinden/Diffusion-based-Segmentation
AttentionPool2d
false
12,747
[ "Apache-2.0" ]
0
43a475e53320adac82838f87ff7fd71f78d8d004
https://github.com/lukaszbinden/Diffusion-based-Segmentation/tree/43a475e53320adac82838f87ff7fd71f78d8d004
DiscrepancyLossWithLogits
import torch import torch.utils.data import torch from torchvision.transforms import functional as F from torch import nn from torch.nn import functional as F class AbstractConsistencyLoss(nn.Module): def __init__(self, reduction='mean'): super().__init__() self.reduction = reduction def forward(self, logits1, logits2): raise NotImplementedError class LossWithLogits(AbstractConsistencyLoss): def __init__(self, reduction='mean', loss_cls=nn.L1Loss): super().__init__(reduction) self.loss_with_softmax = loss_cls(reduction=reduction) def forward(self, logits1, logits2): loss = self.loss_with_softmax(F.softmax(logits1, dim=1), F.softmax( logits2, dim=1)) return loss class DiscrepancyLossWithLogits(AbstractConsistencyLoss): def __init__(self, reduction='mean'): super().__init__(reduction=reduction) self.loss = LossWithLogits(reduction=reduction, loss_cls=nn.L1Loss) def forward(self, logits1, logits2): return self.loss(logits1, logits2) 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 from torchvision.transforms import functional as F from torch import nn from torch.nn import functional as F assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel 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_per_fused__softmax_abs_mean_sub_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) 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' ) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr1 + r3, None) tmp10 = tl.load(in_ptr1 + (r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp11 = tl.load(in_ptr1 + (16 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp13 = tl.load(in_ptr1 + (32 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp15 = tl.load(in_ptr1 + (48 + r0 + 64 * r2), None, eviction_policy= 'evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tmp12 = tmp10 + tmp11 tmp14 = tmp12 + tmp13 tmp16 = tmp14 + tmp15 tmp17 = tmp9 / tmp16 tmp18 = tmp8 - tmp17 tmp19 = tl_math.abs(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((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK= 256, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_0[grid(256)](arg1_1, buf1, 256, XBLOCK= 256, num_warps=4, num_stages=1) del arg1_1 buf3 = empty_strided_cuda((), (), torch.float32) buf4 = buf3 del buf3 triton_per_fused__softmax_abs_mean_sub_1[grid(1)](buf4, buf0, buf1, 1, 256, num_warps=2, num_stages=1) del buf0 del buf1 return buf4, class AbstractConsistencyLoss(nn.Module): def __init__(self, reduction='mean'): super().__init__() self.reduction = reduction def forward(self, logits1, logits2): raise NotImplementedError class LossWithLogits(AbstractConsistencyLoss): def __init__(self, reduction='mean', loss_cls=nn.L1Loss): super().__init__(reduction) self.loss_with_softmax = loss_cls(reduction=reduction) def forward(self, logits1, logits2): loss = self.loss_with_softmax(F.softmax(logits1, dim=1), F.softmax( logits2, dim=1)) return loss class DiscrepancyLossWithLogitsNew(AbstractConsistencyLoss): def __init__(self, reduction='mean'): super().__init__(reduction=reduction) self.loss = LossWithLogits(reduction=reduction, loss_cls=nn.L1Loss) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
lizhenbang56/END-TO-END-TEMPORAL-FEATURE-AGGREGATION-FOR-SIAMESE-TRACKERS
DiscrepancyLossWithLogits
false
12,748
[ "MIT" ]
0
132b2e28b7f66c6ba0719774e9abd9b6515dd7e2
https://github.com/lizhenbang56/END-TO-END-TEMPORAL-FEATURE-AGGREGATION-FOR-SIAMESE-TRACKERS/tree/132b2e28b7f66c6ba0719774e9abd9b6515dd7e2
D2Remap
import torch class D2Remap(torch.nn.Module): def __init__(self): super(D2Remap, self).__init__() self.l1 = torch.nn.Conv2d(4, 16, kernel_size=3, padding=1) self.l2 = torch.nn.Conv2d(16, 3, kernel_size=3, padding=1) def forward(self, x, depth): stack = torch.cat((x, depth.unsqueeze(1)), dim=1) return self.l2(self.l1(stack)) def get_inputs(): return [torch.rand([4, 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 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 = 80 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 5 x0 = xindex % 4 x2 = xindex // 20 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 5, tl.int64) tmp9 = tl.load(in_ptr1 + (x0 + 4 * x2), 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_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 320 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 20 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) @triton.jit def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 60 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 20 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, primals_4, primals_5, primals_6 = 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, (16, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_4, (16,), (1,)) assert_size_stride(primals_5, (3, 16, 3, 3), (144, 9, 3, 1)) assert_size_stride(primals_6, (3,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 5, 4), (20, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(80)](primals_2, primals_1, buf0, 80, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 del primals_2 buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (1, 4, 5, 4), (0, 20, 4, 1), 0), primals_3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (1, 16, 5, 4), (320, 20, 4, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_1[grid(320)](buf2, primals_4, 320, XBLOCK=256, num_warps=4, num_stages=1) del primals_4 buf3 = extern_kernels.convolution(reinterpret_tensor(buf2, (1, 16, 5, 4), (0, 20, 4, 1), 0), 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, (1, 3, 5, 4), (60, 20, 4, 1)) buf4 = buf3 del buf3 triton_poi_fused_convolution_2[grid(60)](buf4, primals_6, 60, XBLOCK=64, num_warps=1, num_stages=1) del primals_6 return reinterpret_tensor(buf4, (3, 5, 4), (20, 4, 1), 0 ), primals_3, primals_5, reinterpret_tensor(buf0, (1, 4, 5, 4), (80, 20, 4, 1), 0), buf2 class D2RemapNew(torch.nn.Module): def __init__(self): super(D2RemapNew, self).__init__() self.l1 = torch.nn.Conv2d(4, 16, kernel_size=3, padding=1) self.l2 = torch.nn.Conv2d(16, 3, kernel_size=3, padding=1) def forward(self, input_0, input_1): primals_3 = self.l1.weight primals_4 = self.l1.bias primals_5 = self.l2.weight primals_6 = self.l2.bias primals_2 = input_0 primals_1 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
m4nh/pytorch-retinanet
D2Remap
false
12,749
[ "Apache-2.0" ]
0
2da8db70b754f773aa7c500133cd690c0b4b1839
https://github.com/m4nh/pytorch-retinanet/tree/2da8db70b754f773aa7c500133cd690c0b4b1839
StdConv2d
import torch from torch import nn import torch.nn.functional as F class StdConv2d(nn.Conv2d): def forward(self, x): w = self.weight v, m = torch.var_mean(w, dim=[1, 2, 3], keepdim=True, unbiased=False) w = (w - m) / torch.sqrt(v + 1e-10) return F.conv2d(x, w, self.bias, self.stride, self.padding, self. dilation, self.groups) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime.triton_helpers import libdevice from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_per_fused_add_div_sqrt_sub_var_mean_0(in_out_ptr0, in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 4 RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r1 = rindex x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tl.where(xmask, tmp1, 0) tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp6 = tl.where(xmask, tmp4, 0) tmp7 = tl.sum(tmp6, 1)[:, None] tmp8 = tl.full([XBLOCK, 1], 64, tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 / tmp9 tmp11 = tmp1 - tmp10 tmp12 = tmp11 * tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.where(xmask, tmp13, 0) tmp16 = tl.sum(tmp15, 1)[:, None] tmp17 = 64.0 tmp18 = tmp16 / tmp17 tmp19 = 1e-10 tmp20 = tmp18 + tmp19 tmp21 = libdevice.sqrt(tmp20) tmp22 = tmp0 - tmp10 tmp23 = tmp22 / tmp21 tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp21, xmask) tl.store(out_ptr1 + (r1 + 64 * x0), tmp23, xmask) @triton.jit def triton_poi_fused_convolution_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 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, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf1 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32) buf3 = reinterpret_tensor(buf1, (4, 1, 1, 1), (1, 1, 1, 1), 0) del buf1 buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_div_sqrt_sub_var_mean_0[grid(4)](buf3, primals_1, buf4, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) buf5 = extern_kernels.convolution(primals_3, buf4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 4, 1, 1), (4, 1, 1, 1)) buf6 = buf5 del buf5 triton_poi_fused_convolution_1[grid(16)](buf6, primals_2, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_2 return buf6, primals_1, primals_3, buf3, buf4 class StdConv2dNew(nn.Conv2d): def forward(self, input_0): primals_1 = self.weight primals_2 = self.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
marekb-sci/kaggle_cassava
StdConv2d
false
12,750
[ "Apache-2.0" ]
0
158d1e398e713381c889e071329b96b9c0ba98d2
https://github.com/marekb-sci/kaggle_cassava/tree/158d1e398e713381c889e071329b96b9c0ba98d2
HamidaEtAl
import torch import torch.utils import torch.utils.data import torch.nn as nn import torch.nn.functional as F from torch.nn import init class HamidaEtAl(nn.Module): """ 3-D Deep Learning Approach for Remote Sensing Image Classification Amina Ben Hamida, Alexandre Benoit, Patrick Lambert, Chokri Ben Amar IEEE TGRS, 2018 https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8344565 """ @staticmethod def weight_init(m): if isinstance(m, nn.Linear) or isinstance(m, nn.Conv3d): init.kaiming_normal_(m.weight) init.zeros_(m.bias) def __init__(self, input_channels, n_classes, patch_size=5, dilation=1): super(HamidaEtAl, self).__init__() self.patch_size = patch_size self.input_channels = input_channels dilation = dilation, 1, 1 if patch_size == 3: self.conv1 = nn.Conv3d(1, 20, (3, 3, 3), stride=(1, 1, 1), dilation=dilation, padding=(1, 0, 0)) else: self.conv1 = nn.Conv3d(1, 20, (3, 3, 3), stride=(1, 1, 1), dilation=dilation, padding=(1, 0, 0)) self.pool1 = nn.Conv3d(20, 2, (3, 1, 1), dilation=dilation, stride= (2, 1, 1), padding=(1, 0, 0)) self.conv2 = nn.Conv3d(2, 35, (3, 3, 3), dilation=dilation, stride= (1, 1, 1), padding=(1, 0, 0)) self.pool2 = nn.Conv3d(35, 2, (2, 1, 1), dilation=dilation, stride= (2, 1, 1), padding=(1, 0, 0)) self.conv3 = nn.Conv3d(2, 35, (3, 1, 1), dilation=dilation, stride= (1, 1, 1), padding=(1, 0, 0)) self.pool3 = nn.Conv3d(35, 2, (1, 1, 1), dilation=dilation, stride= (2, 1, 1), padding=(1, 0, 0)) self.conv4 = nn.Conv3d(2, 35, (3, 1, 1), dilation=dilation, stride= (1, 1, 1), padding=(1, 0, 0)) self.pool4 = nn.Conv3d(35, 4, (1, 1, 1), dilation=dilation, stride= (2, 2, 2), padding=(0, 0, 0)) self.dropout = nn.Dropout(p=0.5) self.features_size = self._get_final_flattened_size() self.fc = nn.Linear(self.features_size, n_classes) self.apply(self.weight_init) def _get_final_flattened_size(self): with torch.no_grad(): x = torch.zeros((1, 1, self.input_channels, self.patch_size, self.patch_size)) x = self.pool1(self.conv1(x)) x = self.pool2(self.conv2(x)) x = self.pool3(self.conv3(x)) x = self.pool4(self.conv4(x)) _, t, c, w, h = x.size() return t * c * w * h def forward(self, x): x = F.relu(self.conv1(x)) x = self.pool1(x) x = F.relu(self.conv2(x)) x = self.pool2(x) x = F.relu(self.conv3(x)) x = self.pool3(x) x = F.relu(self.conv4(x)) x = self.pool4(x) x = x.view(-1, self.features_size) x = self.dropout(x) x = self.fc(x) return x def get_inputs(): return [torch.rand([4, 1, 64, 64, 64])] def get_init_inputs(): return [[], {'input_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.utils import torch.utils.data import torch.nn as nn from torch.nn import 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_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 // 246016 % 20 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_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 984064 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 123008 % 2 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_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 115200 % 35 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_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 489600 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 61200 % 2 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_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 8568000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 61200 % 35 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_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 288000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 36000 % 2 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_relu_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 5040000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 36000 % 35 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_7(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 72000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4500 % 4 x0 = xindex % 4500 x4 = xindex // 4500 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(out_ptr0 + (x0 + 4512 * x4), tmp2, xmask) @triton.jit def triton_poi_fused_convolution_view_8(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 72000 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + (4512 * (x0 // 4500) + x0 % 4500), xmask) tl.store(out_ptr0 + x0, tmp0, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17, primals_18, primals_19) = args args.clear() assert_size_stride(primals_1, (20, 1, 3, 3, 3), (27, 27, 9, 3, 1)) assert_size_stride(primals_2, (20,), (1,)) assert_size_stride(primals_3, (4, 1, 64, 64, 64), (262144, 262144, 4096, 64, 1)) assert_size_stride(primals_4, (2, 20, 3, 1, 1), (60, 3, 1, 1, 1)) assert_size_stride(primals_5, (2,), (1,)) assert_size_stride(primals_6, (35, 2, 3, 3, 3), (54, 27, 9, 3, 1)) assert_size_stride(primals_7, (35,), (1,)) assert_size_stride(primals_8, (2, 35, 2, 1, 1), (70, 2, 1, 1, 1)) assert_size_stride(primals_9, (2,), (1,)) assert_size_stride(primals_10, (35, 2, 3, 1, 1), (6, 3, 1, 1, 1)) assert_size_stride(primals_11, (35,), (1,)) assert_size_stride(primals_12, (2, 35, 1, 1, 1), (35, 1, 1, 1, 1)) assert_size_stride(primals_13, (2,), (1,)) assert_size_stride(primals_14, (35, 2, 3, 1, 1), (6, 3, 1, 1, 1)) assert_size_stride(primals_15, (35,), (1,)) assert_size_stride(primals_16, (4, 35, 1, 1, 1), (35, 1, 1, 1, 1)) assert_size_stride(primals_17, (4,), (1,)) assert_size_stride(primals_18, (4, 4), (4, 1)) assert_size_stride(primals_19, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1, 1), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 20, 64, 62, 62), (4920320, 246016, 3844, 62, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(19681280)](buf1, primals_2, 19681280, XBLOCK=512, num_warps=8, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2, 1, 1), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 2, 32, 62, 62), (246016, 123008, 3844, 62, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_1[grid(984064)](buf3, primals_5, 984064, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1, 1), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 35, 32, 60, 60), (4032000, 115200, 3600, 60, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_2[grid(16128000)](buf5, primals_7, 16128000, XBLOCK=512, num_warps=8, num_stages=1) del primals_7 buf6 = extern_kernels.convolution(buf5, primals_8, stride=(2, 1, 1), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 2, 17, 60, 60), (122400, 61200, 3600, 60, 1)) buf7 = buf6 del buf6 triton_poi_fused_convolution_3[grid(489600)](buf7, primals_9, 489600, XBLOCK=1024, num_warps=4, num_stages=1) del primals_9 buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1, 1 ), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 35, 17, 60, 60), (2142000, 61200, 3600, 60, 1)) buf9 = buf8 del buf8 triton_poi_fused_convolution_relu_4[grid(8568000)](buf9, primals_11, 8568000, XBLOCK=1024, num_warps=4, num_stages=1) del primals_11 buf10 = extern_kernels.convolution(buf9, primals_12, stride=(2, 1, 1), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 2, 10, 60, 60), (72000, 36000, 3600, 60, 1)) buf11 = buf10 del buf10 triton_poi_fused_convolution_5[grid(288000)](buf11, primals_13, 288000, XBLOCK=1024, num_warps=4, num_stages=1) del primals_13 buf12 = extern_kernels.convolution(buf11, primals_14, stride=(1, 1, 1), padding=(1, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 35, 10, 60, 60), (1260000, 36000, 3600, 60, 1)) buf13 = buf12 del buf12 triton_poi_fused_convolution_relu_6[grid(5040000)](buf13, primals_15, 5040000, XBLOCK=512, num_warps=8, num_stages=1) del primals_15 buf14 = extern_kernels.convolution(buf13, primals_16, stride=(2, 2, 2), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False, output_padding=(0, 0, 0), groups=1, bias=None) assert_size_stride(buf14, (4, 4, 5, 30, 30), (18000, 4500, 900, 30, 1)) buf15 = empty_strided_cuda((4, 4, 5, 30, 30), (18048, 4512, 900, 30, 1), torch.float32) triton_poi_fused_convolution_7[grid(72000)](buf14, primals_17, buf15, 72000, XBLOCK=1024, num_warps=4, num_stages=1) del primals_17 buf16 = reinterpret_tensor(buf14, (18000, 4), (4, 1), 0) del buf14 triton_poi_fused_convolution_view_8[grid(72000)](buf15, buf16, 72000, XBLOCK=1024, num_warps=4, num_stages=1) del buf15 buf17 = empty_strided_cuda((18000, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_19, buf16, reinterpret_tensor( primals_18, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf17) del primals_19 return (buf17, primals_1, primals_3, primals_4, primals_6, primals_8, primals_10, primals_12, primals_14, primals_16, buf1, buf3, buf5, buf7, buf9, buf11, buf13, buf16, primals_18) class HamidaEtAlNew(nn.Module): """ 3-D Deep Learning Approach for Remote Sensing Image Classification Amina Ben Hamida, Alexandre Benoit, Patrick Lambert, Chokri Ben Amar IEEE TGRS, 2018 https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8344565 """ @staticmethod def weight_init(m): if isinstance(m, nn.Linear) or isinstance(m, nn.Conv3d): init.kaiming_normal_(m.weight) init.zeros_(m.bias) def __init__(self, input_channels, n_classes, patch_size=5, dilation=1): super(HamidaEtAlNew, self).__init__() self.patch_size = patch_size self.input_channels = input_channels dilation = dilation, 1, 1 if patch_size == 3: self.conv1 = nn.Conv3d(1, 20, (3, 3, 3), stride=(1, 1, 1), dilation=dilation, padding=(1, 0, 0)) else: self.conv1 = nn.Conv3d(1, 20, (3, 3, 3), stride=(1, 1, 1), dilation=dilation, padding=(1, 0, 0)) self.pool1 = nn.Conv3d(20, 2, (3, 1, 1), dilation=dilation, stride= (2, 1, 1), padding=(1, 0, 0)) self.conv2 = nn.Conv3d(2, 35, (3, 3, 3), dilation=dilation, stride= (1, 1, 1), padding=(1, 0, 0)) self.pool2 = nn.Conv3d(35, 2, (2, 1, 1), dilation=dilation, stride= (2, 1, 1), padding=(1, 0, 0)) self.conv3 = nn.Conv3d(2, 35, (3, 1, 1), dilation=dilation, stride= (1, 1, 1), padding=(1, 0, 0)) self.pool3 = nn.Conv3d(35, 2, (1, 1, 1), dilation=dilation, stride= (2, 1, 1), padding=(1, 0, 0)) self.conv4 = nn.Conv3d(2, 35, (3, 1, 1), dilation=dilation, stride= (1, 1, 1), padding=(1, 0, 0)) self.pool4 = nn.Conv3d(35, 4, (1, 1, 1), dilation=dilation, stride= (2, 2, 2), padding=(0, 0, 0)) self.dropout = nn.Dropout(p=0.5) self.features_size = self._get_final_flattened_size() self.fc = nn.Linear(self.features_size, n_classes) self.apply(self.weight_init) def _get_final_flattened_size(self): with torch.no_grad(): x = torch.zeros((1, 1, self.input_channels, self.patch_size, self.patch_size)) x = self.pool1(self.conv1(x)) x = self.pool2(self.conv2(x)) x = self.pool3(self.conv3(x)) x = self.pool4(self.conv4(x)) _, t, c, w, h = x.size() return t * c * w * h def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_4 = self.pool1.weight primals_5 = self.pool1.bias primals_6 = self.conv2.weight primals_7 = self.conv2.bias primals_8 = self.pool2.weight primals_9 = self.pool2.bias primals_10 = self.conv3.weight primals_11 = self.conv3.bias primals_12 = self.pool3.weight primals_13 = self.pool3.bias primals_14 = self.conv4.weight primals_15 = self.conv4.bias primals_16 = self.pool4.weight primals_17 = self.pool4.bias primals_18 = self.fc.weight primals_19 = self.fc.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]) return output[0]
giorgosouz/HSI-classification-using-state-of-the-art-models
HamidaEtAl
false
12,751
[ "MIT" ]
0
a925972ffe02c2cd1e5dde2b163e1faa854a4966
https://github.com/giorgosouz/HSI-classification-using-state-of-the-art-models/tree/a925972ffe02c2cd1e5dde2b163e1faa854a4966
CRF_S
import torch import torch.nn as nn import torch.nn.init class CRF_S(nn.Module): """Conditional Random Field (CRF) layer. This version is used in Lample et al. 2016, has less parameters than CRF_L. args: hidden_dim: input dim size tagset_size: target_set_size if_biase: whether allow bias in linear trans """ def __init__(self, hidden_dim, tagset_size, if_bias=True): super(CRF_S, self).__init__() self.tagset_size = tagset_size self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size, bias=if_bias) self.transitions = nn.Parameter(torch.Tensor(self.tagset_size, self .tagset_size)) def rand_init(self): """random initialization """ utils.init_linear(self.hidden2tag) self.transitions.data.zero_() def forward(self, feats): """ args: feats (batch_size, seq_len, hidden_dim) : input score from previous layers return: output from crf layer ( (batch_size * seq_len), tag_size, tag_size) """ scores = self.hidden2tag(feats).view(-1, self.tagset_size, 1) ins_num = scores.size(0) crf_scores = scores.expand(ins_num, self.tagset_size, self.tagset_size ) + self.transitions.view(1, self.tagset_size, self.tagset_size ).expand(ins_num, self.tagset_size, self.tagset_size) return crf_scores def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'hidden_dim': 4, 'tagset_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 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_0(in_ptr0, in_ptr1, in_ptr2, 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 // 4 x1 = xindex // 4 % 4 x4 = xindex % 16 x5 = xindex tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tl.store(out_ptr0 + x5, 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,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (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_3, (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), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_0[grid(1024)](buf0, primals_2, primals_4, buf1, 1024, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del primals_2 del primals_4 return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0) class CRF_SNew(nn.Module): """Conditional Random Field (CRF) layer. This version is used in Lample et al. 2016, has less parameters than CRF_L. args: hidden_dim: input dim size tagset_size: target_set_size if_biase: whether allow bias in linear trans """ def __init__(self, hidden_dim, tagset_size, if_bias=True): super(CRF_SNew, self).__init__() self.tagset_size = tagset_size self.hidden2tag = nn.Linear(hidden_dim, self.tagset_size, bias=if_bias) self.transitions = nn.Parameter(torch.Tensor(self.tagset_size, self .tagset_size)) def rand_init(self): """random initialization """ utils.init_linear(self.hidden2tag) self.transitions.data.zero_() def forward(self, input_0): primals_1 = self.transitions primals_4 = self.hidden2tag.weight primals_2 = self.hidden2tag.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
markWJJ/LM-LSTM-CRF
CRF_S
false
12,752
[ "Apache-2.0" ]
0
e468974ce2193a5579417f9e253eb6c997932636
https://github.com/markWJJ/LM-LSTM-CRF/tree/e468974ce2193a5579417f9e253eb6c997932636
Policy
import torch import numpy as np from torch import Tensor import torch.nn.functional as F from torch import nn from torch.nn import Linear from torch.autograd import Variable from torch.distributions import Categorical class Policy(nn.Module): def __init__(self, in_sz, hidden_sz, out_sz): super(Policy, self).__init__() self.fc1 = Linear(in_sz, hidden_sz) self.fc2 = Linear(hidden_sz, out_sz) self.log_probs = list() self.rewards = list() def forward(self, inputs): x = self.fc1(inputs) x = F.relu(x) logits = self.fc2(x) return F.softmax(logits, dim=0) def act(self, inputs): if torch.cuda.is_available(): inputs = Variable(Tensor(inputs)) else: inputs = Variable(Tensor(inputs)) probs = self(inputs) m = Categorical(probs) action = m.sample() self.log_probs.append(m.log_prob(action)) return action.data[0] def learn(self, optimizer): self.weight_reward() losses = [] for log_prob, reward in zip(self.log_probs, self.rewards): losses.append(-log_prob * reward) optimizer.zero_grad() losses = torch.cat(losses).sum() losses.backward() optimizer.step() self.rewards = list() self.log_probs = list() def weight_reward(self): R = 0 rewards = [] for r in self.rewards[::-1]: R = r + 0.99 * R rewards.insert(0, R) rewards = Tensor(rewards) self.rewards = (rewards - rewards.mean()) / (rewards.std() + np. finfo(np.float32).eps) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_sz': 4, 'hidden_sz': 4, 'out_sz': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import numpy as np from torch import Tensor from torch import nn from torch.nn import Linear from torch.autograd import Variable from torch.distributions import Categorical assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_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 x0 = xindex % 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) 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 buf5 = 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, buf5, 256, 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, 4), ( 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del primals_5 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=128, num_warps=4, num_stages=1) buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf3 return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), buf4, primals_4, buf5 class PolicyNew(nn.Module): def __init__(self, in_sz, hidden_sz, out_sz): super(PolicyNew, self).__init__() self.fc1 = Linear(in_sz, hidden_sz) self.fc2 = Linear(hidden_sz, out_sz) self.log_probs = list() self.rewards = list() def act(self, inputs): if torch.cuda.is_available(): inputs = Variable(Tensor(inputs)) else: inputs = Variable(Tensor(inputs)) probs = self(inputs) m = Categorical(probs) action = m.sample() self.log_probs.append(m.log_prob(action)) return action.data[0] def learn(self, optimizer): self.weight_reward() losses = [] for log_prob, reward in zip(self.log_probs, self.rewards): losses.append(-log_prob * reward) optimizer.zero_grad() losses = torch.cat(losses).sum() losses.backward() optimizer.step() self.rewards = list() self.log_probs = list() def weight_reward(self): R = 0 rewards = [] for r in self.rewards[::-1]: R = r + 0.99 * R rewards.insert(0, R) rewards = Tensor(rewards) self.rewards = (rewards - rewards.mean()) / (rewards.std() + np. finfo(np.float32).eps) def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
mabirck/CS294-DeepRL
Policy
false
12,753
[ "MIT" ]
0
0445808fa62ae8a22b13c598c998e3aea7632e79
https://github.com/mabirck/CS294-DeepRL/tree/0445808fa62ae8a22b13c598c998e3aea7632e79
Critic
import torch import numpy as np import torch.nn.functional as F import torch.nn as nn def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1.0 / np.sqrt(fan_in) return -lim, lim class Critic(nn.Module): """Critic (Value) Model.""" def __init__(self, state_size, action_size, seed, fcs1_units=256, fc2_units=128): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed fcs1_units (int): Number of nodes in the first hidden layer fc2_units (int): Number of nodes in the second hidden layer """ super(Critic, self).__init__() self.seed = torch.manual_seed(seed) self.fcs1 = nn.Linear(state_size, fcs1_units) self.fc2 = nn.Linear(fcs1_units + action_size, fc2_units) self.fc3 = nn.Linear(fc2_units, 1) self.reset_parameters() def reset_parameters(self): self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1)) self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) self.fc3.weight.data.uniform_(-0.003, 0.003) def forward(self, state, action): """Build a critic (value) network that maps (state, action) pairs -> Q-values.""" xs = F.relu(self.fcs1(state)) x = torch.cat((xs, action), dim=1) x = F.relu(self.fc2(x)) return self.fc3(x) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'state_size': 4, 'action_size': 4, 'seed': 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 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 reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1040 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 260 x1 = xindex // 260 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 256, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (256 * x1 + x0), tmp4 & xmask, eviction_policy ='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full([1], 0, tl.int32) tmp9 = triton_helpers.maximum(tmp8, tmp7) tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp4, tmp9, tmp10) tmp12 = tmp0 >= tmp3 tl.full([1], 260, tl.int64) tmp15 = tl.load(in_ptr2 + (4 * x1 + (-256 + x0)), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.where(tmp4, tmp11, tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 128 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_2(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 x2 = xindex x0 = xindex % 256 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8) = args args.clear() assert_size_stride(primals_1, (256, 4), (4, 1)) assert_size_stride(primals_2, (256,), (1,)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (128, 260), (260, 1)) assert_size_stride(primals_6, (128,), (1,)) assert_size_stride(primals_7, (1, 128), (128, 1)) assert_size_stride(primals_8, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 256), (256, 1), torch.float32) extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 256), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((4, 260), (260, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(1040)](buf0, primals_2, primals_4, buf1, 1040, XBLOCK=128, num_warps=4, num_stages=1) del primals_4 buf2 = empty_strided_cuda((4, 128), (128, 1), torch.float32) extern_kernels.mm(buf1, reinterpret_tensor(primals_5, (260, 128), ( 1, 260), 0), out=buf2) buf3 = buf2 del buf2 triton_poi_fused_relu_1[grid(512)](buf3, primals_6, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_6 buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_8, buf3, reinterpret_tensor(primals_7, (128, 1), (1, 128), 0), alpha=1, beta=1, out=buf5) del primals_8 buf6 = empty_strided_cuda((4, 256), (256, 1), torch.bool) triton_poi_fused_relu_threshold_backward_2[grid(1024)](buf0, primals_2, buf6, 1024, XBLOCK=256, num_warps=4, num_stages=1) del buf0 del primals_2 return buf5, primals_3, buf1, buf3, primals_7, primals_5, buf6 def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1.0 / np.sqrt(fan_in) return -lim, lim class CriticNew(nn.Module): """Critic (Value) Model.""" def __init__(self, state_size, action_size, seed, fcs1_units=256, fc2_units=128): """Initialize parameters and build model. Params ====== state_size (int): Dimension of each state action_size (int): Dimension of each action seed (int): Random seed fcs1_units (int): Number of nodes in the first hidden layer fc2_units (int): Number of nodes in the second hidden layer """ super(CriticNew, self).__init__() self.seed = torch.manual_seed(seed) self.fcs1 = nn.Linear(state_size, fcs1_units) self.fc2 = nn.Linear(fcs1_units + action_size, fc2_units) self.fc3 = nn.Linear(fc2_units, 1) self.reset_parameters() def reset_parameters(self): self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1)) self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) self.fc3.weight.data.uniform_(-0.003, 0.003) def forward(self, input_0, input_1): primals_1 = self.fcs1.weight primals_2 = self.fcs1.bias primals_5 = self.fc2.weight primals_6 = self.fc2.bias primals_7 = self.fc3.weight primals_8 = self.fc3.bias primals_3 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8]) return output[0]
makarand-mac/continuous-control
Critic
false
12,754
[ "MIT" ]
0
6563d652770551ad2773e76daa9d536e617df01a
https://github.com/makarand-mac/continuous-control/tree/6563d652770551ad2773e76daa9d536e617df01a
FairDiscriminator
import torch import torch.nn as nn import torch.nn.functional as F class FairDiscriminator(nn.Module): def __init__(self, nfeat, nhid, nclass): """Just a simple MLP""" super(FairDiscriminator, self).__init__() self.hidden_layer = nn.Linear(nfeat, nhid) self.output_layer = nn.Linear(nhid, nclass) def forward(self, x): x = F.relu(self.hidden_layer(x)) x = F.relu(self.output_layer(x)) return F.log_softmax(x, dim=1) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'nfeat': 4, 'nhid': 4, 'nclass': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import math as tl_math import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(in_out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused__log_softmax_relu_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 // 16 x3 = xindex % 16 x0 = xindex % 4 x4 = xindex tmp0 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask) tmp9 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask) tmp13 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask) tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = tmp5 + tmp1 tmp7 = triton_helpers.maximum(tmp3, tmp6) tmp8 = triton_helpers.maximum(tmp4, tmp7) tmp10 = tmp9 + tmp1 tmp11 = triton_helpers.maximum(tmp3, tmp10) tmp12 = triton_helpers.maximum(tmp8, tmp11) tmp14 = tmp13 + tmp1 tmp15 = triton_helpers.maximum(tmp3, tmp14) tmp16 = triton_helpers.maximum(tmp12, tmp15) tmp17 = tmp4 - tmp16 tmp18 = tl_math.exp(tmp17) tmp19 = tmp7 - tmp16 tmp20 = tl_math.exp(tmp19) tmp21 = tmp18 + tmp20 tmp22 = tmp11 - tmp16 tmp23 = tl_math.exp(tmp22) tmp24 = tmp21 + tmp23 tmp25 = tmp15 - tmp16 tmp26 = tl_math.exp(tmp25) tmp27 = tmp24 + tmp26 tmp28 = tl_math.log(tmp27) tl.store(out_ptr0 + x4, tmp16, xmask) tl.store(out_ptr1 + x4, tmp28, xmask) @triton.jit def triton_poi_fused__log_softmax_relu_threshold_backward_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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 x5 = xindex x0 = xindex % 4 x3 = xindex // 64 x6 = xindex % 16 tmp0 = tl.load(in_ptr0 + x5, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr2 + (x6 + 16 * x3), xmask, eviction_policy= 'evict_last') tmp7 = tl.load(in_ptr3 + (x6 + 16 * x3), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = tmp4 - tmp5 tmp8 = tmp6 - tmp7 tmp9 = 0.0 tmp10 = tmp4 <= tmp9 tl.store(out_ptr0 + x5, tmp8, xmask) tl.store(out_ptr1 + x5, tmp10, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.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) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2) buf3 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) buf4 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) triton_poi_fused__log_softmax_relu_1[grid(64)](buf2, primals_5, buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1) 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__log_softmax_relu_threshold_backward_2[grid(256)](buf2 , primals_5, buf3, buf4, buf5, buf6, 256, XBLOCK=256, num_warps =4, num_stages=1) del buf2 del buf3 del buf4 del primals_5 return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0 ), buf5, buf6, primals_4, buf7 class FairDiscriminatorNew(nn.Module): def __init__(self, nfeat, nhid, nclass): """Just a simple MLP""" super(FairDiscriminatorNew, self).__init__() self.hidden_layer = nn.Linear(nfeat, nhid) self.output_layer = nn.Linear(nhid, nclass) def forward(self, input_0): primals_1 = self.hidden_layer.weight primals_2 = self.hidden_layer.bias primals_4 = self.output_layer.weight primals_5 = self.output_layer.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
markheimann/fgc
FairDiscriminator
false
12,755
[ "MIT" ]
0
909d4f0a84c9b61a8030f9f3f50b17f143576007
https://github.com/markheimann/fgc/tree/909d4f0a84c9b61a8030f9f3f50b17f143576007
TransformerDecoderLayer
import torch from torch import Tensor from typing import Optional from torch import nn def _get_activation_fn(activation: 'str'): if activation == 'relu': return nn.functional.relu elif activation == 'gelu': return nn.functional.gelu raise RuntimeError('activation should be relu/gelu, not {}'.format( activation)) class TransformerDecoderLayer(nn.Module): """ Modified from torch.nn.TransformerDecoderLayer. Add support of normalize_before, i.e., use layer_norm before the first block. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). Examples:: >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) >>> memory = torch.rand(10, 32, 512) >>> tgt = torch.rand(20, 32, 512) >>> out = decoder_layer(tgt, memory) """ def __init__(self, d_model: 'int', nhead: 'int', dim_feedforward: 'int' =2048, dropout: 'float'=0.1, activation: 'str'='relu', normalize_before: 'bool'=True) ->None: super(TransformerDecoderLayer, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0) self.src_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0) self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.norm3 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def __setstate__(self, state): if 'activation' not in state: state['activation'] = nn.functional.relu super(TransformerDecoderLayer, self).__setstate__(state) 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: """Pass the inputs (and mask) through the decoder layer. Args: tgt: the sequence to the decoder layer (required). memory: the sequence from the last layer of the encoder (required). tgt_mask: the mask for the tgt sequence (optional). memory_mask: the mask for the memory sequence (optional). tgt_key_padding_mask: the mask for the tgt keys per batch (optional). memory_key_padding_mask: the mask for the memory keys per batch (optional). Shape: tgt: (T, N, E). memory: (S, N, E). tgt_mask: (T, T). memory_mask: (T, S). tgt_key_padding_mask: (N, T). memory_key_padding_mask: (N, S). S is the source sequence length, T is the target sequence length, N is the batch size, E is the feature number """ residual = tgt if self.normalize_before: tgt = self.norm1(tgt) tgt2 = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0] tgt = residual + self.dropout1(tgt2) if not self.normalize_before: tgt = self.norm1(tgt) residual = tgt if self.normalize_before: tgt = self.norm2(tgt) tgt2 = self.src_attn(tgt, memory, memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)[0] tgt = residual + self.dropout2(tgt2) if not self.normalize_before: tgt = self.norm2(tgt) residual = tgt if self.normalize_before: tgt = self.norm3(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = residual + self.dropout3(tgt2) if not self.normalize_before: tgt = self.norm3(tgt) return tgt def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'d_model': 4, 'nhead': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math 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_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-05 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_mul_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused__softmax_3(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_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_clone_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 4 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask) tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_native_layer_norm_6(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 + tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 + tmp12 tmp14 = tmp10 + tmp13 tmp15 = 4.0 tmp16 = tmp14 / tmp15 tmp17 = tmp2 - tmp16 tmp18 = tmp17 * tmp17 tmp19 = tmp5 - tmp16 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = tmp9 - tmp16 tmp23 = tmp22 * tmp22 tmp24 = tmp21 + tmp23 tmp25 = tmp13 - tmp16 tmp26 = tmp25 * tmp25 tmp27 = tmp24 + tmp26 tmp28 = tmp27 / tmp15 tl.store(out_ptr0 + x0, tmp16, xmask) tl.store(out_ptr1 + x0, tmp28, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_7(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x2, xmask) tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp6 = 1e-05 tmp7 = tmp5 + tmp6 tmp8 = libdevice.rsqrt(tmp7) tmp9 = tmp4 * tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tl.store(out_ptr0 + x2, tmp13, xmask) @triton.jit def triton_poi_fused_add_8(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + 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) @triton.jit def triton_poi_fused_relu_9(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 2048 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_out_ptr0 + x2, xmask) tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) 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, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (12, 4), (4, 1)) assert_size_stride(primals_5, (12,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 4), (4, 1)) assert_size_stride(primals_11, (12, 4), (4, 1)) assert_size_stride(primals_12, (12,), (1,)) assert_size_stride(primals_13, (4, 4), (4, 1)) assert_size_stride(primals_14, (4,), (1,)) assert_size_stride(primals_15, (4,), (1,)) assert_size_stride(primals_16, (4,), (1,)) assert_size_stride(primals_17, (2048, 4), (4, 1)) assert_size_stride(primals_18, (2048,), (1,)) assert_size_stride(primals_19, (4, 2048), (2048, 1)) assert_size_stride(primals_20, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1), (1, 4), torch.float32) buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32) get_raw_stream(0) triton_poi_fused_native_layer_norm_0[grid(4)](primals_1, buf0, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(16)](primals_1, buf0, buf1, primals_2, primals_3, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_2 del primals_3 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4 ), 0), out=buf3) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 4), buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4), 16), alpha= 1, beta=1, out=buf4) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8), buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha= 1, beta=1, out=buf5) buf6 = reinterpret_tensor(buf3, (4, 4, 1), (1, 4, 16), 0) del buf3 triton_poi_fused_mul_2[grid(16)](buf6, primals_5, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf6, reinterpret_tensor(buf4, (4, 1, 4), (1, 1, 4), 0), out=buf7) buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_3[grid(64)](buf7, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = buf7 del buf7 triton_poi_fused__softmax_4[grid(64)](buf8, buf9, 64, XBLOCK=64, num_warps=1, num_stages=1) buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf9, reinterpret_tensor(buf5, (4, 4, 1), (1, 4, 1), 0), out=buf10) buf11 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) triton_poi_fused_clone_5[grid(4, 4)](buf10, buf11, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1) buf12 = reinterpret_tensor(buf10, (4, 4), (4, 1), 0) del buf10 extern_kernels.addmm(primals_7, reinterpret_tensor(buf11, (4, 4), ( 4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf12) del primals_7 buf13 = buf1 del buf1 buf14 = buf0 del buf0 triton_poi_fused_add_native_layer_norm_6[grid(4)](primals_1, buf12, buf13, buf14, 4, XBLOCK=4, num_warps=1, num_stages=1) buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_7[grid(16)](primals_1, buf12, buf13, buf14, primals_8, primals_9, buf15, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_9 buf16 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf15, reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf16) buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_12, (4,), (1,), 4), primals_10, reinterpret_tensor(primals_11, (4, 4), (1, 4), 16), alpha=1, beta=1, out=buf17) buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_12, (4,), (1,), 8), primals_10, reinterpret_tensor(primals_11, (4, 4), (1, 4), 32), alpha=1, beta=1, out=buf18) buf19 = reinterpret_tensor(buf16, (4, 4, 1), (1, 4, 16), 0) del buf16 triton_poi_fused_mul_2[grid(16)](buf19, primals_12, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_12 buf20 = buf8 del buf8 extern_kernels.bmm(buf19, reinterpret_tensor(buf17, (4, 1, 4), (1, 1, 4), 0), out=buf20) buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_3[grid(64)](buf20, buf21, 64, XBLOCK=64, num_warps=1, num_stages=1) buf22 = buf20 del buf20 triton_poi_fused__softmax_4[grid(64)](buf21, buf22, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf21 buf23 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf22, reinterpret_tensor(buf18, (4, 4, 1), (1, 4, 1), 0), out=buf23) buf24 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) triton_poi_fused_clone_5[grid(4, 4)](buf23, buf24, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1) buf25 = reinterpret_tensor(buf23, (4, 4), (4, 1), 0) del buf23 extern_kernels.mm(reinterpret_tensor(buf24, (4, 4), (4, 1), 0), reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), out=buf25) buf26 = buf25 del buf25 triton_poi_fused_add_8[grid(16)](buf26, primals_1, buf12, primals_14, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_14 buf27 = buf14 del buf14 buf28 = buf13 del buf13 triton_poi_fused_native_layer_norm_0[grid(4)](buf26, buf27, buf28, 4, XBLOCK=4, num_warps=1, num_stages=1) buf29 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(16)](buf26, buf27, buf28, primals_15, primals_16, buf29, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf27 del buf28 del primals_16 buf30 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32) extern_kernels.mm(buf29, reinterpret_tensor(primals_17, (4, 2048), (1, 4), 0), out=buf30) buf31 = buf30 del buf30 triton_poi_fused_relu_9[grid(8192)](buf31, primals_18, 8192, XBLOCK =256, num_warps=4, num_stages=1) del primals_18 buf32 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf31, reinterpret_tensor(primals_19, (2048, 4), (1, 2048), 0), out=buf32) buf33 = buf32 del buf32 triton_poi_fused_add_10[grid(16)](buf33, buf26, primals_20, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_20 return (buf33, primals_1, primals_8, primals_15, buf2, buf9, reinterpret_tensor(buf11, (4, 4), (4, 1), 0), buf12, buf15, primals_10, buf22, reinterpret_tensor(buf24, (4, 4), (4, 1), 0), buf26, buf29, buf31, primals_19, primals_17, primals_13, reinterpret_tensor(buf18, (4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf19, (4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf17, (4, 4, 1), (1, 4, 1), 0), reinterpret_tensor(primals_11, (4, 4), (4, 1), 0), primals_6, reinterpret_tensor(buf5, (4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf6, (4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf4, (4, 4, 1), (1, 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (4, 1), 32), reinterpret_tensor(primals_4, (4, 4), (4, 1), 16), reinterpret_tensor(primals_4, (4, 4), (4, 1), 0)) def _get_activation_fn(activation: 'str'): if activation == 'relu': return nn.functional.relu elif activation == 'gelu': return nn.functional.gelu raise RuntimeError('activation should be relu/gelu, not {}'.format( activation)) class TransformerDecoderLayerNew(nn.Module): """ Modified from torch.nn.TransformerDecoderLayer. Add support of normalize_before, i.e., use layer_norm before the first block. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). Examples:: >>> decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8) >>> memory = torch.rand(10, 32, 512) >>> tgt = torch.rand(20, 32, 512) >>> out = decoder_layer(tgt, memory) """ def __init__(self, d_model: 'int', nhead: 'int', dim_feedforward: 'int' =2048, dropout: 'float'=0.1, activation: 'str'='relu', normalize_before: 'bool'=True) ->None: super(TransformerDecoderLayerNew, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0) self.src_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0) self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.norm3 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def __setstate__(self, state): if 'activation' not in state: state['activation'] = nn.functional.relu super(TransformerDecoderLayerNew, self).__setstate__(state) def forward(self, input_0, input_1): primals_4 = self.self_attn.in_proj_weight primals_5 = self.self_attn.in_proj_bias primals_1 = self.self_attn.out_proj.weight primals_2 = self.self_attn.out_proj.bias primals_11 = self.src_attn.in_proj_weight primals_12 = self.src_attn.in_proj_bias primals_6 = self.src_attn.out_proj.weight primals_3 = self.src_attn.out_proj.bias primals_17 = self.linear1.weight primals_18 = self.linear1.bias primals_19 = self.linear2.weight primals_7 = self.linear2.bias primals_8 = self.norm1.weight primals_9 = self.norm1.bias primals_14 = self.norm2.weight primals_15 = self.norm2.bias primals_16 = self.norm3.weight primals_20 = self.norm3.bias primals_10 = input_0 primals_13 = 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]
johnjosephmorgan/snowfall
TransformerDecoderLayer
false
12,756
[ "Apache-2.0" ]
0
604d789c0aed035626d6745e6d7a427168063cae
https://github.com/johnjosephmorgan/snowfall/tree/604d789c0aed035626d6745e6d7a427168063cae
CRF
import torch from torch import nn class CRF(nn.Module): def __init__(self, num_nodes, iteration=10): """Initialize the CRF module Args: num_nodes: int, number of nodes/patches within the fully CRF iteration: int, number of mean field iterations, e.g. 10 """ super(CRF, self).__init__() self.num_nodes = num_nodes self.iteration = iteration self.W = nn.Parameter(torch.zeros(1, num_nodes, num_nodes)) def forward(self, feats, logits): """Performing the CRF. Algorithm details is explained below: Within the paper, I formulate the CRF distribution using negative energy and cost, e.g. cosine distance, to derive pairwise potentials following the convention in energy based models. But for implementation simplicity, I use reward, e.g. cosine similarity to derive pairwise potentials. So now, pairwise potentials would encourage high reward for assigning (y_i, y_j) with the same label if (x_i, x_j) are similar, as measured by cosine similarity, pairwise_sim. For pairwise_potential_E = torch.sum( probs * pairwise_potential - (1 - probs) * pairwise_potential, dim=2, keepdim=True ) This is taking the expectation of pairwise potentials using the current marginal distribution of each patch being tumor, i.e. probs. There are four cases to consider when taking the expectation between (i, j): 1. i=T,j=T; 2. i=N,j=T; 3. i=T,j=N; 4. i=N,j=N probs is the marginal distribution of each i being tumor, therefore logits > 0 means tumor and logits < 0 means normal. Given this, the full expectation equation should be: [probs * +pairwise_potential] + [(1 - probs) * +pairwise_potential] + case 1 case 2 [probs * -pairwise_potential] + [(1 - probs) * -pairwise_potential] case 3 case 4 positive sign rewards logits to be more tumor and negative sign rewards logits to be more normal. But because of label compatibility, i.e. the indicator function within equation 3 in the paper, case 2 and case 3 are dropped, which ends up being: probs * pairwise_potential - (1 - probs) * pairwise_potential In high level speaking, if (i, j) embedding are different, then pairwise_potential, as computed as cosine similarity, would approach 0, which then as no affect anyway. if (i, j) embedding are similar, then pairwise_potential would be a positive reward. In this case, if probs -> 1, then pairwise_potential promotes tumor probability; if probs -> 0, then -pairwise_potential promotes normal probability. Args: feats: 3D tensor with the shape of [batch_size, num_nodes, embedding_size], where num_nodes is the number of patches within a grid, e.g. 9 for a 3x3 grid; embedding_size is the size of extracted feature representation for each patch from ResNet, e.g. 512 logits: 3D tensor with shape of [batch_size, num_nodes, 1], the logit of each patch within the grid being tumor before CRF Returns: logits: 3D tensor with shape of [batch_size, num_nodes, 1], the logit of each patch within the grid being tumor after CRF """ feats_norm = torch.norm(feats, p=2, dim=2, keepdim=True) pairwise_norm = torch.bmm(feats_norm, torch.transpose(feats_norm, 1, 2) ) pairwise_dot = torch.bmm(feats, torch.transpose(feats, 1, 2)) pairwise_sim = pairwise_dot / pairwise_norm W_sym = (self.W + torch.transpose(self.W, 1, 2)) / 2 pairwise_potential = pairwise_sim * W_sym unary_potential = logits.clone() for i in range(self.iteration): probs = torch.transpose(logits.sigmoid(), 1, 2) pairwise_potential_E = torch.sum(probs * pairwise_potential - ( 1 - probs) * pairwise_potential, dim=2, keepdim=True) logits = unary_potential + pairwise_potential_E return logits def __repr__(self): return 'CRF(num_nodes={}, iteration={})'.format(self.num_nodes, self.iteration) def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'num_nodes': 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_linalg_vector_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') 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_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_ptr0 + x0, xmask) tmp1 = tl.load(in_out_ptr0 + x0, xmask) tmp2 = tmp0 / tmp1 tl.store(in_out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused_add_div_mul_rsub_sub_sum_2(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 x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask) tmp2 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last') tmp14 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask) tmp16 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp17 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp18 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last') tmp27 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask) tmp29 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp30 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp31 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last') tmp40 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask) tmp42 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp43 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp44 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last') tmp1 = tl.sigmoid(tmp0) tmp5 = tmp3 + tmp4 tmp6 = 0.5 tmp7 = tmp5 * tmp6 tmp8 = tmp2 * tmp7 tmp9 = tmp1 * tmp8 tmp10 = 1.0 tmp11 = tmp10 - tmp1 tmp12 = tmp11 * tmp8 tmp13 = tmp9 - tmp12 tmp15 = tl.sigmoid(tmp14) tmp19 = tmp17 + tmp18 tmp20 = tmp19 * tmp6 tmp21 = tmp16 * tmp20 tmp22 = tmp15 * tmp21 tmp23 = tmp10 - tmp15 tmp24 = tmp23 * tmp21 tmp25 = tmp22 - tmp24 tmp26 = tmp13 + tmp25 tmp28 = tl.sigmoid(tmp27) tmp32 = tmp30 + tmp31 tmp33 = tmp32 * tmp6 tmp34 = tmp29 * tmp33 tmp35 = tmp28 * tmp34 tmp36 = tmp10 - tmp28 tmp37 = tmp36 * tmp34 tmp38 = tmp35 - tmp37 tmp39 = tmp26 + tmp38 tmp41 = tl.sigmoid(tmp40) tmp45 = tmp43 + tmp44 tmp46 = tmp45 * tmp6 tmp47 = tmp42 * tmp46 tmp48 = tmp41 * tmp47 tmp49 = tmp10 - tmp41 tmp50 = tmp49 * tmp47 tmp51 = tmp48 - tmp50 tmp52 = tmp39 + tmp51 tl.store(out_ptr0 + x2, tmp52, xmask) @triton.jit def triton_poi_fused_add_div_mul_rsub_sub_sum_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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_ptr1 + 4 * x1, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr2 + 4 * x2, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + 4 * x0, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp16 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask) tmp17 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp20 = tl.load(in_ptr2 + (1 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp21 = tl.load(in_ptr3 + (1 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp22 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last') tmp31 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask) tmp32 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp35 = tl.load(in_ptr2 + (2 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp36 = tl.load(in_ptr3 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp37 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last') tmp46 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask) tmp47 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp50 = tl.load(in_ptr2 + (3 + 4 * x2), xmask, eviction_policy='evict_last' ) tmp51 = tl.load(in_ptr3 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp52 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tmp7 = tmp5 + tmp6 tmp8 = 0.5 tmp9 = tmp7 * tmp8 tmp10 = tmp4 * tmp9 tmp11 = tmp3 * tmp10 tmp12 = 1.0 tmp13 = tmp12 - tmp3 tmp14 = tmp13 * tmp10 tmp15 = tmp11 - tmp14 tmp18 = tmp16 + tmp17 tmp19 = tl.sigmoid(tmp18) tmp23 = tmp21 + tmp22 tmp24 = tmp23 * tmp8 tmp25 = tmp20 * tmp24 tmp26 = tmp19 * tmp25 tmp27 = tmp12 - tmp19 tmp28 = tmp27 * tmp25 tmp29 = tmp26 - tmp28 tmp30 = tmp15 + tmp29 tmp33 = tmp31 + tmp32 tmp34 = tl.sigmoid(tmp33) tmp38 = tmp36 + tmp37 tmp39 = tmp38 * tmp8 tmp40 = tmp35 * tmp39 tmp41 = tmp34 * tmp40 tmp42 = tmp12 - tmp34 tmp43 = tmp42 * tmp40 tmp44 = tmp41 - tmp43 tmp45 = tmp30 + tmp44 tmp48 = tmp46 + tmp47 tmp49 = tl.sigmoid(tmp48) tmp53 = tmp51 + tmp52 tmp54 = tmp53 * tmp8 tmp55 = tmp50 * tmp54 tmp56 = tmp49 * tmp55 tmp57 = tmp12 - tmp49 tmp58 = tmp57 * tmp55 tmp59 = tmp56 - tmp58 tmp60 = tmp45 + tmp59 tl.store(out_ptr0 + x2, tmp60, xmask) @triton.jit def triton_poi_fused_add_4(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 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) 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, 4), (16, 4, 1)) assert_size_stride(primals_3, (4, 4, 4), (16, 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_linalg_vector_norm_0[grid(16)](primals_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf0, reinterpret_tensor(buf0, (4, 1, 4), (4, 16, 1), 0), out=buf1) buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(primals_1, reinterpret_tensor(primals_1, (4, 4, 4), (16, 1, 4), 0), out=buf2) del primals_1 buf3 = buf1 del buf1 triton_poi_fused_div_1[grid(64)](buf3, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) buf4 = buf0 del buf0 triton_poi_fused_add_div_mul_rsub_sub_sum_2[grid(16)](primals_3, buf3, primals_2, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf4, buf3, primals_2, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1) buf6 = buf4 del buf4 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf5, buf3, primals_2, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1) buf7 = buf5 del buf5 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf6, buf3, primals_2, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1) buf8 = buf6 del buf6 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf7, buf3, primals_2, buf8, 16, XBLOCK=16, num_warps=1, num_stages=1) buf9 = buf7 del buf7 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf8, buf3, primals_2, buf9, 16, XBLOCK=16, num_warps=1, num_stages=1) buf10 = buf8 del buf8 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf9, buf3, primals_2, buf10, 16, XBLOCK=16, num_warps=1, num_stages=1) buf11 = buf9 del buf9 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf10, buf3, primals_2, buf11, 16, XBLOCK=16, num_warps=1, num_stages=1) buf12 = buf10 del buf10 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf11, buf3, primals_2, buf12, 16, XBLOCK=16, num_warps=1, num_stages=1) buf13 = buf11 del buf11 triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3, buf12, buf3, primals_2, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf12 buf14 = buf2 del buf2 triton_poi_fused_add_4[grid(64)](primals_3, buf13, buf14, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf13 return buf14, primals_2, primals_3, buf3 class CRFNew(nn.Module): def __init__(self, num_nodes, iteration=10): """Initialize the CRF module Args: num_nodes: int, number of nodes/patches within the fully CRF iteration: int, number of mean field iterations, e.g. 10 """ super(CRFNew, self).__init__() self.num_nodes = num_nodes self.iteration = iteration self.W = nn.Parameter(torch.zeros(1, num_nodes, num_nodes)) def __repr__(self): return 'CRF(num_nodes={}, iteration={})'.format(self.num_nodes, self.iteration) def forward(self, input_0, input_1): primals_2 = self.W primals_1 = input_0 primals_3 = input_1 output = call([primals_1, primals_2, primals_3]) return output[0]
lzx325/NCRF
CRF
false
12,757
[ "Apache-2.0" ]
0
2fc081184e3bc45b043e4c8c0a94644a0149e54c
https://github.com/lzx325/NCRF/tree/2fc081184e3bc45b043e4c8c0a94644a0149e54c
Attn
import math import torch import torch.nn.functional as F import torch.nn as nn class Attn(nn.Module): def __init__(self, method, hidden_size): super(Attn, 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): """ :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) :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) return F.softmax(attn_energies, dim=1).unsqueeze(1) def score(self, hidden, encoder_outputs): cat = torch.cat([hidden, encoder_outputs], 2) energy = torch.tanh(self.attn(cat)) 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 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 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 AttnNew(nn.Module): def __init__(self, method, hidden_size): super(AttnNew, 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): cat = torch.cat([hidden, encoder_outputs], 2) energy = torch.tanh(self.attn(cat)) 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]
marvinzh/ConvLab
Attn
false
12,758
[ "MIT" ]
0
45ac46b805e064f783b3a1a409b0902ac81da661
https://github.com/marvinzh/ConvLab/tree/45ac46b805e064f783b3a1a409b0902ac81da661
DilatedResidualLayer
import torch import torch.nn as nn import torch.nn.functional as F class DilatedResidualLayer(nn.Module): def __init__(self, dilation, in_channels, out_channels): super(DilatedResidualLayer, self).__init__() self.conv_dilated = nn.Conv1d(in_channels, out_channels, 3, padding =dilation, dilation=dilation) self.conv_1x1 = nn.Conv1d(out_channels, out_channels, 1) self.dropout = nn.Dropout() def forward(self, x, mask, i, norm=512): out = F.relu(self.conv_dilated(x)) out = self.conv_1x1(out) out = self.dropout(out) return (x + out * i / norm) * mask[:, 0:1, :] def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4]) ] def get_init_inputs(): return [[], {'dilation': 1, 'in_channels': 4, 'out_channels': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_add_convolution_div_mul_1(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 x3 = xindex x1 = xindex // 4 % 4 x0 = xindex % 4 x2 = xindex // 16 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_out_ptr0 + x3, xmask) tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr2 + x3, xmask) tmp9 = tl.load(in_ptr3 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 * tmp4 tmp6 = 0.001953125 tmp7 = tmp5 * tmp6 tmp8 = tmp0 + tmp7 tmp10 = tmp8 * tmp9 tl.store(in_out_ptr0 + x3, 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, 3), (12, 3, 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, 1), (4, 1, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_7, (4, 4, 4), (16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,), padding=(1,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 4), (16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(64)](buf1, primals_2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf2, (4, 4, 4), (16, 4, 1)) buf3 = buf2 del buf2 triton_poi_fused_add_convolution_div_mul_1[grid(64)](buf3, primals_3, primals_5, primals_6, primals_7, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_5 return (buf3, primals_1, primals_3, primals_4, primals_6, buf1, reinterpret_tensor(primals_7, (4, 1, 4), (16, 4, 1), 0)) class DilatedResidualLayerNew(nn.Module): def __init__(self, dilation, in_channels, out_channels): super(DilatedResidualLayerNew, self).__init__() self.conv_dilated = nn.Conv1d(in_channels, out_channels, 3, padding =dilation, dilation=dilation) self.conv_1x1 = nn.Conv1d(out_channels, out_channels, 1) self.dropout = nn.Dropout() def forward(self, input_0, input_1, input_2): primals_1 = self.conv_dilated.weight primals_2 = self.conv_dilated.bias primals_4 = self.conv_1x1.weight primals_5 = self.conv_1x1.bias primals_3 = input_0 primals_6 = input_1 primals_7 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
manthan-kodar/Action-seg-experiments
DilatedResidualLayer
false
12,759
[ "MIT" ]
0
3515ee64082ab567838782f5600e186bf86473a0
https://github.com/manthan-kodar/Action-seg-experiments/tree/3515ee64082ab567838782f5600e186bf86473a0
AddNorm
import torch from torch import nn class AddNorm(nn.Module): def __init__(self, normalized_shape, dropout, **kwargs): super(AddNorm, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) self.ln = nn.LayerNorm(normalized_shape) def forward(self, X, Y): return self.ln(self.dropout(Y) + X) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'normalized_shape': 4, 'dropout': 0.5}]
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_native_layer_norm_0(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 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_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, 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 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, tmp9, xmask) tl.store(out_ptr1 + x2, tmp13, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32) buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32) get_raw_stream(0) triton_poi_fused_add_native_layer_norm_0[grid(64)](primals_1, primals_2, 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) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_1[grid(256)](primals_1, primals_2, buf0, buf1, primals_3, primals_4, buf2, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf0 del buf1 del primals_1 del primals_2 del primals_3 del primals_4 return buf3, buf2 class AddNormNew(nn.Module): def __init__(self, normalized_shape, dropout, **kwargs): super(AddNormNew, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) self.ln = nn.LayerNorm(normalized_shape) def forward(self, input_0, input_1): primals_3 = self.ln.weight primals_4 = self.ln.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
lucmertins/CapDeepLearningBook
AddNorm
false
12,760
[ "MIT" ]
0
e5959b552c8716e7fc65a21ae9c13c58509544c1
https://github.com/lucmertins/CapDeepLearningBook/tree/e5959b552c8716e7fc65a21ae9c13c58509544c1
TransformerEncoderLayer
import torch from torch import Tensor from typing import Optional from torch import nn def _get_activation_fn(activation: 'str'): if activation == 'relu': return nn.functional.relu elif activation == 'gelu': return nn.functional.gelu raise RuntimeError('activation should be relu/gelu, not {}'.format( activation)) class TransformerEncoderLayer(nn.Module): """ Modified from torch.nn.TransformerEncoderLayer. Add support of normalize_before, i.e., use layer_norm before the first block. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). normalize_before: whether to use layer_norm before the first block. Examples:: >>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8) >>> src = torch.rand(10, 32, 512) >>> out = encoder_layer(src) """ def __init__(self, d_model: 'int', nhead: 'int', dim_feedforward: 'int' =2048, dropout: 'float'=0.1, activation: 'str'='relu', normalize_before: 'bool'=True) ->None: super(TransformerEncoderLayer, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0) self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def __setstate__(self, state): if 'activation' not in state: state['activation'] = nn.functional.relu super(TransformerEncoderLayer, self).__setstate__(state) def forward(self, src: 'Tensor', src_mask: 'Optional[Tensor]'=None, src_key_padding_mask: 'Optional[Tensor]'=None) ->Tensor: """ Pass the input through the encoder layer. Args: src: the sequence to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: src: (S, N, E). src_mask: (S, S). src_key_padding_mask: (N, S). S is the source sequence length, T is the target sequence length, N is the batch size, E is the feature number """ residual = src if self.normalize_before: src = self.norm1(src) src2 = self.self_attn(src, src, src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] src = residual + self.dropout1(src2) if not self.normalize_before: src = self.norm1(src) residual = src if self.normalize_before: src = self.norm2(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = residual + self.dropout2(src2) if not self.normalize_before: src = self.norm2(src) return src def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'d_model': 4, 'nhead': 4}]
import torch from torch._inductor.select_algorithm import extern_kernels import triton import triton.language as tl from torch._inductor.runtime.triton_heuristics import grid from torch._C import _cuda_getCurrentRawStream as get_raw_stream from torch._inductor.runtime import triton_helpers from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math 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_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-05 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_mul_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused__softmax_3(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_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_clone_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 4 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask) tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_native_layer_norm_6(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 + tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 + tmp12 tmp14 = tmp10 + tmp13 tmp15 = 4.0 tmp16 = tmp14 / tmp15 tmp17 = tmp2 - tmp16 tmp18 = tmp17 * tmp17 tmp19 = tmp5 - tmp16 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = tmp9 - tmp16 tmp23 = tmp22 * tmp22 tmp24 = tmp21 + tmp23 tmp25 = tmp13 - tmp16 tmp26 = tmp25 * tmp25 tmp27 = tmp24 + tmp26 tmp28 = tmp27 / tmp15 tl.store(out_ptr0 + x0, tmp16, xmask) tl.store(out_ptr1 + x0, tmp28, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_7(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x2, xmask) tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp6 = 1e-05 tmp7 = tmp5 + tmp6 tmp8 = libdevice.rsqrt(tmp7) tmp9 = tmp4 * tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tl.store(out_ptr0 + x2, tmp13, xmask) @triton.jit def triton_poi_fused_relu_8(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x2 = xindex x0 = xindex % 2048 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_add_9(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + 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) = 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,), (1,)) assert_size_stride(primals_4, (12, 4), (4, 1)) assert_size_stride(primals_5, (12,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (2048, 4), (4, 1)) assert_size_stride(primals_11, (2048,), (1,)) assert_size_stride(primals_12, (4, 2048), (2048, 1)) assert_size_stride(primals_13, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1), (1, 4), torch.float32) buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32) get_raw_stream(0) triton_poi_fused_native_layer_norm_0[grid(4)](primals_1, buf0, buf1, 4, XBLOCK=4, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(16)](primals_1, buf0, buf1, primals_2, primals_3, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_2 del primals_3 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4 ), 0), out=buf3) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 4), buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4), 16), alpha= 1, beta=1, out=buf4) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8), buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha= 1, beta=1, out=buf5) buf6 = reinterpret_tensor(buf3, (4, 4, 1), (1, 4, 16), 0) del buf3 triton_poi_fused_mul_2[grid(16)](buf6, primals_5, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf6, reinterpret_tensor(buf4, (4, 1, 4), (1, 1, 4), 0), out=buf7) buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_3[grid(64)](buf7, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1) buf9 = buf7 del buf7 triton_poi_fused__softmax_4[grid(64)](buf8, buf9, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf8 buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf9, reinterpret_tensor(buf5, (4, 4, 1), (1, 4, 1), 0), out=buf10) buf11 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) triton_poi_fused_clone_5[grid(4, 4)](buf10, buf11, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1) buf12 = reinterpret_tensor(buf10, (4, 4), (4, 1), 0) del buf10 extern_kernels.addmm(primals_7, reinterpret_tensor(buf11, (4, 4), ( 4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf12) del primals_7 buf13 = buf1 del buf1 buf14 = buf0 del buf0 triton_poi_fused_add_native_layer_norm_6[grid(4)](primals_1, buf12, buf13, buf14, 4, XBLOCK=4, num_warps=1, num_stages=1) buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_7[grid(16)](primals_1, buf12, buf13, buf14, primals_8, primals_9, buf15, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf13 del buf14 del primals_9 buf16 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32) extern_kernels.mm(buf15, reinterpret_tensor(primals_10, (4, 2048), (1, 4), 0), out=buf16) buf17 = buf16 del buf16 triton_poi_fused_relu_8[grid(8192)](buf17, primals_11, 8192, XBLOCK =128, num_warps=4, num_stages=1) del primals_11 buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf17, reinterpret_tensor(primals_12, (2048, 4), (1, 2048), 0), out=buf18) buf19 = buf18 del buf18 triton_poi_fused_add_9[grid(16)](buf19, primals_1, buf12, primals_13, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_13 return (buf19, primals_1, primals_8, buf2, buf9, reinterpret_tensor( buf11, (4, 4), (4, 1), 0), buf12, buf15, buf17, primals_12, primals_10, primals_6, reinterpret_tensor(buf5, (4, 1, 4), (1, 1, 4 ), 0), reinterpret_tensor(buf6, (4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf4, (4, 4, 1), (1, 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (4, 1), 32), reinterpret_tensor(primals_4, (4, 4), (4, 1), 16), reinterpret_tensor(primals_4, (4, 4), (4, 1), 0)) def _get_activation_fn(activation: 'str'): if activation == 'relu': return nn.functional.relu elif activation == 'gelu': return nn.functional.gelu raise RuntimeError('activation should be relu/gelu, not {}'.format( activation)) class TransformerEncoderLayerNew(nn.Module): """ Modified from torch.nn.TransformerEncoderLayer. Add support of normalize_before, i.e., use layer_norm before the first block. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). normalize_before: whether to use layer_norm before the first block. Examples:: >>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8) >>> src = torch.rand(10, 32, 512) >>> out = encoder_layer(src) """ def __init__(self, d_model: 'int', nhead: 'int', dim_feedforward: 'int' =2048, dropout: 'float'=0.1, activation: 'str'='relu', normalize_before: 'bool'=True) ->None: super(TransformerEncoderLayerNew, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0) self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before def __setstate__(self, state): if 'activation' not in state: state['activation'] = nn.functional.relu super(TransformerEncoderLayerNew, self).__setstate__(state) def forward(self, input_0): primals_4 = self.self_attn.in_proj_weight primals_5 = self.self_attn.in_proj_bias primals_1 = self.self_attn.out_proj.weight primals_2 = self.self_attn.out_proj.bias primals_10 = self.linear1.weight primals_11 = self.linear1.bias primals_12 = self.linear2.weight primals_3 = self.linear2.bias primals_7 = self.norm1.weight primals_8 = self.norm1.bias primals_9 = self.norm2.weight primals_13 = self.norm2.bias primals_6 = 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]
johnjosephmorgan/snowfall
TransformerEncoderLayer
false
12,761
[ "Apache-2.0" ]
0
604d789c0aed035626d6745e6d7a427168063cae
https://github.com/johnjosephmorgan/snowfall/tree/604d789c0aed035626d6745e6d7a427168063cae
EncoderLayer
import math import torch import torch.nn.functional as F import torch.nn as nn def attention(q, k, v, d_k, mask=None, dropout=None): scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: mask = mask.unsqueeze(1) scores = scores.masked_fill(mask == 0, -1000000000.0) scores = F.softmax(scores, dim=-1) if dropout is not None: scores = dropout(scores) output = torch.matmul(scores, v) return output class FeedForward(nn.Module): def __init__(self, d_model, d_ff=2048, dropout=0.1): super().__init__() self.linear_1 = nn.Linear(d_model, d_ff) self.dropout = nn.Dropout(dropout) self.linear_2 = nn.Linear(d_ff, d_model) def forward(self, x): x = self.dropout(F.relu(self.linear_1(x))) x = self.linear_2(x) return x class MultiHeadAttention(nn.Module): def __init__(self, heads, d_model, dropout=0.1): super().__init__() self.d_model = d_model self.d_k = d_model // heads self.h = heads self.q_linear = nn.Linear(d_model, d_model) self.v_linear = nn.Linear(d_model, d_model) self.k_linear = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) self.out = nn.Linear(d_model, d_model) def forward(self, q, k, v, mask=None): bs = q.size(0) k = self.k_linear(k).view(bs, -1, self.h, self.d_k) q = self.q_linear(q).view(bs, -1, self.h, self.d_k) v = self.v_linear(v).view(bs, -1, self.h, self.d_k) k = k.transpose(1, 2) q = q.transpose(1, 2) v = v.transpose(1, 2) scores = attention(q, k, v, self.d_k, mask, self.dropout) concat = scores.transpose(1, 2).contiguous().view(bs, -1, self.d_model) output = self.out(concat) return output class Norm(nn.Module): def __init__(self, d_model, eps=1e-06): super().__init__() self.size = d_model self.alpha = nn.Parameter(torch.ones(self.size)) self.bias = nn.Parameter(torch.zeros(self.size)) self.eps = eps def forward(self, x): norm = self.alpha * (x - x.mean(dim=-1, keepdim=True)) / (x.std(dim =-1, keepdim=True) + self.eps) + self.bias return norm class EncoderLayer(nn.Module): def __init__(self, d_model, heads, dropout=0.1): super().__init__() self.norm_1 = Norm(d_model) self.norm_2 = Norm(d_model) self.attn = MultiHeadAttention(heads, d_model, dropout=dropout) self.ff = FeedForward(d_model, dropout=dropout) self.dropout_1 = nn.Dropout(dropout) self.dropout_2 = nn.Dropout(dropout) def forward(self, x, mask): x2 = self.norm_1(x) x = x + self.dropout_1(self.attn(x2, x2, x2, mask)) x2 = self.norm_2(x) x = x + self.dropout_2(self.ff(x2)) return x def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'d_model': 4, '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 torch.nn.functional as F import torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor @triton.jit def triton_poi_fused_add_div_mean_mul_std_sub_0(in_ptr0, in_ptr1, in_ptr2, 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_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 = tmp0 * tmp11 tmp13 = tmp2 - tmp10 tmp14 = tmp13 * tmp13 tmp15 = tmp3 - tmp10 tmp16 = tmp15 * tmp15 tmp17 = tmp14 + tmp16 tmp18 = tmp5 - tmp10 tmp19 = tmp18 * tmp18 tmp20 = tmp17 + tmp19 tmp21 = tmp7 - tmp10 tmp22 = tmp21 * tmp21 tmp23 = tmp20 + tmp22 tmp24 = 3.0 tmp25 = tmp23 / tmp24 tmp26 = libdevice.sqrt(tmp25) tmp27 = 1e-06 tmp28 = tmp26 + tmp27 tmp29 = tmp12 / tmp28 tmp31 = tmp29 + tmp30 tl.store(out_ptr0 + x2, tmp31, xmask) @triton.jit def triton_poi_fused_clone_1(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_eq_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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.0 tmp2 = tmp0 == tmp1 tl.store(out_ptr0 + x0, tmp2, xmask) @triton.jit def triton_poi_fused__softmax_div_masked_fill_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 % 4 x2 = xindex // 16 x3 = xindex tmp0 = tl.load(in_ptr0 + (4 * x0 + 16 * x2), xmask, eviction_policy= 'evict_last').to(tl.int1) tmp1 = tl.load(in_ptr1 + 4 * x3, xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (1 + 4 * x0 + 16 * x2), xmask, eviction_policy ='evict_last').to(tl.int1) tmp7 = tl.load(in_ptr1 + (1 + 4 * x3), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (2 + 4 * x0 + 16 * x2), xmask, eviction_policy='evict_last').to(tl.int1) tmp12 = tl.load(in_ptr1 + (2 + 4 * x3), xmask, eviction_policy='evict_last' ) tmp16 = tl.load(in_ptr0 + (3 + 4 * x0 + 16 * x2), xmask, eviction_policy='evict_last').to(tl.int1) tmp17 = tl.load(in_ptr1 + (3 + 4 * x3), xmask, eviction_policy='evict_last' ) tmp2 = 1.0 tmp3 = tmp1 * tmp2 tmp4 = -1000000000.0 tmp5 = tl.where(tmp0, tmp4, tmp3) tmp8 = tmp7 * tmp2 tmp9 = tl.where(tmp6, tmp4, tmp8) tmp10 = triton_helpers.maximum(tmp5, tmp9) tmp13 = tmp12 * tmp2 tmp14 = tl.where(tmp11, tmp4, tmp13) tmp15 = triton_helpers.maximum(tmp10, tmp14) tmp18 = tmp17 * tmp2 tmp19 = tl.where(tmp16, tmp4, tmp18) tmp20 = triton_helpers.maximum(tmp15, tmp19) tmp21 = tmp5 - tmp20 tmp22 = tl_math.exp(tmp21) tmp23 = tmp9 - tmp20 tmp24 = tl_math.exp(tmp23) tmp25 = tmp22 + tmp24 tmp26 = tmp14 - tmp20 tmp27 = tl_math.exp(tmp26) tmp28 = tmp25 + tmp27 tmp29 = tmp19 - tmp20 tmp30 = tl_math.exp(tmp29) tmp31 = tmp28 + tmp30 tl.store(out_ptr0 + x3, tmp20, xmask) tl.store(out_ptr1 + x3, tmp31, xmask) @triton.jit def triton_poi_fused__softmax_div_masked_fill_4(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 // 64 x4 = xindex % 16 x5 = xindex x6 = xindex // 4 tmp0 = tl.load(in_ptr0 + (x4 + 16 * x3), xmask, eviction_policy= 'evict_last').to(tl.int1) tmp1 = tl.load(in_out_ptr0 + x5, xmask) tmp6 = tl.load(in_ptr1 + x6, xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr2 + x6, xmask, eviction_policy='evict_last') tmp2 = 1.0 tmp3 = tmp1 * tmp2 tmp4 = -1000000000.0 tmp5 = tl.where(tmp0, tmp4, tmp3) tmp7 = tmp5 - tmp6 tmp8 = tl_math.exp(tmp7) tmp10 = tmp8 / tmp9 tl.store(in_out_ptr0 + x5, tmp10, xmask) @triton.jit def triton_poi_fused_clone_5(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_std_6(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel 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 = 3.0 tmp29 = tmp27 / tmp28 tl.store(out_ptr0 + x0, tmp16, xmask) tl.store(in_out_ptr0 + x0, tmp29, xmask) @triton.jit def triton_poi_fused_add_div_mean_mul_std_sub_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 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') tmp7 = 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 tmp6 = tmp0 * tmp5 tmp8 = libdevice.sqrt(tmp7) tmp9 = 1e-06 tmp10 = tmp8 + tmp9 tmp11 = tmp6 / 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, 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,), (1,)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (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, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_11, (4, 4), (4, 1)) assert_size_stride(primals_12, (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,)) 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_div_mean_mul_std_sub_0[grid(64)](primals_1, primals_2, primals_3, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_1 del primals_3 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2) buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf3) buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32) triton_poi_fused_clone_1[grid(16, 4)](buf2, primals_7, buf4, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) del primals_7 buf5 = reinterpret_tensor(buf2, (4, 4, 1, 4), (16, 4, 4, 1), 0) del buf2 triton_poi_fused_clone_1[grid(16, 4)](buf1, primals_5, buf5, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 0), 0), reinterpret_tensor(buf5, (16, 1, 4), (4, 0, 1), 0), out=buf6) buf7 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.bool) triton_poi_fused_eq_2[grid(64)](primals_10, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_10 buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 64), 0) del buf1 buf9 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32) triton_poi_fused__softmax_div_masked_fill_3[grid(64)](buf7, buf6, buf8, buf9, 64, XBLOCK=64, num_warps=1, num_stages=1) buf10 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf6 triton_poi_fused__softmax_div_masked_fill_4[grid(256)](buf10, buf7, buf8, buf9, 256, XBLOCK=128, num_warps=4, num_stages=1) buf11 = reinterpret_tensor(buf9, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf9 triton_poi_fused_clone_1[grid(16, 4)](buf3, primals_9, buf11, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1) del primals_9 buf12 = reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 1), 0) del buf3 extern_kernels.bmm(reinterpret_tensor(buf10, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf11, (16, 4, 1), (4, 1, 0), 0), out=buf12) buf13 = reinterpret_tensor(buf8, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf8 triton_poi_fused_clone_5[grid(16, 4)](buf12, buf13, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf14 = reinterpret_tensor(buf12, (16, 4), (4, 1), 0) del buf12 extern_kernels.addmm(primals_12, reinterpret_tensor(buf13, (16, 4), (4, 1), 0), reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf14) del primals_12 buf15 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf16 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf17 = buf16 del buf16 triton_poi_fused_add_mean_std_6[grid(16)](buf17, primals_2, buf14, buf15, 16, XBLOCK=16, num_warps=1, num_stages=1) buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_div_mean_mul_std_sub_7[grid(64)](primals_13, primals_2, buf14, buf15, buf17, primals_14, buf18, 64, XBLOCK= 64, num_warps=1, num_stages=1) del buf15 del buf17 del primals_14 buf19 = empty_strided_cuda((16, 2048), (2048, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf18, (16, 4), (4, 1), 0), reinterpret_tensor(primals_15, (4, 2048), (1, 4), 0), out=buf19) buf20 = reinterpret_tensor(buf19, (4, 4, 2048), (8192, 2048, 1), 0) del buf19 buf23 = empty_strided_cuda((4, 4, 2048), (8192, 2048, 1), torch.bool) triton_poi_fused_relu_threshold_backward_8[grid(32768)](buf20, primals_16, buf23, 32768, XBLOCK=256, num_warps=4, num_stages=1) del primals_16 buf21 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf20, (16, 2048), (2048, 1), 0), reinterpret_tensor(primals_17, (2048, 4), (1, 2048), 0), out=buf21) buf22 = reinterpret_tensor(buf21, (4, 4, 4), (16, 4, 1), 0) del buf21 triton_poi_fused_add_9[grid(64)](buf22, primals_2, buf14, primals_18, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_18 return buf22, primals_2, primals_13, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf7, buf10, reinterpret_tensor(buf13, (16, 4), (4, 1), 0 ), buf14, reinterpret_tensor(buf18, (16, 4), (4, 1), 0 ), reinterpret_tensor(buf20, (16, 2048), (2048, 1), 0 ), primals_17, buf23, primals_15, primals_11, reinterpret_tensor(buf11, (16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf5, (16, 4, 1), (4, 1, 4), 0 ), primals_8, primals_6, primals_4 def attention(q, k, v, d_k, mask=None, dropout=None): scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: mask = mask.unsqueeze(1) scores = scores.masked_fill(mask == 0, -1000000000.0) scores = F.softmax(scores, dim=-1) if dropout is not None: scores = dropout(scores) output = torch.matmul(scores, v) return output class FeedForward(nn.Module): def __init__(self, d_model, d_ff=2048, dropout=0.1): super().__init__() self.linear_1 = nn.Linear(d_model, d_ff) self.dropout = nn.Dropout(dropout) self.linear_2 = nn.Linear(d_ff, d_model) def forward(self, x): x = self.dropout(F.relu(self.linear_1(x))) x = self.linear_2(x) return x class MultiHeadAttention(nn.Module): def __init__(self, heads, d_model, dropout=0.1): super().__init__() self.d_model = d_model self.d_k = d_model // heads self.h = heads self.q_linear = nn.Linear(d_model, d_model) self.v_linear = nn.Linear(d_model, d_model) self.k_linear = nn.Linear(d_model, d_model) self.dropout = nn.Dropout(dropout) self.out = nn.Linear(d_model, d_model) def forward(self, q, k, v, mask=None): bs = q.size(0) k = self.k_linear(k).view(bs, -1, self.h, self.d_k) q = self.q_linear(q).view(bs, -1, self.h, self.d_k) v = self.v_linear(v).view(bs, -1, self.h, self.d_k) k = k.transpose(1, 2) q = q.transpose(1, 2) v = v.transpose(1, 2) scores = attention(q, k, v, self.d_k, mask, self.dropout) concat = scores.transpose(1, 2).contiguous().view(bs, -1, self.d_model) output = self.out(concat) return output class Norm(nn.Module): def __init__(self, d_model, eps=1e-06): super().__init__() self.size = d_model self.alpha = nn.Parameter(torch.ones(self.size)) self.bias = nn.Parameter(torch.zeros(self.size)) self.eps = eps def forward(self, x): norm = self.alpha * (x - x.mean(dim=-1, keepdim=True)) / (x.std(dim =-1, keepdim=True) + self.eps) + self.bias return norm class EncoderLayerNew(nn.Module): def __init__(self, d_model, heads, dropout=0.1): super().__init__() self.norm_1 = Norm(d_model) self.norm_2 = Norm(d_model) self.attn = MultiHeadAttention(heads, d_model, dropout=dropout) self.ff = FeedForward(d_model, dropout=dropout) self.dropout_1 = nn.Dropout(dropout) self.dropout_2 = nn.Dropout(dropout) def forward(self, input_0, input_1): primals_1 = self.norm_1.alpha primals_3 = self.norm_1.bias primals_5 = self.norm_2.alpha primals_7 = self.norm_2.bias primals_4 = self.attn.q_linear.weight primals_9 = self.attn.q_linear.bias primals_6 = self.attn.v_linear.weight primals_12 = self.attn.v_linear.bias primals_8 = self.attn.k_linear.weight primals_13 = self.attn.k_linear.bias primals_11 = self.attn.out.weight primals_14 = self.attn.out.bias primals_15 = self.ff.linear_1.weight primals_16 = self.ff.linear_1.bias primals_17 = self.ff.linear_2.weight primals_18 = self.ff.linear_2.bias primals_2 = input_0 primals_10 = 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]) return output[0]
macg0406/Transformer
EncoderLayer
false
12,762
[ "Apache-2.0" ]
0
8c747a6e9f108c63ecc600bf14cde6827b438172
https://github.com/macg0406/Transformer/tree/8c747a6e9f108c63ecc600bf14cde6827b438172