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
|
|---|---|---|---|---|---|---|---|---|---|---|
DPLSTMCell
|
import math
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
from typing import Tuple
from typing import Optional
class LSTMLinear(nn.Linear):
"""
This function is the same as a nn.Linear layer, except that in the backward pass
the grad_samples get accumulated (instead of being concatenated as in the standard
nn.Linear)
"""
def __init__(self, in_features: 'int', out_features: 'int', bias:
'bool'=True):
super().__init__(in_features, out_features, bias)
class DPLSTMCell(nn.Module):
"""
Internal-only class. Implements *one* step of LSTM so that a LSTM layer can be seen as repeated
applications of this class.
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool'):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.ih = LSTMLinear(input_size, 4 * hidden_size, bias=self.bias)
self.hh = LSTMLinear(hidden_size, 4 * hidden_size, bias=self.bias)
self.reset_parameters()
def reset_parameters(self):
"""
Resets parameters by initializing them from an uniform distribution.
"""
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
nn.init.uniform_(weight, -stdv, stdv)
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length
"""
self.ih.max_batch_len = max_batch_length
self.hh.max_batch_len = max_batch_length
def forward(self, x: 'torch.Tensor', h_prev: 'torch.Tensor', c_prev:
'torch.Tensor', batch_size_t: 'Optional[int]'=None) ->Tuple[torch.
Tensor, torch.Tensor]:
if batch_size_t is None:
gates = self.ih(x) + self.hh(h_prev)
else:
gates = self.ih(x) + self.hh(h_prev[:batch_size_t, :])
i_t_input, f_t_input, g_t_input, o_t_input = torch.split(gates,
self.hidden_size, 1)
i_t = torch.sigmoid(i_t_input)
f_t = torch.sigmoid(f_t_input)
g_t = torch.tanh(g_t_input)
o_t = torch.sigmoid(o_t_input)
if batch_size_t is None:
c_t = f_t * c_prev + i_t * g_t
else:
c_t = f_t * c_prev[:batch_size_t, :] + i_t * g_t
h_t = o_t * torch.tanh(c_t)
return h_t, c_t
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4, 'bias': 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 math
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
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_sigmoid_sigmoid_backward_tanh_0(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2,
out_ptr3, out_ptr4, out_ptr5, 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 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp9 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp12 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask)
tmp20 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp25 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp28 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr4 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp10 = tmp8 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = tl.sigmoid(tmp14)
tmp18 = tmp16 + tmp17
tmp21 = tmp19 + tmp20
tmp22 = tmp18 + tmp21
tmp23 = libdevice.tanh(tmp22)
tmp26 = tmp24 + tmp25
tmp29 = tmp27 + tmp28
tmp30 = tmp26 + tmp29
tmp31 = tl.sigmoid(tmp30)
tmp33 = tmp31 * tmp32
tmp34 = tmp7 * tmp23
tmp35 = tmp33 + tmp34
tmp36 = 1.0
tmp37 = tmp36 - tmp31
tmp38 = tmp31 * tmp37
tmp39 = libdevice.tanh(tmp35)
tmp40 = tmp15 * tmp39
tl.store(out_ptr0 + x2, tmp7, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp23, xmask)
tl.store(out_ptr3 + x2, tmp35, xmask)
tl.store(out_ptr4 + x2, tmp38, xmask)
tl.store(out_ptr5 + x2, tmp40, 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, (16, 4), (4, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (16, 4), (4, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (4, 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((4, 16), (16, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 16),
(1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(primals_6, reinterpret_tensor(primals_4, (4, 16),
(1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_sigmoid_sigmoid_backward_tanh_0[grid(16)](buf0
, primals_2, buf1, primals_5, primals_7, buf2, buf4, buf3, buf5,
buf7, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf0
del buf1
del primals_2
del primals_5
return (buf6, buf5, primals_3, primals_6, primals_7, buf2, buf3, buf4,
buf5, buf7)
class LSTMLinear(nn.Linear):
"""
This function is the same as a nn.Linear layer, except that in the backward pass
the grad_samples get accumulated (instead of being concatenated as in the standard
nn.Linear)
"""
def __init__(self, in_features: 'int', out_features: 'int', bias:
'bool'=True):
super().__init__(in_features, out_features, bias)
class DPLSTMCellNew(nn.Module):
"""
Internal-only class. Implements *one* step of LSTM so that a LSTM layer can be seen as repeated
applications of this class.
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool'):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.ih = LSTMLinear(input_size, 4 * hidden_size, bias=self.bias)
self.hh = LSTMLinear(hidden_size, 4 * hidden_size, bias=self.bias)
self.reset_parameters()
def reset_parameters(self):
"""
Resets parameters by initializing them from an uniform distribution.
"""
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
nn.init.uniform_(weight, -stdv, stdv)
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length
"""
self.ih.max_batch_len = max_batch_length
self.hh.max_batch_len = max_batch_length
def forward(self, input_0, input_1, input_2):
primals_1 = self.ih.weight
primals_2 = self.ih.bias
primals_4 = self.hh.weight
primals_5 = self.hh.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], output[1]
|
EXAPPAI/opacus
|
DPLSTMCell
| false
| 2,195
|
[
"Apache-2.0"
] | 0
|
11e188a2f03a8a08be51fdf2367cc1387879312a
|
https://github.com/EXAPPAI/opacus/tree/11e188a2f03a8a08be51fdf2367cc1387879312a
|
MaxMarginRankingLoss
|
import torch
import numpy as np
import torch as th
import torch.nn.functional as F
class MaxMarginRankingLoss(th.nn.Module):
def __init__(self, margin=1.0, negative_weighting=False, batch_size=1,
n_pair=1, hard_negative_rate=0.5):
super(MaxMarginRankingLoss, self).__init__()
self.margin = margin
self.n_pair = n_pair
self.batch_size = batch_size
easy_negative_rate = 1 - hard_negative_rate
self.easy_negative_rate = easy_negative_rate
self.negative_weighting = negative_weighting
if n_pair > 1:
alpha = easy_negative_rate / ((batch_size - 1) * (1 -
easy_negative_rate))
mm_mask = (1 - alpha) * np.eye(self.batch_size) + alpha
mm_mask = np.kron(mm_mask, np.ones((n_pair, n_pair)))
mm_mask = th.tensor(mm_mask) * (batch_size * (1 -
easy_negative_rate))
self.mm_mask = mm_mask.float()
def forward(self, x):
d = th.diag(x)
max_margin = F.relu(self.margin + x - d.view(-1, 1)) + F.relu(self.
margin + x - d.view(1, -1))
if self.negative_weighting and self.n_pair > 1:
max_margin = max_margin * self.mm_mask
return max_margin.mean()
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import numpy as np
import torch as th
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_mean_relu_sub_0(in_out_ptr0, in_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)
r2 = rindex
r1 = rindex // 4
r0 = rindex % 4
tmp0 = tl.load(in_ptr0 + r2, None)
tmp3 = tl.load(in_ptr0 + 5 * r1, None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp5 = tl.full([1, 1], 0, tl.int32)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = tmp2 - tmp7
tmp9 = triton_helpers.maximum(tmp5, tmp8)
tmp10 = tmp6 + tmp9
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp13 = tl.sum(tmp11, 1)[:, None]
tmp14 = 16.0
tmp15 = tmp13 / tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_mean_relu_sub_0[grid(1)](buf1, arg0_1, 1, 16,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class MaxMarginRankingLossNew(th.nn.Module):
def __init__(self, margin=1.0, negative_weighting=False, batch_size=1,
n_pair=1, hard_negative_rate=0.5):
super(MaxMarginRankingLossNew, self).__init__()
self.margin = margin
self.n_pair = n_pair
self.batch_size = batch_size
easy_negative_rate = 1 - hard_negative_rate
self.easy_negative_rate = easy_negative_rate
self.negative_weighting = negative_weighting
if n_pair > 1:
alpha = easy_negative_rate / ((batch_size - 1) * (1 -
easy_negative_rate))
mm_mask = (1 - alpha) * np.eye(self.batch_size) + alpha
mm_mask = np.kron(mm_mask, np.ones((n_pair, n_pair)))
mm_mask = th.tensor(mm_mask) * (batch_size * (1 -
easy_negative_rate))
self.mm_mask = mm_mask.float()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
ErinZhang1998/howto100m-erin
|
MaxMarginRankingLoss
| false
| 2,196
|
[
"Apache-2.0"
] | 0
|
1152ea0fe328d20fcf2218a1d548644881632656
|
https://github.com/ErinZhang1998/howto100m-erin/tree/1152ea0fe328d20fcf2218a1d548644881632656
|
Encoder
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Scaled_Dot_Product_Attention(nn.Module):
"""Scaled Dot-Product Attention """
def __init__(self):
super(Scaled_Dot_Product_Attention, self).__init__()
def forward(self, Q, K, V, scale=None):
"""
Args:
Q: [batch_size, len_Q, dim_Q]
K: [batch_size, len_K, dim_K]
V: [batch_size, len_V, dim_V]
scale: 缩放因子 论文为根号dim_K
Return:
self-attention后的张量,以及attention张量
"""
attention = torch.matmul(Q, K.permute(0, 2, 1))
if scale:
attention = attention * scale
attention = F.softmax(attention, dim=-1)
context = torch.matmul(attention, V)
return context
class Multi_Head_Attention(nn.Module):
def __init__(self, dim_model, num_head, dropout=0.0):
super(Multi_Head_Attention, self).__init__()
self.num_head = num_head
assert dim_model % num_head == 0
self.dim_head = dim_model // self.num_head
self.fc_Q = nn.Linear(dim_model, num_head * self.dim_head)
self.fc_K = nn.Linear(dim_model, num_head * self.dim_head)
self.fc_V = nn.Linear(dim_model, num_head * self.dim_head)
self.attention = Scaled_Dot_Product_Attention()
self.fc = nn.Linear(num_head * self.dim_head, dim_model)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(dim_model)
def forward(self, x):
batch_size = x.size(0)
Q = self.fc_Q(x)
K = self.fc_K(x)
V = self.fc_V(x)
Q = Q.view(batch_size * self.num_head, -1, self.dim_head)
K = K.view(batch_size * self.num_head, -1, self.dim_head)
V = V.view(batch_size * self.num_head, -1, self.dim_head)
scale = K.size(-1) ** -0.5
context = self.attention(Q, K, V, scale)
context = context.view(batch_size, -1, self.dim_head * self.num_head)
out = self.fc(context)
out = self.dropout(out)
out = out + x
out = self.layer_norm(out)
return out
class Position_wise_Feed_Forward(nn.Module):
def __init__(self, dim_model, hidden, dropout=0.0):
super(Position_wise_Feed_Forward, self).__init__()
self.fc1 = nn.Linear(dim_model, hidden)
self.fc2 = nn.Linear(hidden, dim_model)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(dim_model)
def forward(self, x):
out = self.fc1(x)
out = F.relu(out)
out = self.fc2(out)
out = self.dropout(out)
out = out + x
out = self.layer_norm(out)
return out
class Encoder(nn.Module):
def __init__(self, dim_model, num_head, hidden, dropout):
super(Encoder, self).__init__()
self.attention = Multi_Head_Attention(dim_model, num_head, dropout)
self.feed_forward = Position_wise_Feed_Forward(dim_model, hidden,
dropout)
def forward(self, x):
out = self.attention(x)
out = self.feed_forward(out)
return out
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'dim_model': 4, 'num_head': 4, 'hidden': 4, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tmp2 - tmp2
tmp4 = tmp3 * tmp1
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp5 / tmp5
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), 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 * x1), 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 * x1), 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 + x2, tmp16, xmask)
tl.store(out_ptr1 + x2, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_2(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex // 16
x3 = xindex % 16
x4 = xindex // 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp1 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last')
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 + x5, tmp13, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_5(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_6(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17) = 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, (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,), (1,))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4, 4), (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,), (1,))
assert_size_stride(primals_17, (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)
extern_kernels.addmm(primals_5, primals_1, reinterpret_tensor(
primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, primals_1, reinterpret_tensor(
primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del primals_6
del primals_7
buf3 = empty_strided_cuda((16, 1, 1), (1, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 1, 1), (1, 1, 1),
0), reinterpret_tensor(buf1, (16, 1, 1), (1, 1, 1), 0), out=buf3)
buf4 = buf3
del buf3
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((16, 1, 1), (1, 1, 1), torch.float32)
extern_kernels.bmm(buf4, reinterpret_tensor(buf2, (16, 1, 1), (1, 1,
1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (4, 4), (4,
1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf6)
del primals_9
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_1[grid(16)](buf6, primals_1,
buf7, buf8, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_2[grid(64)](buf6, primals_1,
buf7, buf8, primals_10, primals_11, buf9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_11
buf10 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_12, (4, 4), (1, 4), 0), out=buf10)
buf11 = reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0)
del buf10
buf17 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(64)](buf11,
primals_13, buf17, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_13
buf12 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf11, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_14, (4, 4), (1, 4), 0), out=buf12)
buf13 = reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0)
del buf12
triton_poi_fused_add_4[grid(64)](buf13, primals_15, buf9, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_15
buf14 = buf8
del buf8
buf15 = buf7
del buf7
triton_poi_fused_native_layer_norm_5[grid(16)](buf13, buf14, buf15,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_6[grid(64)](buf13, buf14, buf15,
primals_16, primals_17, buf16, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf14
del buf15
del primals_17
return buf16, primals_1, primals_10, primals_16, buf4, reinterpret_tensor(
buf5, (4, 4), (4, 1), 0), buf6, reinterpret_tensor(buf9, (16, 4), (
4, 1), 0), reinterpret_tensor(buf11, (16, 4), (4, 1), 0
), buf13, primals_14, buf17, primals_12, primals_8, reinterpret_tensor(
buf2, (16, 1, 1), (1, 1, 1), 0), reinterpret_tensor(buf0, (16, 1, 1
), (1, 1, 1), 0), reinterpret_tensor(buf1, (16, 1, 1), (1, 1, 1), 0)
class Scaled_Dot_Product_Attention(nn.Module):
"""Scaled Dot-Product Attention """
def __init__(self):
super(Scaled_Dot_Product_Attention, self).__init__()
def forward(self, Q, K, V, scale=None):
"""
Args:
Q: [batch_size, len_Q, dim_Q]
K: [batch_size, len_K, dim_K]
V: [batch_size, len_V, dim_V]
scale: 缩放因子 论文为根号dim_K
Return:
self-attention后的张量,以及attention张量
"""
attention = torch.matmul(Q, K.permute(0, 2, 1))
if scale:
attention = attention * scale
attention = F.softmax(attention, dim=-1)
context = torch.matmul(attention, V)
return context
class Multi_Head_Attention(nn.Module):
def __init__(self, dim_model, num_head, dropout=0.0):
super(Multi_Head_Attention, self).__init__()
self.num_head = num_head
assert dim_model % num_head == 0
self.dim_head = dim_model // self.num_head
self.fc_Q = nn.Linear(dim_model, num_head * self.dim_head)
self.fc_K = nn.Linear(dim_model, num_head * self.dim_head)
self.fc_V = nn.Linear(dim_model, num_head * self.dim_head)
self.attention = Scaled_Dot_Product_Attention()
self.fc = nn.Linear(num_head * self.dim_head, dim_model)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(dim_model)
def forward(self, x):
batch_size = x.size(0)
Q = self.fc_Q(x)
K = self.fc_K(x)
V = self.fc_V(x)
Q = Q.view(batch_size * self.num_head, -1, self.dim_head)
K = K.view(batch_size * self.num_head, -1, self.dim_head)
V = V.view(batch_size * self.num_head, -1, self.dim_head)
scale = K.size(-1) ** -0.5
context = self.attention(Q, K, V, scale)
context = context.view(batch_size, -1, self.dim_head * self.num_head)
out = self.fc(context)
out = self.dropout(out)
out = out + x
out = self.layer_norm(out)
return out
class Position_wise_Feed_Forward(nn.Module):
def __init__(self, dim_model, hidden, dropout=0.0):
super(Position_wise_Feed_Forward, self).__init__()
self.fc1 = nn.Linear(dim_model, hidden)
self.fc2 = nn.Linear(hidden, dim_model)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(dim_model)
def forward(self, x):
out = self.fc1(x)
out = F.relu(out)
out = self.fc2(out)
out = self.dropout(out)
out = out + x
out = self.layer_norm(out)
return out
class EncoderNew(nn.Module):
def __init__(self, dim_model, num_head, hidden, dropout):
super(EncoderNew, self).__init__()
self.attention = Multi_Head_Attention(dim_model, num_head, dropout)
self.feed_forward = Position_wise_Feed_Forward(dim_model, hidden,
dropout)
def forward(self, input_0):
primals_1 = self.attention.fc_Q.weight
primals_3 = self.attention.fc_Q.bias
primals_2 = self.attention.fc_K.weight
primals_5 = self.attention.fc_K.bias
primals_4 = self.attention.fc_V.weight
primals_7 = self.attention.fc_V.bias
primals_6 = self.attention.fc.weight
primals_9 = self.attention.fc.bias
primals_10 = self.attention.layer_norm.weight
primals_11 = self.attention.layer_norm.bias
primals_8 = self.feed_forward.fc1.weight
primals_13 = self.feed_forward.fc1.bias
primals_12 = self.feed_forward.fc2.weight
primals_15 = self.feed_forward.fc2.bias
primals_16 = self.feed_forward.layer_norm.weight
primals_17 = self.feed_forward.layer_norm.bias
primals_14 = 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]
|
Ergtou/TextWord
|
Encoder
| false
| 2,197
|
[
"MIT"
] | 0
|
f05cc5a630fc8d05357b8a9bc0da3ec5cc255a30
|
https://github.com/Ergtou/TextWord/tree/f05cc5a630fc8d05357b8a9bc0da3ec5cc255a30
|
MLP
|
import torch
from torch import Tensor
from torch import nn
class MLP(nn.Module):
def __init__(self, dim, embed_dim):
super().__init__()
self.proj = nn.Linear(dim, embed_dim)
def forward(self, x: 'Tensor') ->Tensor:
x = x.flatten(2).transpose(1, 2)
x = self.proj(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'embed_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 import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_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
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, 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, 16, 4), (64, 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 = reinterpret_tensor(buf1, (4, 16, 4), (64, 4, 1), 0)
del buf1
triton_poi_fused_add_1[grid(256)](buf2, primals_3, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class MLPNew(nn.Module):
def __init__(self, dim, embed_dim):
super().__init__()
self.proj = nn.Linear(dim, embed_dim)
def forward(self, input_0):
primals_2 = self.proj.weight
primals_3 = self.proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
EmanuelNk/semantic-segmentation
|
MLP
| false
| 2,198
|
[
"MIT"
] | 0
|
20ff16da49691fb407724909d9c7e84b47e2fee0
|
https://github.com/EmanuelNk/semantic-segmentation/tree/20ff16da49691fb407724909d9c7e84b47e2fee0
|
Flatten
|
import torch
import torch.nn as nn
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
"""
Arguments:
x: a float tensor with shape [batch_size, c, h, w].
Returns:
a float tensor with shape [batch_size, c*h*w].
"""
x = x.transpose(3, 2).contiguous()
return x.view(x.size(0), -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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](arg0_1, buf0, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 64), (64, 1), 0),
class FlattenNew(nn.Module):
def __init__(self):
super(FlattenNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Escaton615/mtcnn-pytorch
|
Flatten
| false
| 2,199
|
[
"MIT"
] | 0
|
4a645c1bf8dca0b5410cc0454ee0a538ada2d241
|
https://github.com/Escaton615/mtcnn-pytorch/tree/4a645c1bf8dca0b5410cc0454ee0a538ada2d241
|
SigmoidAbsoluteRelativeErrorLoss
|
import torch
from torch import nn
class SigmoidAbsoluteRelativeErrorLoss(nn.Module):
def __init__(self, epsilon=0.0001):
super().__init__()
self.epsilon = epsilon
def forward(self, pred, target):
error = (pred - target) / (target + self.epsilon)
return torch.sigmoid(torch.abs(error))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_abs_add_div_sigmoid_sub_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 - tmp1
tmp3 = 0.0001
tmp4 = tmp1 + tmp3
tmp5 = tmp2 / tmp4
tmp6 = tl_math.abs(tmp5)
tmp7 = tl.sigmoid(tmp6)
tl.store(out_ptr0 + x0, tmp7, 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_add_div_sigmoid_sub_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 SigmoidAbsoluteRelativeErrorLossNew(nn.Module):
def __init__(self, epsilon=0.0001):
super().__init__()
self.epsilon = epsilon
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
ElectronicElephant/openpilot-reimplementation
|
SigmoidAbsoluteRelativeErrorLoss
| false
| 2,200
|
[
"MIT"
] | 0
|
063a9f5c6bbbf02c03dadc59e236e8f7c253a350
|
https://github.com/ElectronicElephant/openpilot-reimplementation/tree/063a9f5c6bbbf02c03dadc59e236e8f7c253a350
|
Position_wise_Feed_Forward
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Position_wise_Feed_Forward(nn.Module):
def __init__(self, dim_model, hidden, dropout=0.0):
super(Position_wise_Feed_Forward, self).__init__()
self.fc1 = nn.Linear(dim_model, hidden)
self.fc2 = nn.Linear(hidden, dim_model)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(dim_model)
def forward(self, x):
out = self.fc1(x)
out = F.relu(out)
out = self.fc2(out)
out = self.dropout(out)
out = out + x
out = self.layer_norm(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_model': 4, 'hidden': 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_add_native_layer_norm_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_2(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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, 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, 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,), (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
buf6 = 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, buf6, 256, XBLOCK=256, 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, 1), (16, 4, 1, 64), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_native_layer_norm_1[grid(64)](buf2, primals_3,
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)
triton_poi_fused_add_native_layer_norm_2[grid(256)](buf2, primals_3,
buf3, buf4, primals_6, primals_7, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf3
del buf4
del primals_7
return buf5, primals_3, primals_6, reinterpret_tensor(buf1, (64, 4), (4,
1), 0), buf2, primals_4, buf6
class Position_wise_Feed_ForwardNew(nn.Module):
def __init__(self, dim_model, hidden, dropout=0.0):
super(Position_wise_Feed_ForwardNew, self).__init__()
self.fc1 = nn.Linear(dim_model, hidden)
self.fc2 = nn.Linear(hidden, dim_model)
self.dropout = nn.Dropout(dropout)
self.layer_norm = nn.LayerNorm(dim_model)
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.layer_norm.weight
primals_7 = self.layer_norm.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
Ergtou/TextWord
|
Position_wise_Feed_Forward
| false
| 2,201
|
[
"MIT"
] | 0
|
f05cc5a630fc8d05357b8a9bc0da3ec5cc255a30
|
https://github.com/Ergtou/TextWord/tree/f05cc5a630fc8d05357b8a9bc0da3ec5cc255a30
|
TOP1_max
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class TOP1_max(nn.Module):
def __init__(self):
super(TOP1_max, self).__init__()
def forward(self, logit):
logit_softmax = F.softmax(logit, dim=1)
diff = -(logit.diag().view(-1, 1).expand_as(logit) - logit)
loss = torch.mean(logit_softmax * (torch.sigmoid(diff) + torch.
sigmoid(logit ** 2)))
return loss
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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 = 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_per_fused__softmax_add_mean_mul_neg_pow_sigmoid_sub_1(in_out_ptr0,
in_ptr0, in_ptr1, 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)
r2 = rindex
r1 = rindex // 4
tmp0 = tl.load(in_ptr0 + r2, None)
tmp1 = tl.load(in_ptr0 + 4 * r1, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * r1), None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * r1), None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * r1), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + 5 * r1, None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + r2, None)
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp11 = tmp9 - tmp10
tmp12 = -tmp11
tmp13 = tl.sigmoid(tmp12)
tmp14 = tmp10 * tmp10
tmp15 = tl.sigmoid(tmp14)
tmp16 = tmp13 + tmp15
tmp17 = tmp8 * tmp16
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
tmp20 = tl.sum(tmp18, 1)[:, None]
tmp21 = 16.0
tmp22 = tmp20 / tmp21
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp22, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__softmax_add_mean_mul_neg_pow_sigmoid_sub_1[grid(1)](
buf2, buf0, arg0_1, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class TOP1_maxNew(nn.Module):
def __init__(self):
super(TOP1_maxNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Ethan-Yys/GRU4REC-pytorch-master
|
TOP1_max
| false
| 2,202
|
[
"Apache-2.0"
] | 0
|
175ccb851f881d3506680c459491e76f50aa9898
|
https://github.com/Ethan-Yys/GRU4REC-pytorch-master/tree/175ccb851f881d3506680c459491e76f50aa9898
|
Sentence_Maxpool
|
import torch
import torch as th
import torch.nn.functional as F
import torch.nn as nn
class Sentence_Maxpool(nn.Module):
def __init__(self, word_dimension, output_dim, relu=True):
super(Sentence_Maxpool, self).__init__()
self.fc = nn.Linear(word_dimension, output_dim)
self.out_dim = output_dim
self.relu = relu
def forward(self, x):
x = self.fc(x)
if self.relu:
x = F.relu(x)
return th.max(x, dim=1)[0]
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'word_dimension': 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
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_relu_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
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 > tmp7
tmp18 = tmp4 == tmp7
tmp19 = tmp4 != tmp4
tmp20 = tmp7 != tmp7
tmp21 = tmp19 > tmp20
tmp22 = tmp17 | tmp21
tmp23 = tmp19 & tmp20
tmp24 = tmp18 | tmp23
tmp25 = tl.full([1], 0, tl.int64)
tmp26 = tl.full([1], 1, tl.int64)
tmp27 = tmp25 < tmp26
tmp28 = tmp24 & tmp27
tmp29 = tmp22 | tmp28
tmp30 = tl.where(tmp29, tmp4, tmp7)
tmp31 = tl.where(tmp29, tmp25, tmp26)
tmp32 = tmp30 > tmp11
tmp33 = tmp30 == tmp11
tmp34 = tmp30 != tmp30
tmp35 = tmp11 != tmp11
tmp36 = tmp34 > tmp35
tmp37 = tmp32 | tmp36
tmp38 = tmp34 & tmp35
tmp39 = tmp33 | tmp38
tmp40 = tl.full([1], 2, tl.int64)
tmp41 = tmp31 < tmp40
tmp42 = tmp39 & tmp41
tmp43 = tmp37 | tmp42
tmp44 = tl.where(tmp43, tmp30, tmp11)
tmp45 = tl.where(tmp43, tmp31, tmp40)
tmp46 = tmp44 > tmp15
tmp47 = tmp44 == tmp15
tmp48 = tmp44 != tmp44
tmp49 = tmp15 != tmp15
tmp50 = tmp48 > tmp49
tmp51 = tmp46 | tmp50
tmp52 = tmp48 & tmp49
tmp53 = tmp47 | tmp52
tmp54 = tl.full([1], 3, tl.int64)
tmp55 = tmp45 < tmp54
tmp56 = tmp53 & tmp55
tmp57 = tmp51 | tmp56
tl.where(tmp57, tmp44, tmp15)
tmp59 = tl.where(tmp57, tmp45, tmp54)
tl.store(out_ptr0 + x4, tmp16, xmask)
tl.store(out_ptr1 + x4, tmp59, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.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((4, 4, 4), (16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused_max_relu_0[grid(64)](buf0, primals_2, buf1, buf2,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256)](buf0,
primals_2, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4, 1, 4, 4), (16, 16, 4, 1), 0), buf3
class Sentence_MaxpoolNew(nn.Module):
def __init__(self, word_dimension, output_dim, relu=True):
super(Sentence_MaxpoolNew, self).__init__()
self.fc = nn.Linear(word_dimension, output_dim)
self.out_dim = output_dim
self.relu = relu
def forward(self, input_0):
primals_1 = self.fc.weight
primals_2 = self.fc.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ErinZhang1998/howto100m-erin
|
Sentence_Maxpool
| false
| 2,203
|
[
"Apache-2.0"
] | 0
|
1152ea0fe328d20fcf2218a1d548644881632656
|
https://github.com/ErinZhang1998/howto100m-erin/tree/1152ea0fe328d20fcf2218a1d548644881632656
|
Attention
|
import math
import torch
import torch.nn.functional as F
import torch.utils.data
def restricted_softmax(src, dim: 'int'=-1, margin: 'float'=0.0):
src_max = torch.clamp(src.max(dim=dim, keepdim=True)[0], min=0.0)
out = (src - src_max).exp()
out = out / (out.sum(dim=dim, keepdim=True) + (margin - src_max).exp())
return out
class Attention(torch.nn.Module):
def __init__(self, dropout=0):
super(Attention, self).__init__()
self.dropout = dropout
def forward(self, query, key, value):
return self.compute_attention(query, key, value)
def compute_attention(self, query, key, value):
assert query.dim() == key.dim() == value.dim() >= 2
assert query.size(-1) == key.size(-1)
assert key.size(-2) == value.size(-2)
score = torch.matmul(query, key.transpose(-2, -1))
score = score / math.sqrt(key.size(-1))
score = restricted_softmax(score, dim=-1)
score = F.dropout(score, p=self.dropout, training=self.training)
return torch.matmul(score, value)
def __repr__(self):
return '{}(dropout={})'.format(self.__class__.__name__, self.dropout)
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
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch.nn.functional as F
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clamp_div_exp_max_sub_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)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 0.5
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 = 0.0
tmp15 = triton_helpers.maximum(tmp13, tmp14)
tmp16 = tmp2 - tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x2, tmp17, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_exp_max_rsub_sum_1(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = 0.5
tmp9 = tmp7 * tmp8
tmp11 = tmp10 * tmp8
tmp12 = triton_helpers.maximum(tmp9, tmp11)
tmp14 = tmp13 * tmp8
tmp15 = triton_helpers.maximum(tmp12, tmp14)
tmp17 = tmp16 * tmp8
tmp18 = triton_helpers.maximum(tmp15, tmp17)
tmp19 = 0.0
tmp20 = triton_helpers.maximum(tmp18, tmp19)
tmp21 = tmp19 - tmp20
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp6 + tmp22
tl.store(out_ptr0 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_exp_max_rsub_sum_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
x1 = xindex // 4
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):
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((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg0_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(arg1_1, (16, 4, 4), (16, 1, 4), 0),
out=buf0)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_div_exp_max_sub_0[grid(256)](buf0, buf1, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_clamp_div_exp_max_rsub_sum_1[grid(64)](buf1,
buf0, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = buf1
del buf1
triton_poi_fused_add_clamp_div_exp_max_rsub_sum_2[grid(256)](buf3,
buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
buf4 = buf0
del buf0
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(arg2_1, (16, 4, 4), (16, 4, 1), 0), out=buf4
)
del arg2_1
del buf3
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0),
def restricted_softmax(src, dim: 'int'=-1, margin: 'float'=0.0):
src_max = torch.clamp(src.max(dim=dim, keepdim=True)[0], min=0.0)
out = (src - src_max).exp()
out = out / (out.sum(dim=dim, keepdim=True) + (margin - src_max).exp())
return out
class AttentionNew(torch.nn.Module):
def __init__(self, dropout=0):
super(AttentionNew, self).__init__()
self.dropout = dropout
def compute_attention(self, query, key, value):
assert query.dim() == key.dim() == value.dim() >= 2
assert query.size(-1) == key.size(-1)
assert key.size(-2) == value.size(-2)
score = torch.matmul(query, key.transpose(-2, -1))
score = score / math.sqrt(key.size(-1))
score = restricted_softmax(score, dim=-1)
score = F.dropout(score, p=self.dropout, training=self.training)
return torch.matmul(score, value)
def __repr__(self):
return '{}(dropout={})'.format(self.__class__.__name__, self.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]
|
EricAlcaide/pytorch_geometric
|
Attention
| false
| 2,204
|
[
"MIT"
] | 0
|
31cef566cfe22602459155fdf91e9b6ce398bfe7
|
https://github.com/EricAlcaide/pytorch_geometric/tree/31cef566cfe22602459155fdf91e9b6ce398bfe7
|
AdaptiveConcatPool2d
|
import torch
from typing import Type
from typing import Optional
import torch.nn as nn
class AdaptiveConcatPool2d(nn.Module):
"""Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`."""
def __init__(self, size: 'Optional[int]'=None):
"""Output will be 2*size or 2 if size is None"""
super().__init__()
size = size or 1
self.ap = nn.AdaptiveAvgPool2d(size)
self.mp = nn.AdaptiveMaxPool2d(size)
def forward(self, x: 'Type[torch.Tensor]') ->Type[torch.Tensor]:
return torch.cat([self.mp(x), self.ap(x)], 1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from typing import Optional
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_adaptive_max_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
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + 16 * x2, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp7 = tl.load(in_ptr0 + (4 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (5 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (6 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr0 + (7 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (8 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp17 = tl.load(in_ptr0 + (9 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (10 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (11 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (12 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr0 + (13 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (14 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr0 + (15 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp20 = triton_helpers.maximum(tmp19, tmp18)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = triton_helpers.maximum(tmp23, tmp22)
tmp26 = triton_helpers.maximum(tmp25, tmp24)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tl.store(out_ptr0 + (x0 + 8 * x1), tmp30, xmask)
@triton.jit
def triton_per_fused_mean_1(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
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.store(out_ptr1 + (x2 + 8 * x3), tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf3 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 1, 1), torch.float32)
buf0 = reinterpret_tensor(buf3, (4, 4, 1, 1), (8, 1, 1, 1), 0)
get_raw_stream(0)
triton_poi_fused_adaptive_max_pool2d_0[grid(16)](arg0_1, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf3, (4, 4, 1, 1), (8, 1, 1, 1), 4)
triton_per_fused_mean_1[grid(16)](arg0_1, buf2, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del arg0_1
return buf3,
class AdaptiveConcatPool2dNew(nn.Module):
"""Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`."""
def __init__(self, size: 'Optional[int]'=None):
"""Output will be 2*size or 2 if size is None"""
super().__init__()
size = size or 1
self.ap = nn.AdaptiveAvgPool2d(size)
self.mp = nn.AdaptiveMaxPool2d(size)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Erlemar/kekas
|
AdaptiveConcatPool2d
| false
| 2,205
|
[
"MIT"
] | 0
|
6fd8413f15390bf079bdb57a38a7094a5c53ab0f
|
https://github.com/Erlemar/kekas/tree/6fd8413f15390bf079bdb57a38a7094a5c53ab0f
|
CustomNet
|
import torch
import torch.nn as nn
class CustomNet(nn.Module):
"""
A network with a fully connected layer followed by a sigmoid layer. This is
used for testing customized operation handles.
"""
def __init__(self, input_dim: 'int', output_dim: 'int') ->None:
super(CustomNet, self).__init__()
self.conv = nn.Linear(input_dim, output_dim)
self.sigmoid = nn.Sigmoid()
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv(x)
x = self.sigmoid(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sigmoid_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.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_sigmoid_0[grid(256)](buf1, primals_2, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_2
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf1
class CustomNetNew(nn.Module):
"""
A network with a fully connected layer followed by a sigmoid layer. This is
used for testing customized operation handles.
"""
def __init__(self, input_dim: 'int', output_dim: 'int') ->None:
super(CustomNetNew, self).__init__()
self.conv = nn.Linear(input_dim, output_dim)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
DenXX/fvcore
|
CustomNet
| false
| 2,206
|
[
"Apache-2.0"
] | 0
|
4b91cf092f4f5d379b2c93398780a3b5755e7179
|
https://github.com/DenXX/fvcore/tree/4b91cf092f4f5d379b2c93398780a3b5755e7179
|
BPRLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class BPRLoss(nn.Module):
def __init__(self):
super(BPRLoss, self).__init__()
def forward(self, logit):
"""
Args:
logit (BxB): Variable that stores the logits for the items in the mini-batch
The first dimension corresponds to the batches, and the second
dimension corresponds to sampled number of items to evaluate
"""
diff = logit.diag().view(-1, 1).expand_as(logit) - logit
loss = -torch.mean(F.logsigmoid(diff))
return loss
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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_log_sigmoid_forward_mean_neg_sub_0(in_out_ptr0,
in_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)
r1 = rindex // 4
r2 = rindex
tmp0 = tl.load(in_ptr0 + 5 * r1, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + r2, None)
tmp2 = tmp0 - tmp1
tmp3 = 0.0
tmp4 = triton_helpers.minimum(tmp3, tmp2)
tmp5 = tl_math.abs(tmp2)
tmp6 = -tmp5
tmp7 = tl_math.exp(tmp6)
tmp8 = libdevice.log1p(tmp7)
tmp9 = tmp4 - tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.sum(tmp10, 1)[:, None]
tmp13 = 16.0
tmp14 = tmp12 / tmp13
tmp15 = -tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_log_sigmoid_forward_mean_neg_sub_0[grid(1)](buf1,
arg0_1, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class BPRLossNew(nn.Module):
def __init__(self):
super(BPRLossNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Ethan-Yys/GRU4REC-pytorch-master
|
BPRLoss
| false
| 2,207
|
[
"Apache-2.0"
] | 0
|
175ccb851f881d3506680c459491e76f50aa9898
|
https://github.com/Ethan-Yys/GRU4REC-pytorch-master/tree/175ccb851f881d3506680c459491e76f50aa9898
|
ResBlock
|
import torch
import torch.nn as nn
def get_same_padding(kernel_size, dilation):
kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1)
padding = (kernel_size - 1) // 2
return padding
class ResBlock(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1):
super(ResBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=kernel_size,
stride=stride, padding=get_same_padding(kernel_size, dilation),
dilation=dilation)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=kernel_size,
stride=1, padding=get_same_padding(kernel_size, dilation),
dilation=dilation)
self.relu = nn.ReLU(inplace=True)
self.res_translate = None
if not inplanes == planes or not stride == 1:
self.res_translate = nn.Conv2d(inplanes, planes, kernel_size=1,
stride=stride)
def forward(self, x):
residual = x
out = self.relu(self.conv1(x))
out = self.conv2(out)
if self.res_translate is not None:
residual = self.res_translate(residual)
out += residual
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_convolution_1(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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 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_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 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_3, 256,
XBLOCK=128, 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, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_add_convolution_1[grid(256)](buf3, primals_5,
primals_1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_2, primals_4, buf1
def get_same_padding(kernel_size, dilation):
kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1)
padding = (kernel_size - 1) // 2
return padding
class ResBlockNew(nn.Module):
def __init__(self, inplanes, planes, kernel_size=3, stride=1, dilation=1):
super(ResBlockNew, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=kernel_size,
stride=stride, padding=get_same_padding(kernel_size, dilation),
dilation=dilation)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=kernel_size,
stride=1, padding=get_same_padding(kernel_size, dilation),
dilation=dilation)
self.relu = nn.ReLU(inplace=True)
self.res_translate = None
if not inplanes == planes or not stride == 1:
self.res_translate = nn.Conv2d(inplanes, planes, kernel_size=1,
stride=stride)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Etienne66/CDVD-TSP
|
ResBlock
| false
| 2,208
|
[
"MIT"
] | 0
|
fccde88ff75832286612262613808eef7b1c3255
|
https://github.com/Etienne66/CDVD-TSP/tree/fccde88ff75832286612262613808eef7b1c3255
|
Copy
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.nn.init
class Copy(nn.Module):
def __init__(self, hidden_size, copy_weight=1.0):
super().__init__()
self.Wcopy = nn.Linear(hidden_size, hidden_size)
self.copy_weight = copy_weight
def forward(self, enc_out_hs, dec_hs):
"""
get unnormalized copy score
:param enc_out_hs: [B, Tenc, H]
:param dec_hs: [B, Tdec, H] testing: Tdec=1
:return: raw_cp_score of each position, size [B, Tdec, Tenc]
"""
raw_cp_score = torch.tanh(self.Wcopy(enc_out_hs))
raw_cp_score = torch.einsum('beh,bdh->bde', raw_cp_score, dec_hs)
return raw_cp_score * self.copy_weight
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
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_tanh_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 = libdevice.tanh(tmp0)
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (16,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf1, reinterpret_tensor(primals_4, (4, 4, 4), (
16, 1, 4), 0), out=buf2)
del buf1
buf3 = reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0)
del buf2
triton_poi_fused_mul_1[grid(64)](buf3, 64, XBLOCK=64, num_warps=1,
num_stages=1)
return buf3, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf0, primals_4
class CopyNew(nn.Module):
def __init__(self, hidden_size, copy_weight=1.0):
super().__init__()
self.Wcopy = nn.Linear(hidden_size, hidden_size)
self.copy_weight = copy_weight
def forward(self, input_0, input_1):
primals_1 = self.Wcopy.weight
primals_2 = self.Wcopy.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
ChrisGeishauser/ConvLab-2
|
Copy
| false
| 2,209
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
BinaryNLLEntropy
|
import torch
import torch.nn.functional as F
import torch.utils.data
import torch.nn.init
from torch.nn.modules.loss import _Loss
class BinaryNLLEntropy(_Loss):
def __init__(self, size_average=True):
super(BinaryNLLEntropy, self).__init__()
self.size_average = size_average
def forward(self, net_output, label_output):
"""
:param net_output: batch_size x
:param labels:
:return:
"""
batch_size = net_output.size(0)
loss = F.binary_cross_entropy_with_logits(net_output, label_output,
size_average=self.size_average)
if self.size_average is False:
loss /= batch_size
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 libdevice, math as tl_math
import torch.utils.data
import torch.nn.init
from torch.nn.modules.loss import _Loss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_binary_cross_entropy_with_logits_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp2 * tmp3
tmp5 = 0.0
tmp6 = triton_helpers.minimum(tmp5, tmp3)
tmp7 = tl_math.abs(tmp3)
tmp8 = -tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = libdevice.log1p(tmp9)
tmp11 = tmp6 - tmp10
tmp12 = tmp4 - tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_with_logits_0[grid(1)](buf1,
arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class BinaryNLLEntropyNew(_Loss):
def __init__(self, size_average=True):
super(BinaryNLLEntropyNew, self).__init__()
self.size_average = size_average
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
ChrisGeishauser/ConvLab-2
|
BinaryNLLEntropy
| false
| 2,210
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
ClassHead
|
import torch
from itertools import product as product
import torch.nn as nn
class ClassHead(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(ClassHead, self).__init__()
self.num_anchors = num_anchors
self.conv1x1 = nn.Conv2d(inchannels, self.num_anchors * 2,
kernel_size=(1, 1), stride=1, padding=0)
def forward(self, x):
out = self.conv1x1(x)
out = out.permute(0, 2, 3, 1).contiguous()
return out.view(out.shape[0], -1, 2)
def get_inputs():
return [torch.rand([4, 512, 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 itertools import product as product
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 2097152 * y1), tmp0, None)
@triton.jit
def triton_poi_fused_clone_view_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)
x4 = xindex
x0 = xindex % 6
tmp0 = tl.load(in_out_ptr0 + x4, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x4, tmp2, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (6, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_2, (6,), (1,))
assert_size_stride(primals_3, (4, 512, 64, 64), (2097152, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768, 512
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 4096)](primals_3, buf0, 2048, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 6, 64, 64), (24576, 1, 384, 6))
buf2 = reinterpret_tensor(buf1, (4, 64, 64, 6), (24576, 384, 6, 1), 0)
del buf1
buf3 = reinterpret_tensor(buf2, (4, 12288, 2), (24576, 2, 1), 0)
del buf2
triton_poi_fused_clone_view_1[grid(98304)](buf3, primals_2, 98304,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
return buf3, primals_1, buf0
class ClassHeadNew(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(ClassHeadNew, self).__init__()
self.num_anchors = num_anchors
self.conv1x1 = nn.Conv2d(inchannels, self.num_anchors * 2,
kernel_size=(1, 1), stride=1, padding=0)
def forward(self, input_0):
primals_1 = self.conv1x1.weight
primals_2 = self.conv1x1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Danil328/Pytorch_Retinaface
|
ClassHead
| false
| 2,211
|
[
"MIT"
] | 0
|
048a1d68217b2a99fbf83e2537ecc7e281ed6bd6
|
https://github.com/Danil328/Pytorch_Retinaface/tree/048a1d68217b2a99fbf83e2537ecc7e281ed6bd6
|
SmallConvNet
|
import torch
import torch.nn as nn
from numpy import prod
class SmallConvNet(nn.Module):
"""
A network with three conv layers. This is used for testing convolution
layers for activation count.
"""
def __init__(self, input_dim: 'int') ->None:
super(SmallConvNet, self).__init__()
conv_dim1 = 8
conv_dim2 = 4
conv_dim3 = 2
self.conv1 = nn.Conv2d(input_dim, conv_dim1, 1, 1)
self.conv2 = nn.Conv2d(conv_dim1, conv_dim2, 1, 2)
self.conv3 = nn.Conv2d(conv_dim2, conv_dim3, 1, 2)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
def get_gt_activation(self, x: 'torch.Tensor') ->int:
count = 0
x = self.conv1(x)
count += prod(list(x.size()))
x = self.conv2(x)
count += prod(list(x.size()))
x = self.conv3(x)
count += prod(list(x.size()))
return count
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from numpy import prod
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 = 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
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 = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (8, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 8, 1, 1), (8, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_7, (2,), (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, 8, 4, 4), (128, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(512)](buf1, primals_2, 512,
XBLOCK=256, num_warps=4, 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, 4, 2, 2), (16, 4, 2, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(64)](buf3, primals_5, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 2, 1, 1), (2, 1, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(8)](buf5, primals_7, 8, XBLOCK=
8, num_warps=1, num_stages=1)
del primals_7
return buf5, primals_1, primals_3, primals_4, primals_6, buf1, buf3
class SmallConvNetNew(nn.Module):
"""
A network with three conv layers. This is used for testing convolution
layers for activation count.
"""
def __init__(self, input_dim: 'int') ->None:
super(SmallConvNetNew, self).__init__()
conv_dim1 = 8
conv_dim2 = 4
conv_dim3 = 2
self.conv1 = nn.Conv2d(input_dim, conv_dim1, 1, 1)
self.conv2 = nn.Conv2d(conv_dim1, conv_dim2, 1, 2)
self.conv3 = nn.Conv2d(conv_dim2, conv_dim3, 1, 2)
def get_gt_activation(self, x: 'torch.Tensor') ->int:
count = 0
x = self.conv1(x)
count += prod(list(x.size()))
x = self.conv2(x)
count += prod(list(x.size()))
x = self.conv3(x)
count += prod(list(x.size()))
return count
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
DenXX/fvcore
|
SmallConvNet
| false
| 2,212
|
[
"Apache-2.0"
] | 0
|
4b91cf092f4f5d379b2c93398780a3b5755e7179
|
https://github.com/DenXX/fvcore/tree/4b91cf092f4f5d379b2c93398780a3b5755e7179
|
DPSLTMAdapter
|
import math
import torch
from torch import Tensor
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
from typing import Union
from typing import List
from typing import Tuple
from typing import Optional
from torch.nn.utils.rnn import PackedSequence
from torch.nn.utils.rnn import pack_padded_sequence
from typing import Dict
from torch.nn.modules.module import _IncompatibleKeys
def _compute_last_states(h_n: 'List[torch.Tensor]', c_n:
'List[torch.Tensor]', seq_lengths: 'List[int]') ->Tuple[torch.Tensor,
torch.Tensor]:
"""
Given h and c values of all time steps, this function computes the h and c values for each sequence at their last timestep (this can vary across sequences with different sequence lengths).
Args:
h_n: A list of hidden state values across all timesteps.
c_n: A list of cell state values across all timesteps.
seq_lengths: the length parameter used in the torch.nn.utils.rnn.packed_padded_sequence function to create a PackedSequence. This can be computed using the _compute_seq_lengths function.
Returns:
h_last: Contains the last hidden state values for each of the sequences.
If the i'th sequence has a length of l_i, then h_last[i,:] contains the hidden state corresponding to the i'th sequence at timestep l_i.
c_last: The structure is the same as h_last, except that it contains the last cell state values for each of the sequences.
"""
max_batch_size = len(seq_lengths)
hidden_size = h_n[0].shape[-1]
h_last = torch.zeros(max_batch_size, hidden_size)
c_last = torch.zeros(max_batch_size, hidden_size)
for i, seq_len in enumerate(seq_lengths):
h_last[i, :] = h_n[seq_len - 1][i, :]
c_last[i, :] = c_n[seq_len - 1][i, :]
return h_last, c_last
def _compute_seq_lengths(batch_sizes: 'torch.Tensor') ->List[int]:
"""
Computes the sequence lengths (the length parameter used in the packed_padded_sequence function to create a PackedSequence).
Args:
batch_sizes: Contains the batch sizes as stored in a PackedSequence
Returns:
running_seq_lengths: the length parameter used in the torch.nn.utils.rnn.packed_padded_sequence function to create a PackedSequence.
It's a list of the same length as batch_sizes.
"""
max_batch_size = batch_sizes[0]
if len(batch_sizes) == 1:
return [1] * max_batch_size
running_seq = 0
running_seq_lengths = []
for i in range(1, len(batch_sizes)):
delta = batch_sizes[i - 1].item() - batch_sizes[i].item()
running_seq += 1
running_seq_lengths += delta * [running_seq]
running_seq += 1
running_seq_lengths += batch_sizes[-1].item() * [running_seq]
running_seq_lengths.reverse()
return running_seq_lengths
def _concat_sequence_directions(forward:
'Union[List[torch.Tensor], Tuple[torch.Tensor]]', reverse:
'Union[List[torch.Tensor], Tuple[torch.Tensor]]', dim: 'int') ->Tuple[torch
.Tensor]:
"""
Given two list/tuple of same length containing tensors, this function returns a concatenation along dimension d. So, output[i] : concatenation of forward[i] and reverse[i] along dimension dim.
forward[i] and reverse[i] should have the same shape. This function is used for concatenating the outputs of the forward and reverse layer of a bidirectional LSTM.
Args:
forward: list/tuple containing n tensors, representing the output of the forward layer.
reverse: list/tuple containing n tensors, representing the output of the backward layer.
dim: the dimension along which the sequence of tensors within forward and reverse will be concatenated.
Returns:
output: list/tuple containing n concatenated tensors.
"""
if len(forward) != len(reverse):
raise ValueError(
'The forward and reverse layer output sequences should have the same length'
)
seq_length = len(forward)
output = [0] * seq_length
for i in range(seq_length):
output[i] = torch.cat((forward[i], reverse[i]), dim=dim)
return output
def filter_out_old_keys(self, state_dict, prefix, local_metadata):
new_state_dict = {param_name: param_value for param_name, param_value in
state_dict.items() if param_name not in self.old_to_new}
return new_state_dict
class LSTMLinear(nn.Linear):
"""
This function is the same as a nn.Linear layer, except that in the backward pass
the grad_samples get accumulated (instead of being concatenated as in the standard
nn.Linear)
"""
def __init__(self, in_features: 'int', out_features: 'int', bias:
'bool'=True):
super().__init__(in_features, out_features, bias)
class DPLSTMCell(nn.Module):
"""
Internal-only class. Implements *one* step of LSTM so that a LSTM layer can be seen as repeated
applications of this class.
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool'):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.ih = LSTMLinear(input_size, 4 * hidden_size, bias=self.bias)
self.hh = LSTMLinear(hidden_size, 4 * hidden_size, bias=self.bias)
self.reset_parameters()
def reset_parameters(self):
"""
Resets parameters by initializing them from an uniform distribution.
"""
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
nn.init.uniform_(weight, -stdv, stdv)
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length
"""
self.ih.max_batch_len = max_batch_length
self.hh.max_batch_len = max_batch_length
def forward(self, x: 'torch.Tensor', h_prev: 'torch.Tensor', c_prev:
'torch.Tensor', batch_size_t: 'Optional[int]'=None) ->Tuple[torch.
Tensor, torch.Tensor]:
if batch_size_t is None:
gates = self.ih(x) + self.hh(h_prev)
else:
gates = self.ih(x) + self.hh(h_prev[:batch_size_t, :])
i_t_input, f_t_input, g_t_input, o_t_input = torch.split(gates,
self.hidden_size, 1)
i_t = torch.sigmoid(i_t_input)
f_t = torch.sigmoid(f_t_input)
g_t = torch.tanh(g_t_input)
o_t = torch.sigmoid(o_t_input)
if batch_size_t is None:
c_t = f_t * c_prev + i_t * g_t
else:
c_t = f_t * c_prev[:batch_size_t, :] + i_t * g_t
h_t = o_t * torch.tanh(c_t)
return h_t, c_t
class DPLSTMLayer(nn.Module):
"""
Implements *one* layer of LSTM in a way amenable to differential privacy.
We don't expect you to use this directly: use DPLSTM instead :)
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool',
dropout: 'float', reverse: 'bool'=False):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.dropout = dropout
self.reverse = reverse
self.cell = DPLSTMCell(input_size=input_size, hidden_size=
hidden_size, bias=bias)
self.dropout_layer = nn.Dropout(dropout) if dropout > 0 else None
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length. Useful for PackedSequences
"""
self.cell.set_max_batch_length(max_batch_length)
def forward(self, x: 'Union[torch.Tensor, Tuple]', state_init:
'Tuple[torch.Tensor, torch.Tensor]', batch_sizes:
'Optional[torch.Tensor]'=None) ->Tuple[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
"""
Implements the forward pass of the DPLSTMLayer when a sequence is given in input.
Args:
x: Input sequence to the DPLSTMCell of shape ``[T, B, D]``.
state_init: Initial state of the LSTMCell as a tuple ``(h_0, c_0)``
where ``h_0`` is the initial hidden state and ``c_0`` is the
initial cell state of the DPLSTMCell
batch_sizes: Contains the batch sizes as stored in PackedSequence
Returns:
``output, (h_n, c_n)`` where, ``output`` is of shape ``[T, B, H]`` and is a
tensor containing the output features (``h_t``) from the last layer of the
DPLSTMCell for each timestep ``t``. ``h_n`` is of shape ``[B, H]`` and is a
tensor containing the hidden state for ``t = T``. ``c_n`` is of shape ``[B, H]``
tensor containing the cell state for ``t = T``.
"""
if batch_sizes is not None:
seq_length = batch_sizes.size(0)
if self.reverse:
x = tuple(reversed(x))
batch_sizes = batch_sizes.flip(0)
else:
seq_length, _batch_sz, _ = x.shape
if self.reverse:
x = x.flip(0)
x = torch.unbind(x, dim=0)
h_0, c_0 = state_init
h_n = [h_0]
c_n = [c_0]
batch_size_prev = h_0.shape[0]
for t in range(seq_length):
if batch_sizes is not None:
batch_size_t = batch_sizes[t].item()
delta = batch_size_t - batch_size_prev
if delta > 0:
h_cat = torch.cat((h_n[t], h_0[batch_size_prev:
batch_size_t, :]), 0)
c_cat = torch.cat((c_n[t], c_0[batch_size_prev:
batch_size_t, :]), 0)
h_next, c_next = self.cell(x[t], h_cat, c_cat, batch_size_t
)
else:
h_next, c_next = self.cell(x[t], h_n[t], c_n[t],
batch_size_t)
else:
h_next, c_next = self.cell(x[t], h_n[t], c_n[t])
if self.dropout:
h_next = self.dropout_layer(h_next)
h_n.append(h_next)
c_n.append(c_next)
batch_size_prev = h_next.shape[0]
if batch_sizes is None:
h_n = torch.stack(h_n[1:], dim=0)
return h_n.flip(0) if self.reverse else h_n, (h_n[-1], c_n[-1])
else:
seq_lengths = _compute_seq_lengths(batch_sizes)
h_temp, c_temp = h_n[1:], c_n[1:]
h_last, c_last = _compute_last_states(h_temp, c_temp, seq_lengths)
if self.reverse:
h_temp = tuple(reversed(h_temp))
return h_temp, (h_last, c_last)
class BidirectionalDPLSTMLayer(nn.Module):
"""
Implements *one* layer of Bidirectional LSTM in a way amenable to differential privacy.
We don't expect you to use this directly: use DPLSTM instead :)
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool',
dropout: 'float'):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.dropout = dropout
self.forward_layer = DPLSTMLayer(input_size=input_size, hidden_size
=hidden_size, bias=bias, dropout=dropout, reverse=False)
self.reverse_layer = DPLSTMLayer(input_size=input_size, hidden_size
=hidden_size, bias=bias, dropout=dropout, reverse=True)
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length
"""
self.forward_layer.set_max_batch_length(max_batch_length)
self.reverse_layer.set_max_batch_length(max_batch_length)
def forward(self, x: 'torch.Tensor', state_init:
'Tuple[torch.Tensor, torch.Tensor]', batch_sizes:
'Optional[torch.Tensor]'=None) ->Tuple[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
"""
Implements the forward pass of the DPLSTM when a sequence is input.
Dimensions as follows:
- B: Batch size
- T: Sequence length
- D: LSTM input hidden size (eg from a word embedding)
- H: LSTM output hidden size
- P: number of directions (2 if bidirectional, else 1)
Args:
x: Input sequence to the DPLSTM of shape ``[T, B, D]``
state_init: Initial state of the LSTM as a tuple ``(h_0, c_0)``, where
``h_0`` of shape ``[P, B, H]`` contains the initial hidden state, and
``c_0`` of shape ``[P, B, H]`` contains the initial cell state. This
argument can be (and defaults to) None, in which case zero tensors
will be used.
Returns:
``output, (h_n, c_n)`` where, ``output`` is of shape ``[T, B, H * P]`` and is a
tensor containing the output features (``h_t``) from the last layer of the
DPLSTM for each timestep ``t``. ``h_n`` is of shape ``[P, B, H]`` and contains
the hidden state for ``t = T``. ``c_n`` is of shape ``[P, B, H]`` and contains
the cell state for ``t = T``.
"""
h0, c0 = state_init
h0_f, h0_r = h0.unbind(0)
c0_f, c0_r = c0.unbind(0)
out_f, (h_f, c_f) = self.forward_layer(x, (h0_f, c0_f), batch_sizes)
out_r, (h_r, c_r) = self.reverse_layer(x, (h0_r, c0_r), batch_sizes)
if batch_sizes is None:
out = torch.cat([out_f, out_r], dim=-1)
else:
out = _concat_sequence_directions(out_f, out_r, -1)
h = torch.stack([h_f, h_r], dim=0)
c = torch.stack([c_f, c_r], dim=0)
return out, (h, c)
class ParamRenamedModule(nn.Module):
"""
This class defines a nn.Module whose parameters are renamed. This is useful when you want to
reimplement a layer but make sure its state_dict and list of parameters are exactly the same
as another reference layer so that you can have a drop-in replacement that does not depend on
how your layer is actually implemented. In Opacus, this is used for DPLSTM, where our
implementation leverages submodules and requires alignment to the state_dict of nn.LSTM.
"""
def __init__(self, rename_map: 'Dict[str, str]'):
"""
Initializes internal state. Subclass this instead of ``torch.nn.Module`` whenever you need
to rename your model's state.
Args:
rename_map: mapping from old name -> new name for each parameter you want renamed.
Note that this must be a 1:1 mapping!
"""
super().__init__()
self.old_to_new = rename_map
self.new_to_old = {v: k for k, v in rename_map.items()}
self._register_state_dict_hook(filter_out_old_keys)
def _register_renamed_parameters(self):
"""
Internal function. This function simply registers parameters under their new name. They will
automatically mask their duplicates coming from submodules. This trick works because
self.parameters() proceeds recursively from the top, going into submodules after processing
items at the current level, and will not return duplicates.
"""
for old_name, param in super().named_parameters():
if old_name in self.old_to_new:
new_name = self.old_to_new[old_name]
self.register_parameter(new_name, param)
def __setattr__(self, name: 'str', value: 'Union[Tensor, nn.Module]'
) ->None:
"""
Whenever you set an attribute, eg `self.linear`, this is called to actually register it in
any nn.Module. We rely on the masking trick explained in the docs for
``_register_renamed_parameters`` to make sure we replace things only once. If a new parameter
in the rename list is detected, we rename and mask it so next time this is called we will
no longer find it.
"""
super().__setattr__(name, value)
try:
self._register_renamed_parameters()
except AttributeError:
pass
def load_state_dict(self, state_dict: 'Dict[str, Tensor]', strict:
'bool'=True):
"""
Identical to ``torch.nn.Module.load_state_dict()`` but handles the renamed keys.
"""
missing_keys, unexpected_keys = super().load_state_dict(state_dict,
strict=False)
missing_keys = [k for k in missing_keys if k not in self.old_to_new]
if strict:
error_msgs = []
if len(unexpected_keys) > 0:
error_msgs.insert(0,
'Unexpected key(s) in state_dict: {}. '.format(', '.
join('"{}"'.format(k) for k in unexpected_keys)))
if len(missing_keys) > 0:
error_msgs.insert(0, 'Missing key(s) in state_dict: {}. '.
format(', '.join('"{}"'.format(k) for k in missing_keys)))
if len(error_msgs) > 0:
raise RuntimeError(
'Error(s) in loading state_dict for {}:\n\t{}'.format(
self.__class__.__name__, '\n\t'.join(error_msgs)))
return _IncompatibleKeys(missing_keys, unexpected_keys)
class DPLSTM(ParamRenamedModule):
"""
DP-friendly drop-in replacement of the ``torch.nn.LSTM`` module.
Its state_dict matches that of nn.LSTM exactly, so that after training it can be exported
and loaded by an nn.LSTM for inference.
Refer to nn.LSTM's documentation for all parameters and inputs.
"""
def __init__(self, input_size: 'int', hidden_size: 'int', num_layers:
'int'=1, bias: 'bool'=True, batch_first: 'bool'=False, dropout:
'float'=0, bidirectional: 'bool'=False):
rename_dict = self._make_rename_dict(num_layers, bias, bidirectional)
super().__init__(rename_dict)
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.bias = bias
self.batch_first = batch_first
self.dropout = dropout
self.bidirectional = bidirectional
self.num_directions = 2 if self.bidirectional else 1
LayerClass = BidirectionalDPLSTMLayer if bidirectional else DPLSTMLayer
self.layers = nn.ModuleList([LayerClass(input_size=self.input_size if
i == 0 else self.hidden_size * self.num_directions, hidden_size
=self.hidden_size, bias=self.bias, dropout=self.dropout if i <
self.num_layers - 1 else 0) for i in range(num_layers)])
def forward(self, x: 'Union[torch.Tensor, PackedSequence]', state_init:
'Optional[Tuple[torch.Tensor, torch.Tensor]]'=None) ->Tuple[torch.
Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""
Implements the forward pass of the DPLSTM when a sequence is input.
Dimensions as follows:
- B: Batch size
- T: Sequence length
- D: LSTM input hidden size (eg from a word embedding)
- H: LSTM output hidden size
- L: number of layers in the LSTM
- P: number of directions (2 if bidirectional, else 1)
Args:
x: Input sequence to the DPLSTM of shape ``[T, B, D]``. Or it can be a PackedSequence.
state_init: Initial state of the LSTM as a tuple ``(h_0, c_0)``, where:
- ``h_0`` of shape ``[L*P, B, H]`` contains the initial hidden state
- ``c_0`` of shape ``[L*P, B, H]`` contains the initial cell state
This argument can be (and defaults to) None, in which case zero tensors will be used.
Returns:
``output, (h_n, c_n)`` where, ``output`` is of shape ``[T, B, H * P]`` and is a
tensor containing the output features (``h_t``) from the last layer of the DPLSTM
for each timestep ``t``. ``h_n`` is of shape ``[L * P, B, H]`` and contains the
hidden state for ``t = T``. ``c_n`` is of shape ``[L * P, B, H]`` and contains
the cell state for ``t = T``.
"""
if isinstance(x, PackedSequence):
x, batch_sizes, sorted_indices, unsorted_indices = x
B = batch_sizes[0].item()
_, _D = x.shape
x = x.split(tuple(batch_sizes))
for layer in self.layers:
layer.set_max_batch_length(B)
else:
sorted_indices = None
unsorted_indices = None
batch_sizes = None
x = self._rearrange_batch_dim(x)
_T, B, _D = x.shape
L = self.num_layers
P = 2 if self.bidirectional else 1
H = self.hidden_size
h_0s, c_0s = state_init or (None, None)
if h_0s is None:
h_0s = torch.zeros(L, P, B, self.hidden_size, dtype=x[0].dtype,
device=x[0].device)
else:
h_0s = h_0s.reshape([L, P, B, H])
h_0s = self._permute_hidden(h_0s, sorted_indices, 2)
if c_0s is None:
c_0s = torch.zeros(L, P, B, self.hidden_size, dtype=x[0].dtype,
device=x[0].device)
else:
c_0s = c_0s.reshape([L, P, B, H])
c_0s = self._permute_hidden(c_0s, sorted_indices, 2)
hs: 'List[torch.Tensor]' = []
cs: 'List[torch.Tensor]' = []
for layer, h0, c0 in zip(self.layers, h_0s, c_0s):
if not self.bidirectional:
h0 = h0.squeeze(0)
c0 = c0.squeeze(0)
x, (h, c) = layer(x, (h0, c0), batch_sizes)
if not self.bidirectional:
h = h.unsqueeze(0)
c = c.unsqueeze(0)
hs.append(h)
cs.append(c)
hs = torch.cat(hs, dim=0)
cs = torch.cat(cs, dim=0)
if batch_sizes is not None:
seq_lengths = _compute_seq_lengths(batch_sizes)
packed_data = pack_padded_sequence(pad_sequence(x, batch_first=
False), seq_lengths, batch_first=True)[0]
out = PackedSequence(packed_data, batch_sizes, sorted_indices,
unsorted_indices)
else:
out = self._rearrange_batch_dim(x)
return out, (self._permute_hidden(hs, unsorted_indices), self.
_permute_hidden(cs, unsorted_indices))
def _permute_hidden(self, x: 'torch.Tensor', permutation:
'Optional[torch.Tensor]'=None, dim: 'int'=1) ->torch.Tensor:
if permutation is None:
return x
if dim == 1:
return x[:, permutation, :]
elif dim == 2:
return x[:, :, permutation, :]
def _rearrange_batch_dim(self, x: 'torch.Tensor') ->torch.Tensor:
if self.batch_first:
x = x.transpose(0, 1)
return x
def __repr__(self):
s = f'DPLSTM({self.input_size}, {self.hidden_size}, bias={self.bias}'
if self.batch_first:
s += f', batch_first={self.batch_first}'
if self.num_layers > 1:
s += f', num_layers={self.num_layers}'
if self.dropout:
s += f', dropout={self.dropout}'
if self.bidirectional:
s += f', bidirectional={self.bidirectional}'
return s
def _make_rename_dict(self, num_layers, bias, bidirectional):
"""
Programmatically constructs a dictionary old_name -> new_name to align with the param
names used in ``torch.nn.LSTM``.
"""
d = {}
components = ['weight'] + ['bias' if bias else []]
matrices = ['ih', 'hh']
for i in range(num_layers):
for c in components:
for m in matrices:
nn_name = f'{c}_{m}_l{i}'
if bidirectional:
d[f'layers.{i}.forward_layer.cell.{m}.{c}'] = nn_name
d[f'layers.{i}.reverse_layer.cell.{m}.{c}'
] = nn_name + '_reverse'
else:
d[f'layers.{i}.cell.{m}.{c}'] = nn_name
return d
class DPSLTMAdapter(nn.Module):
"""
Adapter for DPLSTM.
LSTM returns a tuple, but our testing tools need the model to return a single tensor in output.
We do this adaption here.
"""
def __init__(self, *args, **kwargs):
super().__init__()
self.dplstm = DPLSTM(*args, **kwargs)
def forward(self, x):
out, _rest = self.dplstm(x)
return out
def get_inputs():
return [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 math
from torch import Tensor
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
from typing import Union
from typing import List
from typing import Tuple
from typing import Optional
from torch.nn.utils.rnn import PackedSequence
from torch.nn.utils.rnn import pack_padded_sequence
from typing import Dict
from torch.nn.modules.module import _IncompatibleKeys
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_add_mul_sigmoid_sigmoid_backward_tanh_1(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2,
out_ptr3, out_ptr4, out_ptr5, 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 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp9 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp12 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask)
tmp20 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp25 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp28 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr4 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp10 = tmp8 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = tl.sigmoid(tmp14)
tmp18 = tmp16 + tmp17
tmp21 = tmp19 + tmp20
tmp22 = tmp18 + tmp21
tmp23 = libdevice.tanh(tmp22)
tmp26 = tmp24 + tmp25
tmp29 = tmp27 + tmp28
tmp30 = tmp26 + tmp29
tmp31 = tl.sigmoid(tmp30)
tmp33 = tmp31 * tmp32
tmp34 = tmp7 * tmp23
tmp35 = tmp33 + tmp34
tmp36 = 1.0
tmp37 = tmp36 - tmp31
tmp38 = tmp31 * tmp37
tmp39 = libdevice.tanh(tmp35)
tmp40 = tmp15 * tmp39
tl.store(out_ptr0 + x2, tmp7, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp23, xmask)
tl.store(out_ptr3 + x2, tmp35, xmask)
tl.store(out_ptr4 + x2, tmp38, xmask)
tl.store(out_ptr5 + x2, tmp40, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_tanh_2(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2, out_ptr3, out_ptr4,
out_ptr5, 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 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp9 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp12 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp20 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp25 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask)
tmp28 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr4 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp10 = tmp8 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = tl.sigmoid(tmp14)
tmp18 = tmp16 + tmp17
tmp21 = tmp19 + tmp20
tmp22 = tmp18 + tmp21
tmp23 = tl.sigmoid(tmp22)
tmp26 = tmp24 + tmp25
tmp29 = tmp27 + tmp28
tmp30 = tmp26 + tmp29
tmp31 = libdevice.tanh(tmp30)
tmp33 = tmp15 * tmp32
tmp34 = tmp7 * tmp31
tmp35 = tmp33 + tmp34
tmp36 = libdevice.tanh(tmp35)
tmp37 = tmp23 * tmp36
tl.store(out_ptr0 + x2, tmp7, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp23, xmask)
tl.store(out_ptr3 + x2, tmp31, xmask)
tl.store(out_ptr4 + x2, tmp35, xmask)
tl.store(out_ptr5 + x2, tmp37, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_tanh_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp9 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp12 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask)
tmp20 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr4 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp10 = tmp8 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = tl.sigmoid(tmp14)
tmp18 = tmp16 + tmp17
tmp21 = tmp19 + tmp20
tmp22 = tmp18 + tmp21
tmp23 = libdevice.tanh(tmp22)
tmp25 = tmp15 * tmp24
tmp26 = tmp7 * tmp23
tmp27 = tmp25 + tmp26
tmp28 = libdevice.tanh(tmp27)
tl.store(out_ptr0 + x2, tmp7, xmask)
tl.store(out_ptr1 + x2, tmp15, xmask)
tl.store(out_ptr2 + x2, tmp23, xmask)
tl.store(out_ptr3 + x2, tmp28, xmask)
@triton.jit
def triton_poi_fused_sigmoid_4(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 + (12 + x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tl.store(out_ptr0 + x2, tmp7, xmask)
@triton.jit
def triton_poi_fused_stack_5(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
x1 = xindex // 4
x0 = xindex % 4
x2 = 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), 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_ptr1 + (x0 + 4 * (-4 + x1)), 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_ptr2 + (x0 + 4 * (-8 + x1)), tmp14 & xmask, other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 16, tl.int64)
tmp19 = tl.load(in_ptr3 + (x0 + 4 * (-12 + x1)), tmp16 & xmask, other=0.0)
tmp20 = tl.load(in_ptr4 + (x0 + 4 * (-12 + x1)), tmp16 & xmask, other=0.0)
tmp21 = tmp19 * tmp20
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp16, tmp21, tmp22)
tmp24 = tl.where(tmp14, tmp15, tmp23)
tmp25 = tl.where(tmp9, tmp10, tmp24)
tmp26 = tl.where(tmp4, tmp5, tmp25)
tl.store(out_ptr0 + x2, tmp26, 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, (16, 4), (4, 1))
assert_size_stride(primals_3, (16,), (1,))
assert_size_stride(primals_4, (16, 4), (4, 1))
assert_size_stride(primals_5, (16,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 1, 4, 4), (16, 1, 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 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 16), (1, 4), 0), out=buf1)
buf2 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 16), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf32 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_sigmoid_backward_tanh_1[grid(16)](buf1
, primals_3, buf2, primals_5, buf0, buf3, buf5, buf4, buf6,
buf32, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf8 = buf2
del buf2
extern_kernels.mm(reinterpret_tensor(primals_1, (4, 4), (4, 1), 16),
reinterpret_tensor(primals_2, (4, 16), (1, 4), 0), out=buf8)
buf9 = buf1
del buf1
extern_kernels.mm(buf7, reinterpret_tensor(primals_4, (4, 16), (1,
4), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf13 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_tanh_2[grid(16)](buf8, primals_3,
buf9, primals_5, buf6, buf10, buf11, buf13, buf12, buf14, buf15,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf16 = buf9
del buf9
extern_kernels.mm(reinterpret_tensor(primals_1, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_2, (4, 16), (1, 4), 0), out=buf16)
buf17 = buf8
del buf8
extern_kernels.mm(buf15, reinterpret_tensor(primals_4, (4, 16), (1,
4), 0), out=buf17)
buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf19 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf21 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf20 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf22 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf23 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_tanh_2[grid(16)](buf16, primals_3,
buf17, primals_5, buf14, buf18, buf19, buf21, buf20, buf22,
buf23, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf24 = buf17
del buf17
extern_kernels.mm(reinterpret_tensor(primals_1, (4, 4), (4, 1), 48),
reinterpret_tensor(primals_2, (4, 16), (1, 4), 0), out=buf24)
del primals_2
buf25 = buf16
del buf16
extern_kernels.mm(buf23, reinterpret_tensor(primals_4, (4, 16), (1,
4), 0), out=buf25)
buf26 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf27 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf28 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf30 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_tanh_3[grid(16)](buf24, primals_3,
buf25, primals_5, buf22, buf26, buf27, buf28, buf30, 16, XBLOCK
=16, num_warps=1, num_stages=1)
buf29 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_sigmoid_4[grid(16)](buf24, primals_3, buf25,
primals_5, buf29, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf24
del primals_3
del primals_5
buf31 = reinterpret_tensor(buf25, (16, 4), (4, 1), 0)
del buf25
triton_poi_fused_stack_5[grid(64)](buf7, buf15, buf23, buf29, buf30,
buf31, 64, XBLOCK=64, num_warps=1, num_stages=1)
return (reinterpret_tensor(buf31, (4, 4, 4), (16, 4, 1), 0),
reinterpret_tensor(buf0, (4, 4), (4, 1), 0), reinterpret_tensor(
primals_1, (4, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4),
(4, 1), 16), reinterpret_tensor(primals_1, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_1, (4, 4), (4, 1), 48), buf3, buf4, buf5,
buf6, buf7, buf10, buf11, buf12, buf13, buf14, buf15, buf18, buf19,
buf20, buf21, buf22, buf23, buf26, buf27, buf28, buf29, buf30,
primals_4, buf32)
def _compute_last_states(h_n: 'List[torch.Tensor]', c_n:
'List[torch.Tensor]', seq_lengths: 'List[int]') ->Tuple[torch.Tensor,
torch.Tensor]:
"""
Given h and c values of all time steps, this function computes the h and c values for each sequence at their last timestep (this can vary across sequences with different sequence lengths).
Args:
h_n: A list of hidden state values across all timesteps.
c_n: A list of cell state values across all timesteps.
seq_lengths: the length parameter used in the torch.nn.utils.rnn.packed_padded_sequence function to create a PackedSequence. This can be computed using the _compute_seq_lengths function.
Returns:
h_last: Contains the last hidden state values for each of the sequences.
If the i'th sequence has a length of l_i, then h_last[i,:] contains the hidden state corresponding to the i'th sequence at timestep l_i.
c_last: The structure is the same as h_last, except that it contains the last cell state values for each of the sequences.
"""
max_batch_size = len(seq_lengths)
hidden_size = h_n[0].shape[-1]
h_last = torch.zeros(max_batch_size, hidden_size)
c_last = torch.zeros(max_batch_size, hidden_size)
for i, seq_len in enumerate(seq_lengths):
h_last[i, :] = h_n[seq_len - 1][i, :]
c_last[i, :] = c_n[seq_len - 1][i, :]
return h_last, c_last
def _compute_seq_lengths(batch_sizes: 'torch.Tensor') ->List[int]:
"""
Computes the sequence lengths (the length parameter used in the packed_padded_sequence function to create a PackedSequence).
Args:
batch_sizes: Contains the batch sizes as stored in a PackedSequence
Returns:
running_seq_lengths: the length parameter used in the torch.nn.utils.rnn.packed_padded_sequence function to create a PackedSequence.
It's a list of the same length as batch_sizes.
"""
max_batch_size = batch_sizes[0]
if len(batch_sizes) == 1:
return [1] * max_batch_size
running_seq = 0
running_seq_lengths = []
for i in range(1, len(batch_sizes)):
delta = batch_sizes[i - 1].item() - batch_sizes[i].item()
running_seq += 1
running_seq_lengths += delta * [running_seq]
running_seq += 1
running_seq_lengths += batch_sizes[-1].item() * [running_seq]
running_seq_lengths.reverse()
return running_seq_lengths
def _concat_sequence_directions(forward:
'Union[List[torch.Tensor], Tuple[torch.Tensor]]', reverse:
'Union[List[torch.Tensor], Tuple[torch.Tensor]]', dim: 'int') ->Tuple[torch
.Tensor]:
"""
Given two list/tuple of same length containing tensors, this function returns a concatenation along dimension d. So, output[i] : concatenation of forward[i] and reverse[i] along dimension dim.
forward[i] and reverse[i] should have the same shape. This function is used for concatenating the outputs of the forward and reverse layer of a bidirectional LSTM.
Args:
forward: list/tuple containing n tensors, representing the output of the forward layer.
reverse: list/tuple containing n tensors, representing the output of the backward layer.
dim: the dimension along which the sequence of tensors within forward and reverse will be concatenated.
Returns:
output: list/tuple containing n concatenated tensors.
"""
if len(forward) != len(reverse):
raise ValueError(
'The forward and reverse layer output sequences should have the same length'
)
seq_length = len(forward)
output = [0] * seq_length
for i in range(seq_length):
output[i] = torch.cat((forward[i], reverse[i]), dim=dim)
return output
def filter_out_old_keys(self, state_dict, prefix, local_metadata):
new_state_dict = {param_name: param_value for param_name, param_value in
state_dict.items() if param_name not in self.old_to_new}
return new_state_dict
class LSTMLinear(nn.Linear):
"""
This function is the same as a nn.Linear layer, except that in the backward pass
the grad_samples get accumulated (instead of being concatenated as in the standard
nn.Linear)
"""
def __init__(self, in_features: 'int', out_features: 'int', bias:
'bool'=True):
super().__init__(in_features, out_features, bias)
class DPLSTMCell(nn.Module):
"""
Internal-only class. Implements *one* step of LSTM so that a LSTM layer can be seen as repeated
applications of this class.
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool'):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.ih = LSTMLinear(input_size, 4 * hidden_size, bias=self.bias)
self.hh = LSTMLinear(hidden_size, 4 * hidden_size, bias=self.bias)
self.reset_parameters()
def reset_parameters(self):
"""
Resets parameters by initializing them from an uniform distribution.
"""
stdv = 1.0 / math.sqrt(self.hidden_size)
for weight in self.parameters():
nn.init.uniform_(weight, -stdv, stdv)
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length
"""
self.ih.max_batch_len = max_batch_length
self.hh.max_batch_len = max_batch_length
def forward(self, x: 'torch.Tensor', h_prev: 'torch.Tensor', c_prev:
'torch.Tensor', batch_size_t: 'Optional[int]'=None) ->Tuple[torch.
Tensor, torch.Tensor]:
if batch_size_t is None:
gates = self.ih(x) + self.hh(h_prev)
else:
gates = self.ih(x) + self.hh(h_prev[:batch_size_t, :])
i_t_input, f_t_input, g_t_input, o_t_input = torch.split(gates,
self.hidden_size, 1)
i_t = torch.sigmoid(i_t_input)
f_t = torch.sigmoid(f_t_input)
g_t = torch.tanh(g_t_input)
o_t = torch.sigmoid(o_t_input)
if batch_size_t is None:
c_t = f_t * c_prev + i_t * g_t
else:
c_t = f_t * c_prev[:batch_size_t, :] + i_t * g_t
h_t = o_t * torch.tanh(c_t)
return h_t, c_t
class DPLSTMLayer(nn.Module):
"""
Implements *one* layer of LSTM in a way amenable to differential privacy.
We don't expect you to use this directly: use DPLSTM instead :)
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool',
dropout: 'float', reverse: 'bool'=False):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.dropout = dropout
self.reverse = reverse
self.cell = DPLSTMCell(input_size=input_size, hidden_size=
hidden_size, bias=bias)
self.dropout_layer = nn.Dropout(dropout) if dropout > 0 else None
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length. Useful for PackedSequences
"""
self.cell.set_max_batch_length(max_batch_length)
def forward(self, x: 'Union[torch.Tensor, Tuple]', state_init:
'Tuple[torch.Tensor, torch.Tensor]', batch_sizes:
'Optional[torch.Tensor]'=None) ->Tuple[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
"""
Implements the forward pass of the DPLSTMLayer when a sequence is given in input.
Args:
x: Input sequence to the DPLSTMCell of shape ``[T, B, D]``.
state_init: Initial state of the LSTMCell as a tuple ``(h_0, c_0)``
where ``h_0`` is the initial hidden state and ``c_0`` is the
initial cell state of the DPLSTMCell
batch_sizes: Contains the batch sizes as stored in PackedSequence
Returns:
``output, (h_n, c_n)`` where, ``output`` is of shape ``[T, B, H]`` and is a
tensor containing the output features (``h_t``) from the last layer of the
DPLSTMCell for each timestep ``t``. ``h_n`` is of shape ``[B, H]`` and is a
tensor containing the hidden state for ``t = T``. ``c_n`` is of shape ``[B, H]``
tensor containing the cell state for ``t = T``.
"""
if batch_sizes is not None:
seq_length = batch_sizes.size(0)
if self.reverse:
x = tuple(reversed(x))
batch_sizes = batch_sizes.flip(0)
else:
seq_length, _batch_sz, _ = x.shape
if self.reverse:
x = x.flip(0)
x = torch.unbind(x, dim=0)
h_0, c_0 = state_init
h_n = [h_0]
c_n = [c_0]
batch_size_prev = h_0.shape[0]
for t in range(seq_length):
if batch_sizes is not None:
batch_size_t = batch_sizes[t].item()
delta = batch_size_t - batch_size_prev
if delta > 0:
h_cat = torch.cat((h_n[t], h_0[batch_size_prev:
batch_size_t, :]), 0)
c_cat = torch.cat((c_n[t], c_0[batch_size_prev:
batch_size_t, :]), 0)
h_next, c_next = self.cell(x[t], h_cat, c_cat, batch_size_t
)
else:
h_next, c_next = self.cell(x[t], h_n[t], c_n[t],
batch_size_t)
else:
h_next, c_next = self.cell(x[t], h_n[t], c_n[t])
if self.dropout:
h_next = self.dropout_layer(h_next)
h_n.append(h_next)
c_n.append(c_next)
batch_size_prev = h_next.shape[0]
if batch_sizes is None:
h_n = torch.stack(h_n[1:], dim=0)
return h_n.flip(0) if self.reverse else h_n, (h_n[-1], c_n[-1])
else:
seq_lengths = _compute_seq_lengths(batch_sizes)
h_temp, c_temp = h_n[1:], c_n[1:]
h_last, c_last = _compute_last_states(h_temp, c_temp, seq_lengths)
if self.reverse:
h_temp = tuple(reversed(h_temp))
return h_temp, (h_last, c_last)
class BidirectionalDPLSTMLayer(nn.Module):
"""
Implements *one* layer of Bidirectional LSTM in a way amenable to differential privacy.
We don't expect you to use this directly: use DPLSTM instead :)
"""
def __init__(self, input_size: 'int', hidden_size: 'int', bias: 'bool',
dropout: 'float'):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.dropout = dropout
self.forward_layer = DPLSTMLayer(input_size=input_size, hidden_size
=hidden_size, bias=bias, dropout=dropout, reverse=False)
self.reverse_layer = DPLSTMLayer(input_size=input_size, hidden_size
=hidden_size, bias=bias, dropout=dropout, reverse=True)
def set_max_batch_length(self, max_batch_length: 'int') ->None:
"""
Sets max batch length
"""
self.forward_layer.set_max_batch_length(max_batch_length)
self.reverse_layer.set_max_batch_length(max_batch_length)
def forward(self, x: 'torch.Tensor', state_init:
'Tuple[torch.Tensor, torch.Tensor]', batch_sizes:
'Optional[torch.Tensor]'=None) ->Tuple[torch.Tensor, Tuple[torch.
Tensor, torch.Tensor]]:
"""
Implements the forward pass of the DPLSTM when a sequence is input.
Dimensions as follows:
- B: Batch size
- T: Sequence length
- D: LSTM input hidden size (eg from a word embedding)
- H: LSTM output hidden size
- P: number of directions (2 if bidirectional, else 1)
Args:
x: Input sequence to the DPLSTM of shape ``[T, B, D]``
state_init: Initial state of the LSTM as a tuple ``(h_0, c_0)``, where
``h_0`` of shape ``[P, B, H]`` contains the initial hidden state, and
``c_0`` of shape ``[P, B, H]`` contains the initial cell state. This
argument can be (and defaults to) None, in which case zero tensors
will be used.
Returns:
``output, (h_n, c_n)`` where, ``output`` is of shape ``[T, B, H * P]`` and is a
tensor containing the output features (``h_t``) from the last layer of the
DPLSTM for each timestep ``t``. ``h_n`` is of shape ``[P, B, H]`` and contains
the hidden state for ``t = T``. ``c_n`` is of shape ``[P, B, H]`` and contains
the cell state for ``t = T``.
"""
h0, c0 = state_init
h0_f, h0_r = h0.unbind(0)
c0_f, c0_r = c0.unbind(0)
out_f, (h_f, c_f) = self.forward_layer(x, (h0_f, c0_f), batch_sizes)
out_r, (h_r, c_r) = self.reverse_layer(x, (h0_r, c0_r), batch_sizes)
if batch_sizes is None:
out = torch.cat([out_f, out_r], dim=-1)
else:
out = _concat_sequence_directions(out_f, out_r, -1)
h = torch.stack([h_f, h_r], dim=0)
c = torch.stack([c_f, c_r], dim=0)
return out, (h, c)
class ParamRenamedModule(nn.Module):
"""
This class defines a nn.Module whose parameters are renamed. This is useful when you want to
reimplement a layer but make sure its state_dict and list of parameters are exactly the same
as another reference layer so that you can have a drop-in replacement that does not depend on
how your layer is actually implemented. In Opacus, this is used for DPLSTM, where our
implementation leverages submodules and requires alignment to the state_dict of nn.LSTM.
"""
def __init__(self, rename_map: 'Dict[str, str]'):
"""
Initializes internal state. Subclass this instead of ``torch.nn.Module`` whenever you need
to rename your model's state.
Args:
rename_map: mapping from old name -> new name for each parameter you want renamed.
Note that this must be a 1:1 mapping!
"""
super().__init__()
self.old_to_new = rename_map
self.new_to_old = {v: k for k, v in rename_map.items()}
self._register_state_dict_hook(filter_out_old_keys)
def _register_renamed_parameters(self):
"""
Internal function. This function simply registers parameters under their new name. They will
automatically mask their duplicates coming from submodules. This trick works because
self.parameters() proceeds recursively from the top, going into submodules after processing
items at the current level, and will not return duplicates.
"""
for old_name, param in super().named_parameters():
if old_name in self.old_to_new:
new_name = self.old_to_new[old_name]
self.register_parameter(new_name, param)
def __setattr__(self, name: 'str', value: 'Union[Tensor, nn.Module]'
) ->None:
"""
Whenever you set an attribute, eg `self.linear`, this is called to actually register it in
any nn.Module. We rely on the masking trick explained in the docs for
``_register_renamed_parameters`` to make sure we replace things only once. If a new parameter
in the rename list is detected, we rename and mask it so next time this is called we will
no longer find it.
"""
super().__setattr__(name, value)
try:
self._register_renamed_parameters()
except AttributeError:
pass
def load_state_dict(self, state_dict: 'Dict[str, Tensor]', strict:
'bool'=True):
"""
Identical to ``torch.nn.Module.load_state_dict()`` but handles the renamed keys.
"""
missing_keys, unexpected_keys = super().load_state_dict(state_dict,
strict=False)
missing_keys = [k for k in missing_keys if k not in self.old_to_new]
if strict:
error_msgs = []
if len(unexpected_keys) > 0:
error_msgs.insert(0,
'Unexpected key(s) in state_dict: {}. '.format(', '.
join('"{}"'.format(k) for k in unexpected_keys)))
if len(missing_keys) > 0:
error_msgs.insert(0, 'Missing key(s) in state_dict: {}. '.
format(', '.join('"{}"'.format(k) for k in missing_keys)))
if len(error_msgs) > 0:
raise RuntimeError(
'Error(s) in loading state_dict for {}:\n\t{}'.format(
self.__class__.__name__, '\n\t'.join(error_msgs)))
return _IncompatibleKeys(missing_keys, unexpected_keys)
class DPLSTM(ParamRenamedModule):
"""
DP-friendly drop-in replacement of the ``torch.nn.LSTM`` module.
Its state_dict matches that of nn.LSTM exactly, so that after training it can be exported
and loaded by an nn.LSTM for inference.
Refer to nn.LSTM's documentation for all parameters and inputs.
"""
def __init__(self, input_size: 'int', hidden_size: 'int', num_layers:
'int'=1, bias: 'bool'=True, batch_first: 'bool'=False, dropout:
'float'=0, bidirectional: 'bool'=False):
rename_dict = self._make_rename_dict(num_layers, bias, bidirectional)
super().__init__(rename_dict)
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.bias = bias
self.batch_first = batch_first
self.dropout = dropout
self.bidirectional = bidirectional
self.num_directions = 2 if self.bidirectional else 1
LayerClass = BidirectionalDPLSTMLayer if bidirectional else DPLSTMLayer
self.layers = nn.ModuleList([LayerClass(input_size=self.input_size if
i == 0 else self.hidden_size * self.num_directions, hidden_size
=self.hidden_size, bias=self.bias, dropout=self.dropout if i <
self.num_layers - 1 else 0) for i in range(num_layers)])
def forward(self, x: 'Union[torch.Tensor, PackedSequence]', state_init:
'Optional[Tuple[torch.Tensor, torch.Tensor]]'=None) ->Tuple[torch.
Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""
Implements the forward pass of the DPLSTM when a sequence is input.
Dimensions as follows:
- B: Batch size
- T: Sequence length
- D: LSTM input hidden size (eg from a word embedding)
- H: LSTM output hidden size
- L: number of layers in the LSTM
- P: number of directions (2 if bidirectional, else 1)
Args:
x: Input sequence to the DPLSTM of shape ``[T, B, D]``. Or it can be a PackedSequence.
state_init: Initial state of the LSTM as a tuple ``(h_0, c_0)``, where:
- ``h_0`` of shape ``[L*P, B, H]`` contains the initial hidden state
- ``c_0`` of shape ``[L*P, B, H]`` contains the initial cell state
This argument can be (and defaults to) None, in which case zero tensors will be used.
Returns:
``output, (h_n, c_n)`` where, ``output`` is of shape ``[T, B, H * P]`` and is a
tensor containing the output features (``h_t``) from the last layer of the DPLSTM
for each timestep ``t``. ``h_n`` is of shape ``[L * P, B, H]`` and contains the
hidden state for ``t = T``. ``c_n`` is of shape ``[L * P, B, H]`` and contains
the cell state for ``t = T``.
"""
if isinstance(x, PackedSequence):
x, batch_sizes, sorted_indices, unsorted_indices = x
B = batch_sizes[0].item()
_, _D = x.shape
x = x.split(tuple(batch_sizes))
for layer in self.layers:
layer.set_max_batch_length(B)
else:
sorted_indices = None
unsorted_indices = None
batch_sizes = None
x = self._rearrange_batch_dim(x)
_T, B, _D = x.shape
L = self.num_layers
P = 2 if self.bidirectional else 1
H = self.hidden_size
h_0s, c_0s = state_init or (None, None)
if h_0s is None:
h_0s = torch.zeros(L, P, B, self.hidden_size, dtype=x[0].dtype,
device=x[0].device)
else:
h_0s = h_0s.reshape([L, P, B, H])
h_0s = self._permute_hidden(h_0s, sorted_indices, 2)
if c_0s is None:
c_0s = torch.zeros(L, P, B, self.hidden_size, dtype=x[0].dtype,
device=x[0].device)
else:
c_0s = c_0s.reshape([L, P, B, H])
c_0s = self._permute_hidden(c_0s, sorted_indices, 2)
hs: 'List[torch.Tensor]' = []
cs: 'List[torch.Tensor]' = []
for layer, h0, c0 in zip(self.layers, h_0s, c_0s):
if not self.bidirectional:
h0 = h0.squeeze(0)
c0 = c0.squeeze(0)
x, (h, c) = layer(x, (h0, c0), batch_sizes)
if not self.bidirectional:
h = h.unsqueeze(0)
c = c.unsqueeze(0)
hs.append(h)
cs.append(c)
hs = torch.cat(hs, dim=0)
cs = torch.cat(cs, dim=0)
if batch_sizes is not None:
seq_lengths = _compute_seq_lengths(batch_sizes)
packed_data = pack_padded_sequence(pad_sequence(x, batch_first=
False), seq_lengths, batch_first=True)[0]
out = PackedSequence(packed_data, batch_sizes, sorted_indices,
unsorted_indices)
else:
out = self._rearrange_batch_dim(x)
return out, (self._permute_hidden(hs, unsorted_indices), self.
_permute_hidden(cs, unsorted_indices))
def _permute_hidden(self, x: 'torch.Tensor', permutation:
'Optional[torch.Tensor]'=None, dim: 'int'=1) ->torch.Tensor:
if permutation is None:
return x
if dim == 1:
return x[:, permutation, :]
elif dim == 2:
return x[:, :, permutation, :]
def _rearrange_batch_dim(self, x: 'torch.Tensor') ->torch.Tensor:
if self.batch_first:
x = x.transpose(0, 1)
return x
def __repr__(self):
s = f'DPLSTM({self.input_size}, {self.hidden_size}, bias={self.bias}'
if self.batch_first:
s += f', batch_first={self.batch_first}'
if self.num_layers > 1:
s += f', num_layers={self.num_layers}'
if self.dropout:
s += f', dropout={self.dropout}'
if self.bidirectional:
s += f', bidirectional={self.bidirectional}'
return s
def _make_rename_dict(self, num_layers, bias, bidirectional):
"""
Programmatically constructs a dictionary old_name -> new_name to align with the param
names used in ``torch.nn.LSTM``.
"""
d = {}
components = ['weight'] + ['bias' if bias else []]
matrices = ['ih', 'hh']
for i in range(num_layers):
for c in components:
for m in matrices:
nn_name = f'{c}_{m}_l{i}'
if bidirectional:
d[f'layers.{i}.forward_layer.cell.{m}.{c}'] = nn_name
d[f'layers.{i}.reverse_layer.cell.{m}.{c}'
] = nn_name + '_reverse'
else:
d[f'layers.{i}.cell.{m}.{c}'] = nn_name
return d
class DPSLTMAdapterNew(nn.Module):
"""
Adapter for DPLSTM.
LSTM returns a tuple, but our testing tools need the model to return a single tensor in output.
We do this adaption here.
"""
def __init__(self, *args, **kwargs):
super().__init__()
self.dplstm = DPLSTM(*args, **kwargs)
def forward(self, input_0):
primals_2 = self.dplstm.weight_ih_l0
primals_3 = self.dplstm.bias_ih_l0
primals_4 = self.dplstm.weight_hh_l0
primals_5 = self.dplstm.bias_hh_l0
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
EXAPPAI/opacus
|
DPSLTMAdapter
| false
| 2,213
|
[
"Apache-2.0"
] | 0
|
11e188a2f03a8a08be51fdf2367cc1387879312a
|
https://github.com/EXAPPAI/opacus/tree/11e188a2f03a8a08be51fdf2367cc1387879312a
|
LandmarkHead
|
import torch
from itertools import product as product
import torch.nn as nn
class LandmarkHead(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(LandmarkHead, self).__init__()
self.conv1x1 = nn.Conv2d(inchannels, num_anchors * 10, kernel_size=
(1, 1), stride=1, padding=0)
def forward(self, x):
out = self.conv1x1(x)
out = out.permute(0, 2, 3, 1).contiguous()
return out.view(out.shape[0], -1, 10)
def get_inputs():
return [torch.rand([4, 512, 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 itertools import product as product
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 2097152 * y1), tmp0, None)
@triton.jit
def triton_poi_fused_clone_view_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)
x4 = xindex
x0 = xindex % 30
tmp0 = tl.load(in_out_ptr0 + x4, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x4, tmp2, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (30, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_2, (30,), (1,))
assert_size_stride(primals_3, (4, 512, 64, 64), (2097152, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768, 512
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 4096)](primals_3, buf0, 2048, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 30, 64, 64), (122880, 1, 1920, 30))
buf2 = reinterpret_tensor(buf1, (4, 64, 64, 30), (122880, 1920, 30,
1), 0)
del buf1
buf3 = reinterpret_tensor(buf2, (4, 12288, 10), (122880, 10, 1), 0)
del buf2
triton_poi_fused_clone_view_1[grid(491520)](buf3, primals_2, 491520,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
return buf3, primals_1, buf0
class LandmarkHeadNew(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(LandmarkHeadNew, self).__init__()
self.conv1x1 = nn.Conv2d(inchannels, num_anchors * 10, kernel_size=
(1, 1), stride=1, padding=0)
def forward(self, input_0):
primals_1 = self.conv1x1.weight
primals_2 = self.conv1x1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Danil328/Pytorch_Retinaface
|
LandmarkHead
| false
| 2,214
|
[
"MIT"
] | 0
|
048a1d68217b2a99fbf83e2537ecc7e281ed6bd6
|
https://github.com/Danil328/Pytorch_Retinaface/tree/048a1d68217b2a99fbf83e2537ecc7e281ed6bd6
|
Normalize
|
import torch
import torch.nn as nn
from itertools import product as product
class Normalize(nn.Module):
def __init__(self, n_channels, scale=1.0):
super(Normalize, self).__init__()
self.n_channels = n_channels
self.scale = scale
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.weight.data *= 0.0
self.weight.data += self.scale
self.register_parameter('bias', None)
def forward(self, x):
norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.eps
x = x / norm * self.weight.view(1, -1, 1, 1)
return x
def __repr__(self):
return 'Normalize(n_channels=%d, scale=%f)' % (self.n_channels,
self.scale)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from itertools import product as product
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_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-10
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tmp17 = tmp15 * tmp16
tl.store(out_ptr0 + x3, tmp17, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mul_pow_sqrt_sum_0[grid(256)](primals_1,
primals_2, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf0, primals_1
class NormalizeNew(nn.Module):
def __init__(self, n_channels, scale=1.0):
super(NormalizeNew, self).__init__()
self.n_channels = n_channels
self.scale = scale
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.weight.data *= 0.0
self.weight.data += self.scale
self.register_parameter('bias', None)
def __repr__(self):
return 'Normalize(n_channels=%d, scale=%f)' % (self.n_channels,
self.scale)
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
DongChengdongHangZhou/caffe-to-pytorch
|
Normalize
| false
| 2,215
|
[
"Apache-2.0"
] | 0
|
5e3104f3aa77d35bad5d2de235b067460c136fd5
|
https://github.com/DongChengdongHangZhou/caffe-to-pytorch/tree/5e3104f3aa77d35bad5d2de235b067460c136fd5
|
BboxHead
|
import torch
from itertools import product as product
import torch.nn as nn
class BboxHead(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(BboxHead, self).__init__()
self.conv1x1 = nn.Conv2d(inchannels, num_anchors * 4, kernel_size=(
1, 1), stride=1, padding=0)
def forward(self, x):
out = self.conv1x1(x)
out = out.permute(0, 2, 3, 1).contiguous()
return out.view(out.shape[0], -1, 4)
def get_inputs():
return [torch.rand([4, 512, 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 itertools import product as product
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 2097152 * y1), tmp0, None)
@triton.jit
def triton_poi_fused_clone_view_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)
x4 = xindex
x0 = xindex % 12
tmp0 = tl.load(in_out_ptr0 + x4, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x4, tmp2, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (12, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_2, (12,), (1,))
assert_size_stride(primals_3, (4, 512, 64, 64), (2097152, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512, 64, 64), (2097152, 1, 32768, 512
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2048, 4096)](primals_3, buf0, 2048, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 12, 64, 64), (49152, 1, 768, 12))
buf2 = reinterpret_tensor(buf1, (4, 64, 64, 12), (49152, 768, 12, 1), 0
)
del buf1
buf3 = reinterpret_tensor(buf2, (4, 12288, 4), (49152, 4, 1), 0)
del buf2
triton_poi_fused_clone_view_1[grid(196608)](buf3, primals_2, 196608,
XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
return buf3, primals_1, buf0
class BboxHeadNew(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super(BboxHeadNew, self).__init__()
self.conv1x1 = nn.Conv2d(inchannels, num_anchors * 4, kernel_size=(
1, 1), stride=1, padding=0)
def forward(self, input_0):
primals_1 = self.conv1x1.weight
primals_2 = self.conv1x1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Danil328/Pytorch_Retinaface
|
BboxHead
| false
| 2,216
|
[
"MIT"
] | 0
|
048a1d68217b2a99fbf83e2537ecc7e281ed6bd6
|
https://github.com/Danil328/Pytorch_Retinaface/tree/048a1d68217b2a99fbf83e2537ecc7e281ed6bd6
|
ConvNet
|
import torch
import torch.nn as nn
class ConvNet(nn.Module):
"""
A network with a single convolution layer. This is used for testing flop
count for convolution layers.
"""
def __init__(self, conv_dim: 'int', input_dim: 'int', output_dim: 'int',
kernel_size: 'int', spatial_dim: 'int', stride: 'int', padding:
'int', groups_num: 'int') ->None:
super(ConvNet, self).__init__()
if conv_dim == 1:
convLayer = nn.Conv1d
elif conv_dim == 2:
convLayer = nn.Conv2d
else:
convLayer = nn.Conv3d
self.conv = convLayer(input_dim, output_dim, kernel_size, stride,
padding, groups=groups_num)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'conv_dim': 4, 'input_dim': 4, 'output_dim': 4,
'kernel_size': 4, 'spatial_dim': 4, 'stride': 1, 'padding': 4,
'groups_num': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
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 = 2916
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 729
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4, 4), (256, 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(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(1, 1,
1), padding=(4, 4, 4), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 9, 9, 9), (2916, 729, 81, 9, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(2916)](buf1, primals_2, 2916,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 9, 9, 9), (729, 81, 9, 1), 0
), primals_1, reinterpret_tensor(primals_3, (1, 4, 4, 4, 4), (256,
64, 16, 4, 1), 0)
class ConvNetNew(nn.Module):
"""
A network with a single convolution layer. This is used for testing flop
count for convolution layers.
"""
def __init__(self, conv_dim: 'int', input_dim: 'int', output_dim: 'int',
kernel_size: 'int', spatial_dim: 'int', stride: 'int', padding:
'int', groups_num: 'int') ->None:
super(ConvNetNew, self).__init__()
if conv_dim == 1:
convLayer = nn.Conv1d
elif conv_dim == 2:
convLayer = nn.Conv2d
else:
convLayer = nn.Conv3d
self.conv = convLayer(input_dim, output_dim, kernel_size, stride,
padding, groups=groups_num)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
DenXX/fvcore
|
ConvNet
| false
| 2,217
|
[
"Apache-2.0"
] | 0
|
4b91cf092f4f5d379b2c93398780a3b5755e7179
|
https://github.com/DenXX/fvcore/tree/4b91cf092f4f5d379b2c93398780a3b5755e7179
|
TOP1Loss
|
import torch
import torch.nn as nn
class TOP1Loss(nn.Module):
def __init__(self):
super(TOP1Loss, self).__init__()
def forward(self, logit):
"""
Args:
logit (BxB): Variable that stores the logits for the items in the mini-batch
The first dimension corresponds to the batches, and the second
dimension corresponds to sampled number of items to evaluate
"""
diff = -(logit.diag().view(-1, 1).expand_as(logit) - logit)
loss = torch.sigmoid(diff).mean() + torch.sigmoid(logit ** 2).mean()
return loss
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mean_neg_pow_sigmoid_sub_0(in_out_ptr0, in_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)
r1 = rindex // 4
r2 = rindex
tmp0 = tl.load(in_ptr0 + 5 * r1, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + r2, None)
tmp2 = tmp0 - tmp1
tmp3 = -tmp2
tmp4 = tl.sigmoid(tmp3)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.sum(tmp5, 1)[:, None]
tmp8 = tmp1 * tmp1
tmp9 = tl.sigmoid(tmp8)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.sum(tmp10, 1)[:, None]
tmp13 = 16.0
tmp14 = tmp7 / tmp13
tmp15 = tmp12 / tmp13
tmp16 = tmp14 + tmp15
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp16, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_mean_neg_pow_sigmoid_sub_0[grid(1)](buf2,
arg0_1, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf2,
class TOP1LossNew(nn.Module):
def __init__(self):
super(TOP1LossNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Ethan-Yys/GRU4REC-pytorch-master
|
TOP1Loss
| false
| 2,218
|
[
"Apache-2.0"
] | 0
|
175ccb851f881d3506680c459491e76f50aa9898
|
https://github.com/Ethan-Yys/GRU4REC-pytorch-master/tree/175ccb851f881d3506680c459491e76f50aa9898
|
PNet
|
import torch
import torch.nn.functional as F
import torch.nn as nn
from collections import OrderedDict
class PNet(nn.Module):
def __init__(self):
super(PNet, self).__init__()
self.features = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3,
10, 3, 1)), ('prelu1', nn.PReLU(10)), ('pool1', nn.MaxPool2d(2,
2, ceil_mode=True)), ('conv2', nn.Conv2d(10, 16, 3, 1)), (
'prelu2', nn.PReLU(16)), ('conv3', nn.Conv2d(16, 32, 3, 1)), (
'prelu3', nn.PReLU(32))]))
self.conv4_1 = nn.Conv2d(32, 2, 1, 1)
self.conv4_2 = nn.Conv2d(32, 4, 1, 1)
def forward(self, x):
"""
Arguments:
x: a float tensor with shape [batch_size, 3, h, w].
Returns:
b: a float tensor with shape [batch_size, 4, h', w'].
a: a float tensor with shape [batch_size, 2, h', w'].
"""
x = self.features(x)
a = self.conv4_1(x)
b = self.conv4_2(x)
a = F.softmax(a)
return b, a
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from collections import OrderedDict
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__prelu_kernel_convolution_0(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 153760
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3844 % 10
x0 = xindex % 3844
x4 = xindex // 3844
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp6 = tmp5 * tmp2
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + (x0 + 3872 * x4), tmp7, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 38440
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 31
x1 = xindex // 31 % 31
x4 = xindex // 961
x3 = xindex // 9610
x5 = xindex % 9610
tmp0 = tl.load(in_ptr0 + (2 * x0 + 124 * x1 + 3872 * x4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 124 * x1 + 3872 * x4), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (62 + 2 * x0 + 124 * x1 + 3872 * x4), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (63 + 2 * x0 + 124 * x1 + 3872 * x4), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (x5 + 9632 * x3), tmp6, xmask)
tl.store(out_ptr1 + (x5 + 9728 * x3), tmp16, xmask)
@triton.jit
def triton_poi_fused__prelu_kernel_convolution_2(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 53824
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 841 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp6 = tmp5 * tmp2
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused__prelu_kernel_convolution_3(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 93312
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 729 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp6 = tmp5 * tmp2
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 11664
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 729 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_convolution_5(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 5832
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 729 % 2
x0 = xindex % 729
x2 = xindex // 1458
x4 = xindex % 1458
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (x0 + 1458 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr1 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp7 = tl.load(in_ptr0 + (729 + x0 + 1458 * x2), xmask, eviction_policy
='evict_last')
tmp8 = tl.load(in_ptr1 + 1)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp6 = tmp3 + tmp5
tmp10 = tmp7 + tmp9
tmp11 = triton_helpers.maximum(tmp6, tmp10)
tmp12 = tmp2 - tmp11
tmp13 = tl_math.exp(tmp12)
tl.store(out_ptr0 + (x4 + 1472 * x2), tmp13, xmask)
@triton.jit
def triton_poi_fused__softmax_6(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 5832
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 1458
x3 = xindex % 1458
x0 = xindex % 729
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 1472 * x2), xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 1472 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (729 + x0 + 1472 * x2), xmask, eviction_policy
='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 / tmp3
tl.store(out_ptr0 + x4, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14) = args
args.clear()
assert_size_stride(primals_1, (10, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (10,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (10,), (1,))
assert_size_stride(primals_5, (16, 10, 3, 3), (90, 9, 3, 1))
assert_size_stride(primals_6, (16,), (1,))
assert_size_stride(primals_7, (16,), (1,))
assert_size_stride(primals_8, (32, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (32,), (1,))
assert_size_stride(primals_11, (2, 32, 1, 1), (32, 1, 1, 1))
assert_size_stride(primals_12, (2,), (1,))
assert_size_stride(primals_13, (4, 32, 1, 1), (32, 1, 1, 1))
assert_size_stride(primals_14, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 10, 62, 62), (38440, 3844, 62, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 10, 62, 62), (38720, 3872, 62, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused__prelu_kernel_convolution_0[grid(153760)](buf1,
primals_2, primals_4, buf2, 153760, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_2
buf3 = empty_strided_cuda((4, 10, 31, 31), (9632, 961, 31, 1),
torch.float32)
buf4 = empty_strided_cuda((4, 10, 31, 31), (9728, 961, 31, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(38440)](buf2, buf3,
buf4, 38440, XBLOCK=512, num_warps=4, num_stages=1)
buf5 = extern_kernels.convolution(buf3, 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, 16, 29, 29), (13456, 841, 29, 1))
buf6 = buf5
del buf5
buf7 = empty_strided_cuda((4, 16, 29, 29), (13456, 841, 29, 1),
torch.float32)
triton_poi_fused__prelu_kernel_convolution_2[grid(53824)](buf6,
primals_6, primals_7, buf7, 53824, XBLOCK=512, num_warps=4,
num_stages=1)
del primals_6
buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 32, 27, 27), (23328, 729, 27, 1))
buf9 = buf8
del buf8
buf10 = empty_strided_cuda((4, 32, 27, 27), (23328, 729, 27, 1),
torch.float32)
triton_poi_fused__prelu_kernel_convolution_3[grid(93312)](buf9,
primals_9, primals_10, buf10, 93312, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_9
buf11 = extern_kernels.convolution(buf10, primals_11, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 2, 27, 27), (1458, 729, 27, 1))
buf12 = extern_kernels.convolution(buf10, primals_13, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 4, 27, 27), (2916, 729, 27, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_4[grid(11664)](buf13, primals_14,
11664, XBLOCK=256, num_warps=4, num_stages=1)
del primals_14
buf14 = empty_strided_cuda((4, 2, 27, 27), (1472, 729, 27, 1),
torch.float32)
triton_poi_fused__softmax_convolution_5[grid(5832)](buf11,
primals_12, buf14, 5832, XBLOCK=256, num_warps=4, num_stages=1)
del primals_12
buf15 = buf11
del buf11
triton_poi_fused__softmax_6[grid(5832)](buf14, buf15, 5832, XBLOCK=
128, num_warps=4, num_stages=1)
del buf14
return (buf13, buf15, primals_1, primals_3, primals_4, primals_5,
primals_7, primals_8, primals_10, primals_11, primals_13, buf1,
buf2, buf3, buf4, buf6, buf7, buf9, buf10, buf15)
class PNetNew(nn.Module):
def __init__(self):
super(PNetNew, self).__init__()
self.features = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3,
10, 3, 1)), ('prelu1', nn.PReLU(10)), ('pool1', nn.MaxPool2d(2,
2, ceil_mode=True)), ('conv2', nn.Conv2d(10, 16, 3, 1)), (
'prelu2', nn.PReLU(16)), ('conv3', nn.Conv2d(16, 32, 3, 1)), (
'prelu3', nn.PReLU(32))]))
self.conv4_1 = nn.Conv2d(32, 2, 1, 1)
self.conv4_2 = nn.Conv2d(32, 4, 1, 1)
def forward(self, input_0):
primals_1 = self.features.conv1.weight
primals_2 = self.features.conv1.bias
primals_4 = self.features.prelu1.weight
primals_5 = self.features.conv2.weight
primals_6 = self.features.conv2.bias
primals_7 = self.features.prelu2.weight
primals_8 = self.features.conv3.weight
primals_9 = self.features.conv3.bias
primals_10 = self.features.prelu3.weight
primals_11 = self.conv4_1.weight
primals_12 = self.conv4_1.bias
primals_13 = self.conv4_2.weight
primals_14 = self.conv4_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14])
return output[0], output[1]
|
Escaton615/mtcnn-pytorch
|
PNet
| false
| 2,219
|
[
"MIT"
] | 0
|
4a645c1bf8dca0b5410cc0454ee0a538ada2d241
|
https://github.com/Escaton615/mtcnn-pytorch/tree/4a645c1bf8dca0b5410cc0454ee0a538ada2d241
|
Conv2d_GN_ReLU
|
import torch
import torch.nn as nn
class Conv2d_GN_ReLU(nn.Module):
""" Implements a module that performs
conv2d + groupnorm + ReLU +
Assumes kernel size is odd
"""
def __init__(self, in_channels, out_channels, num_groups, ksize=3, stride=1
):
super(Conv2d_GN_ReLU, self).__init__()
padding = 0 if ksize < 2 else ksize // 2
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=ksize,
stride=stride, padding=padding, bias=False)
self.gn1 = nn.GroupNorm(num_groups, out_channels)
self.relu1 = nn.ReLU(inplace=True)
def forward(self, x):
out = self.conv1(x)
out = self.gn1(out)
out = self.relu1(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'num_groups': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_native_group_norm_relu_threshold_backward_0(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr2, out_ptr3, out_ptr4, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
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 = tmp0 - tmp10
tmp18 = 64.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.full([1, 1], 0, tl.int32)
tmp29 = triton_helpers.maximum(tmp28, tmp27)
tmp30 = 0.0
tmp31 = tmp29 <= tmp30
tl.store(out_ptr2 + (r1 + 64 * x0), tmp29, xmask)
tl.store(out_ptr3 + (r1 + 64 * x0), tmp31, xmask)
tl.store(out_ptr4 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,
1), padding=(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, 1, 1, 1), (1, 4, 4, 4), torch.float32)
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)
buf4 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
get_raw_stream(0)
triton_per_fused_native_group_norm_relu_threshold_backward_0[grid(4)](
buf0, primals_3, primals_4, buf1, buf5, buf6, buf4, 4, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del primals_4
return buf5, primals_1, primals_2, primals_3, buf0, reinterpret_tensor(buf1
, (4, 1), (1, 1), 0), reinterpret_tensor(buf4, (4, 1), (1, 1), 0), buf6
class Conv2d_GN_ReLUNew(nn.Module):
""" Implements a module that performs
conv2d + groupnorm + ReLU +
Assumes kernel size is odd
"""
def __init__(self, in_channels, out_channels, num_groups, ksize=3, stride=1
):
super(Conv2d_GN_ReLUNew, self).__init__()
padding = 0 if ksize < 2 else ksize // 2
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=ksize,
stride=stride, padding=padding, bias=False)
self.gn1 = nn.GroupNorm(num_groups, out_channels)
self.relu1 = nn.ReLU(inplace=True)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_3 = self.gn1.weight
primals_4 = self.gn1.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
FANG-Xiaolin/uois
|
Conv2d_GN_ReLU
| false
| 2,220
|
[
"MIT"
] | 0
|
7489e69d1513faf2f3f030a441abdd33ca22304c
|
https://github.com/FANG-Xiaolin/uois/tree/7489e69d1513faf2f3f030a441abdd33ca22304c
|
mlp
|
import torch
from torch import nn
class mlp(nn.Module):
def __init__(self, in_feature, **kwargs):
super().__init__()
self.in_feature = in_feature
self.relu = nn.ReLU()
self.linear1 = nn.Linear(in_feature, in_feature)
self.dropout1 = nn.Dropout(p=0.3)
self.linear2 = nn.Linear(in_feature, in_feature // 2)
self.dropout2 = nn.Dropout(p=0.1)
self.linear3 = nn.Linear(in_feature // 2, 1)
def forward(self, input):
x = self.linear1(input)
x = self.dropout1(x)
x = self.relu(x)
x = self.linear2(x)
x = self.dropout2(x)
x = self.relu(x)
x = self.linear3(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_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
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):
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)
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, (1, 2), (2, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
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=256, 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
buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 2), (
2, 1), 0), reinterpret_tensor(primals_6, (2, 1), (1, 2), 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, 4), (4, 1), 0), reinterpret_tensor(
buf3, (64, 2), (2, 1), 0), primals_6, buf6, primals_4, buf7
class mlpNew(nn.Module):
def __init__(self, in_feature, **kwargs):
super().__init__()
self.in_feature = in_feature
self.relu = nn.ReLU()
self.linear1 = nn.Linear(in_feature, in_feature)
self.dropout1 = nn.Dropout(p=0.3)
self.linear2 = nn.Linear(in_feature, in_feature // 2)
self.dropout2 = nn.Dropout(p=0.1)
self.linear3 = nn.Linear(in_feature // 2, 1)
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_6 = self.linear3.weight
primals_7 = self.linear3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
EuphoriaYan/sales_pred
|
mlp
| false
| 2,221
|
[
"MIT"
] | 0
|
cc39c32a3387285f3561aeeea7a133810069dc98
|
https://github.com/EuphoriaYan/sales_pred/tree/cc39c32a3387285f3561aeeea7a133810069dc98
|
ScaledDotProductAttention
|
import torch
import numpy as np
import torch.nn as nn
import torch.utils.data
import torch.nn.init
class ScaledDotProductAttention(nn.Module):
""" Scaled Dot-Product Attention """
def __init__(self, temperature, attn_dropout=0.1):
super(ScaledDotProductAttention, self).__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=2)
def forward(self, q, k, v, mask=None):
attn = torch.bmm(q, k.transpose(1, 2))
attn = attn / self.temperature
if mask is not None:
attn = attn.masked_fill(mask, -np.inf)
attn = self.softmax(attn)
attn = self.dropout(attn)
output = torch.bmm(attn, v)
return output, attn
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'temperature': 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
import torch.utils.data
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__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.25
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(arg1_1, reinterpret_tensor(arg0_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
class ScaledDotProductAttentionNew(nn.Module):
""" Scaled Dot-Product Attention """
def __init__(self, temperature, attn_dropout=0.1):
super(ScaledDotProductAttentionNew, self).__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=2)
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], output[1]
|
ChrisGeishauser/ConvLab-2
|
ScaledDotProductAttention
| false
| 2,222
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
CELossWeighted
|
import torch
import torch.nn as nn
class WeightedLoss(nn.Module):
def __init__(self):
super(WeightedLoss, self).__init__()
self.weighted = False
def generate_weight_mask(self, mask, to_ignore=None):
""" Generates a weight mask where pixel weights are inversely proportional to
how many pixels are in the class
@param mask: a [N x ...] torch.FloatTensor with values in {0, 1, 2, ..., K+1}, where K is number of objects. {0,1} are background/table.
@param to_ignore: a list of classes (integers) to ignore when creating mask
@return: a torch.FloatTensor that is same shape as mask.
"""
N = mask.shape[0]
if self.weighted:
weight_mask = torch.zeros_like(mask).float()
for i in range(N):
unique_object_labels = torch.unique(mask[i])
for obj in unique_object_labels:
if to_ignore is not None and obj in to_ignore:
continue
num_pixels = torch.sum(mask[i] == obj, dtype=torch.float)
weight_mask[i, mask[i] == obj] = 1 / num_pixels
else:
weight_mask = torch.ones_like(mask)
if to_ignore is not None:
for obj in to_ignore:
weight_mask[mask == obj] = 0
return weight_mask
class CELossWeighted(WeightedLoss):
""" Compute weighted CE loss with logits
"""
def __init__(self, weighted=False):
super(CELossWeighted, self).__init__()
self.CrossEntropyLoss = nn.CrossEntropyLoss(reduction='none')
self.weighted = weighted
def forward(self, x, target):
""" Compute weighted cross entropy
@param x: a [N x C x H x W] torch.FloatTensor of values
@param target: a [N x H x W] torch.LongTensor of values
"""
temp = self.CrossEntropyLoss(x, target)
weight_mask = self.generate_weight_mask(target)
loss = torch.sum(temp * weight_mask) / torch.sum(weight_mask)
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__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_mul_neg_sum_1(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp13 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp16 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp20 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp24 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp1 = tl_math.exp(tmp0)
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 + tmp3
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp4 + tmp6
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp0 - tmp11
tmp14 = tmp12 * tmp13
tmp15 = tmp2 - tmp11
tmp17 = tmp15 * tmp16
tmp18 = tmp14 + tmp17
tmp19 = tmp5 - tmp11
tmp21 = tmp19 * tmp20
tmp22 = tmp18 + tmp21
tmp23 = tmp8 - tmp11
tmp25 = tmp23 * tmp24
tmp26 = tmp22 + tmp25
tmp27 = -tmp26
tl.store(out_ptr0 + x2, tmp27, xmask)
@triton.jit
def triton_per_fused__log_softmax_div_mul_neg_ones_like_sum_2(in_out_ptr0,
in_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex % 64
tmp0 = tl.load(in_ptr0 + r0, None, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp6 = tl.broadcast_to(tmp1, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tmp5 / tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_mul_neg_sum_1[grid(64)](buf0, arg0_1,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del buf0
buf2 = empty_strided_cuda((), (), torch.float32)
buf4 = buf2
del buf2
triton_per_fused__log_softmax_div_mul_neg_ones_like_sum_2[grid(1)](buf4
, buf1, 1, 256, num_warps=2, num_stages=1)
del buf1
return buf4,
class WeightedLoss(nn.Module):
def __init__(self):
super(WeightedLoss, self).__init__()
self.weighted = False
def generate_weight_mask(self, mask, to_ignore=None):
""" Generates a weight mask where pixel weights are inversely proportional to
how many pixels are in the class
@param mask: a [N x ...] torch.FloatTensor with values in {0, 1, 2, ..., K+1}, where K is number of objects. {0,1} are background/table.
@param to_ignore: a list of classes (integers) to ignore when creating mask
@return: a torch.FloatTensor that is same shape as mask.
"""
N = mask.shape[0]
if self.weighted:
weight_mask = torch.zeros_like(mask).float()
for i in range(N):
unique_object_labels = torch.unique(mask[i])
for obj in unique_object_labels:
if to_ignore is not None and obj in to_ignore:
continue
num_pixels = torch.sum(mask[i] == obj, dtype=torch.float)
weight_mask[i, mask[i] == obj] = 1 / num_pixels
else:
weight_mask = torch.ones_like(mask)
if to_ignore is not None:
for obj in to_ignore:
weight_mask[mask == obj] = 0
return weight_mask
class CELossWeightedNew(WeightedLoss):
""" Compute weighted CE loss with logits
"""
def __init__(self, weighted=False):
super(CELossWeightedNew, self).__init__()
self.CrossEntropyLoss = nn.CrossEntropyLoss(reduction='none')
self.weighted = weighted
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
FANG-Xiaolin/uois
|
CELossWeighted
| false
| 2,223
|
[
"MIT"
] | 0
|
7489e69d1513faf2f3f030a441abdd33ca22304c
|
https://github.com/FANG-Xiaolin/uois/tree/7489e69d1513faf2f3f030a441abdd33ca22304c
|
SelfAttn
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torch.nn.init
import torch as th
class SelfAttn(nn.Module):
def __init__(self, hidden_size):
super(SelfAttn, self).__init__()
self.query = nn.Linear(hidden_size, 1)
def forward(self, keys, values, attn_mask=None):
"""
:param attn_inputs: batch_size x time_len x hidden_size
:param attn_mask: batch_size x time_len
:return: summary state
"""
alpha = F.softmax(self.query(keys), dim=1)
if attn_mask is not None:
alpha = alpha * attn_mask.unsqueeze(2)
alpha = alpha / th.sum(alpha, dim=1, keepdim=True)
summary = th.sum(values * alpha, dim=1)
return summary
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.data
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__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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask)
tmp1 = tl.load(in_ptr1 + (x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask)
tmp8 = tl.load(in_ptr1 + (8 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask)
tmp12 = tl.load(in_ptr1 + (12 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x4, tmp14, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_1
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0)
del buf2
triton_poi_fused__softmax_mul_sum_2[grid(64)](primals_4, buf3, buf4,
64, XBLOCK=64, num_warps=1, num_stages=1)
del buf3
return buf4, primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1
class SelfAttnNew(nn.Module):
def __init__(self, hidden_size):
super(SelfAttnNew, self).__init__()
self.query = nn.Linear(hidden_size, 1)
def forward(self, input_0, input_1):
primals_1 = self.query.weight
primals_2 = self.query.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
ChrisGeishauser/ConvLab-2
|
SelfAttn
| false
| 2,224
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
BCEWithLogitsLossWeighted
|
import torch
import torch.nn as nn
class WeightedLoss(nn.Module):
def __init__(self):
super(WeightedLoss, self).__init__()
self.weighted = False
def generate_weight_mask(self, mask, to_ignore=None):
""" Generates a weight mask where pixel weights are inversely proportional to
how many pixels are in the class
@param mask: a [N x ...] torch.FloatTensor with values in {0, 1, 2, ..., K+1}, where K is number of objects. {0,1} are background/table.
@param to_ignore: a list of classes (integers) to ignore when creating mask
@return: a torch.FloatTensor that is same shape as mask.
"""
N = mask.shape[0]
if self.weighted:
weight_mask = torch.zeros_like(mask).float()
for i in range(N):
unique_object_labels = torch.unique(mask[i])
for obj in unique_object_labels:
if to_ignore is not None and obj in to_ignore:
continue
num_pixels = torch.sum(mask[i] == obj, dtype=torch.float)
weight_mask[i, mask[i] == obj] = 1 / num_pixels
else:
weight_mask = torch.ones_like(mask)
if to_ignore is not None:
for obj in to_ignore:
weight_mask[mask == obj] = 0
return weight_mask
class BCEWithLogitsLossWeighted(WeightedLoss):
""" Compute weighted BCE loss with logits
"""
def __init__(self, weighted=False):
super(BCEWithLogitsLossWeighted, self).__init__()
self.BCEWithLogitsLoss = nn.BCEWithLogitsLoss(reduction='none')
self.weighted = weighted
def forward(self, x, target):
""" Compute masked cosine similarity loss
@param x: a [N x H x W] torch.FloatTensor of foreground logits
@param target: a [N x H x W] torch.FloatTensor of values in [0, 1]
"""
temp = self.BCEWithLogitsLoss(x, target)
weight_mask = self.generate_weight_mask(target)
loss = torch.sum(temp * weight_mask) / torch.sum(weight_mask)
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 libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_binary_cross_entropy_with_logits_div_mul_ones_like_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 = tmp1 - tmp0
tmp4 = tmp2 * tmp3
tmp5 = 0.0
tmp6 = triton_helpers.minimum(tmp5, tmp3)
tmp7 = tl_math.abs(tmp3)
tmp8 = -tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = libdevice.log1p(tmp9)
tmp11 = tmp6 - tmp10
tmp12 = tmp4 - tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = tl.broadcast_to(tmp1, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = tmp15 / tmp18
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp19, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_with_logits_div_mul_ones_like_sum_0[
grid(1)](buf2, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class WeightedLoss(nn.Module):
def __init__(self):
super(WeightedLoss, self).__init__()
self.weighted = False
def generate_weight_mask(self, mask, to_ignore=None):
""" Generates a weight mask where pixel weights are inversely proportional to
how many pixels are in the class
@param mask: a [N x ...] torch.FloatTensor with values in {0, 1, 2, ..., K+1}, where K is number of objects. {0,1} are background/table.
@param to_ignore: a list of classes (integers) to ignore when creating mask
@return: a torch.FloatTensor that is same shape as mask.
"""
N = mask.shape[0]
if self.weighted:
weight_mask = torch.zeros_like(mask).float()
for i in range(N):
unique_object_labels = torch.unique(mask[i])
for obj in unique_object_labels:
if to_ignore is not None and obj in to_ignore:
continue
num_pixels = torch.sum(mask[i] == obj, dtype=torch.float)
weight_mask[i, mask[i] == obj] = 1 / num_pixels
else:
weight_mask = torch.ones_like(mask)
if to_ignore is not None:
for obj in to_ignore:
weight_mask[mask == obj] = 0
return weight_mask
class BCEWithLogitsLossWeightedNew(WeightedLoss):
""" Compute weighted BCE loss with logits
"""
def __init__(self, weighted=False):
super(BCEWithLogitsLossWeightedNew, self).__init__()
self.BCEWithLogitsLoss = nn.BCEWithLogitsLoss(reduction='none')
self.weighted = weighted
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
FANG-Xiaolin/uois
|
BCEWithLogitsLossWeighted
| false
| 2,225
|
[
"MIT"
] | 0
|
7489e69d1513faf2f3f030a441abdd33ca22304c
|
https://github.com/FANG-Xiaolin/uois/tree/7489e69d1513faf2f3f030a441abdd33ca22304c
|
Attn
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torch.nn.init
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
import torch.utils.data
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_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]
|
ChrisGeishauser/ConvLab-2
|
Attn
| false
| 2,226
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
Scale
|
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from itertools import product as product
class Scale(nn.Module):
def __init__(self, channels):
super(Scale, self).__init__()
self.weight = Parameter(torch.Tensor(channels))
self.bias = Parameter(torch.Tensor(channels))
self.channels = channels
def forward(self, x):
nB = x.size(0)
nC = x.size(1)
nH = x.size(2)
nW = x.size(3)
x = x * self.weight.view(1, nC, 1, 1).expand(nB, nC, nH, nW
) + self.bias.view(1, nC, 1, 1).expand(nB, nC, nH, nW)
return x
def __repr__(self):
return 'Scale(channels=%d)' % self.channels
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from torch.nn.parameter import Parameter
from itertools import product as product
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(256)](primals_1, primals_2,
primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
del primals_3
return buf0, primals_1
class ScaleNew(nn.Module):
def __init__(self, channels):
super(ScaleNew, self).__init__()
self.weight = Parameter(torch.Tensor(channels))
self.bias = Parameter(torch.Tensor(channels))
self.channels = channels
def __repr__(self):
return 'Scale(channels=%d)' % self.channels
def forward(self, input_0):
primals_2 = self.weight
primals_3 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
DongChengdongHangZhou/caffe-to-pytorch
|
Scale
| false
| 2,227
|
[
"Apache-2.0"
] | 0
|
5e3104f3aa77d35bad5d2de235b067460c136fd5
|
https://github.com/DongChengdongHangZhou/caffe-to-pytorch/tree/5e3104f3aa77d35bad5d2de235b067460c136fd5
|
PositionwiseFeedForward
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torch.nn.init
class PositionwiseFeedForward(nn.Module):
""" A two-feed-forward-layer module """
def __init__(self, d_in, d_hid, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Conv1d(d_in, d_hid, 1)
self.w_2 = nn.Conv1d(d_hid, d_in, 1)
self.layer_norm = nn.LayerNorm(d_in)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
residual = x
output = x.transpose(1, 2)
output = self.w_2(F.relu(self.w_1(output)))
output = output.transpose(1, 2)
output = self.dropout(output)
output = self.layer_norm(output + residual)
return output
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d_in': 4, 'd_hid': 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
import torch.nn.init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_3(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 % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp4 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp8 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
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 + x2, tmp16, xmask)
tl.store(out_ptr1 + x2, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_4(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, 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 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + y3, ymask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + y3, ymask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x2, 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 + 4 * y3), tmp13, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 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,))
assert_size_stride(primals_6, (4,), (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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(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_relu_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4), (16, 4, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_2[grid(64)](buf4, primals_5, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf6 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_3[grid(16)](buf4, primals_1,
buf5, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf7 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_4[grid(16, 4)](buf4,
primals_1, buf5, buf6, primals_6, primals_7, buf7, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del buf5
del buf6
del primals_7
return buf7, primals_1, primals_2, primals_4, primals_6, buf2, buf4
class PositionwiseFeedForwardNew(nn.Module):
""" A two-feed-forward-layer module """
def __init__(self, d_in, d_hid, dropout=0.1):
super(PositionwiseFeedForwardNew, self).__init__()
self.w_1 = nn.Conv1d(d_in, d_hid, 1)
self.w_2 = nn.Conv1d(d_hid, d_in, 1)
self.layer_norm = nn.LayerNorm(d_in)
self.dropout = nn.Dropout(dropout)
def forward(self, input_0):
primals_2 = self.w_1.weight
primals_3 = self.w_1.bias
primals_4 = self.w_2.weight
primals_5 = self.w_2.bias
primals_6 = self.layer_norm.weight
primals_7 = self.layer_norm.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
ChrisGeishauser/ConvLab-2
|
PositionwiseFeedForward
| false
| 2,228
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
BPR_max
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class BPR_max(nn.Module):
def __init__(self):
super(BPR_max, self).__init__()
def forward(self, logit):
logit_softmax = F.softmax(logit, dim=1)
diff = logit.diag().view(-1, 1).expand_as(logit) - logit
loss = -torch.log(torch.mean(logit_softmax * torch.sigmoid(diff)))
return loss
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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 = 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_per_fused__softmax_log_mean_mul_neg_sigmoid_sub_1(in_out_ptr0,
in_ptr0, in_ptr1, 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)
r2 = rindex
r1 = rindex // 4
tmp0 = tl.load(in_ptr0 + r2, None)
tmp1 = tl.load(in_ptr0 + 4 * r1, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * r1), None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * r1), None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * r1), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + 5 * r1, None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + r2, None)
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp11 = tmp9 - tmp10
tmp12 = tl.sigmoid(tmp11)
tmp13 = tmp8 * tmp12
tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
tmp16 = tl.sum(tmp14, 1)[:, None]
tmp17 = 16.0
tmp18 = tmp16 / tmp17
tmp19 = tl_math.log(tmp18)
tmp20 = -tmp19
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp20, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__softmax_log_mean_mul_neg_sigmoid_sub_1[grid(1)](buf2,
buf0, arg0_1, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class BPR_maxNew(nn.Module):
def __init__(self):
super(BPR_maxNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Ethan-Yys/GRU4REC-pytorch-master
|
BPR_max
| false
| 2,229
|
[
"Apache-2.0"
] | 0
|
175ccb851f881d3506680c459491e76f50aa9898
|
https://github.com/Ethan-Yys/GRU4REC-pytorch-master/tree/175ccb851f881d3506680c459491e76f50aa9898
|
SilogLoss
|
import torch
import torch.nn as nn
class SilogLoss(nn.Module):
def __init__(self, ratio=10, ratio2=0.85):
super().__init__()
self.ratio = ratio
self.ratio2 = ratio2
def forward(self, pred, gt):
log_diff = torch.log(pred * self.ratio) - torch.log(gt * self.ratio)
silog1 = torch.mean(log_diff ** 2)
silog2 = self.ratio2 * log_diff.mean() ** 2
silog_loss = torch.sqrt(silog1 - silog2) * self.ratio
return silog_loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_log_mean_mul_pow_sqrt_sub_0(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp4 = tl.load(in_ptr1 + r0, None)
tmp1 = 10.0
tmp2 = tmp0 * tmp1
tmp3 = tl_math.log(tmp2)
tmp5 = tmp4 * tmp1
tmp6 = tl_math.log(tmp5)
tmp7 = tmp3 - tmp6
tmp8 = tmp7 * tmp7
tmp9 = tl.broadcast_to(tmp8, [RBLOCK])
tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0))
tmp12 = tl.broadcast_to(tmp7, [RBLOCK])
tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0))
tmp15 = 256.0
tmp16 = tmp11 / tmp15
tmp17 = tmp14 / tmp15
tmp18 = tmp17 * tmp17
tmp19 = 0.85
tmp20 = tmp18 * tmp19
tmp21 = tmp16 - tmp20
tmp22 = libdevice.sqrt(tmp21)
tmp23 = tmp22 * tmp1
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((), (), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_log_mean_mul_pow_sqrt_sub_0[grid(1)](buf2, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class SilogLossNew(nn.Module):
def __init__(self, ratio=10, ratio2=0.85):
super().__init__()
self.ratio = ratio
self.ratio2 = ratio2
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-
|
SilogLoss
| false
| 2,230
|
[
"MIT"
] | 0
|
13fac05601efed16ae8b29989aad487e04cd90a7
|
https://github.com/Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-/tree/13fac05601efed16ae8b29989aad487e04cd90a7
|
PatchEmbed
|
import torch
from itertools import chain as chain
import torch.utils.data
import torch.nn as nn
class PatchEmbed(nn.Module):
"""
PatchEmbed.
"""
def __init__(self, dim_in=3, dim_out=768, kernel=(1, 16, 16), stride=(1,
4, 4), padding=(1, 7, 7), conv_2d=False):
super().__init__()
if conv_2d:
conv = nn.Conv2d
else:
conv = nn.Conv3d
self.proj = conv(dim_in, dim_out, kernel_size=kernel, stride=stride,
padding=padding)
def forward(self, x):
x = self.proj(x)
return x.flatten(2).transpose(1, 2)
def get_inputs():
return [torch.rand([4, 3, 64, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from itertools import chain as chain
import torch.utils.data
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_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 // 16896 % 768
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (768, 3, 1, 16, 16), (768, 256, 256, 16, 1))
assert_size_stride(primals_2, (768,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64, 64), (786432, 262144, 4096,
64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
4, 4), padding=(1, 7, 7), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 768, 66, 16, 16), (12976128, 16896,
256, 16, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(51904512)](buf1, primals_2,
51904512, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 16896, 768), (12976128, 1, 16896), 0
), primals_1, primals_3
class PatchEmbedNew(nn.Module):
"""
PatchEmbed.
"""
def __init__(self, dim_in=3, dim_out=768, kernel=(1, 16, 16), stride=(1,
4, 4), padding=(1, 7, 7), conv_2d=False):
super().__init__()
if conv_2d:
conv = nn.Conv2d
else:
conv = nn.Conv3d
self.proj = conv(dim_in, dim_out, kernel_size=kernel, stride=stride,
padding=padding)
def forward(self, input_0):
primals_1 = self.proj.weight
primals_2 = self.proj.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Drill-D/SlowFast
|
PatchEmbed
| false
| 2,231
|
[
"Apache-2.0"
] | 0
|
d55ae1cf30a9415858a9bd5da983790a2b418653
|
https://github.com/Drill-D/SlowFast/tree/d55ae1cf30a9415858a9bd5da983790a2b418653
|
ThreeNet
|
import torch
import torch.nn as nn
class ThreeNet(nn.Module):
"""
A network with three layers. This is used for testing a network with more
than one operation. The network has a convolution layer followed by two
fully connected layers.
"""
def __init__(self, input_dim: 'int', conv_dim: 'int', linear_dim: 'int'
) ->None:
super(ThreeNet, self).__init__()
self.conv = nn.Conv2d(input_dim, conv_dim, 1, 1)
out_dim = 1
self.pool = nn.AdaptiveAvgPool2d((out_dim, out_dim))
self.linear1 = nn.Linear(conv_dim, linear_dim)
self.linear2 = nn.Linear(linear_dim, 1)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv(x)
x = self.pool(x)
x = torch.flatten(x, 1)
x = self.linear1(x)
x = self.linear2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'conv_dim': 4, 'linear_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_convolution_mean_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
tmp7 = 16.0
tmp8 = tmp6 / tmp7
tl.debug_barrier()
tl.store(in_out_ptr0 + x3, 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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_convolution_mean_0[grid(16)](buf2, buf0, primals_2,
16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del primals_2
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (4, 4), (4,
1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf3)
del primals_5
buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, buf3, reinterpret_tensor(primals_6,
(4, 1), (1, 4), 0), alpha=1, beta=1, out=buf5)
del primals_7
return buf5, primals_1, primals_3, reinterpret_tensor(buf2, (4, 4), (4,
1), 0), buf3, primals_6, primals_4
class ThreeNetNew(nn.Module):
"""
A network with three layers. This is used for testing a network with more
than one operation. The network has a convolution layer followed by two
fully connected layers.
"""
def __init__(self, input_dim: 'int', conv_dim: 'int', linear_dim: 'int'
) ->None:
super(ThreeNetNew, self).__init__()
self.conv = nn.Conv2d(input_dim, conv_dim, 1, 1)
out_dim = 1
self.pool = nn.AdaptiveAvgPool2d((out_dim, out_dim))
self.linear1 = nn.Linear(conv_dim, linear_dim)
self.linear2 = nn.Linear(linear_dim, 1)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_4 = self.linear1.weight
primals_5 = self.linear1.bias
primals_6 = self.linear2.weight
primals_7 = self.linear2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
DenXX/fvcore
|
ThreeNet
| false
| 2,232
|
[
"Apache-2.0"
] | 0
|
4b91cf092f4f5d379b2c93398780a3b5755e7179
|
https://github.com/DenXX/fvcore/tree/4b91cf092f4f5d379b2c93398780a3b5755e7179
|
Hidden2Discrete
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torch.nn.init
class Hidden2Discrete(nn.Module):
def __init__(self, input_size, y_size, k_size, is_lstm=False, has_bias=True
):
super(Hidden2Discrete, self).__init__()
self.y_size = y_size
self.k_size = k_size
latent_size = self.k_size * self.y_size
if is_lstm:
self.p_h = nn.Linear(input_size, latent_size, bias=has_bias)
self.p_c = nn.Linear(input_size, latent_size, bias=has_bias)
else:
self.p_h = nn.Linear(input_size, latent_size, bias=has_bias)
self.is_lstm = is_lstm
def forward(self, inputs):
"""
:param inputs: batch_size x input_size
:return:
"""
if self.is_lstm:
h, c = inputs
if h.dim() == 3:
h = h.squeeze(0)
c = c.squeeze(0)
logits = self.p_h(h) + self.p_c(c)
else:
logits = self.p_h(inputs)
logits = logits.view(-1, self.k_size)
log_qy = F.log_softmax(logits, dim=1)
return logits, log_qy
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'y_size': 4, 'k_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
import torch.utils.data
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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
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, (16, 4), (4, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((256, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(1024)](buf0, buf1, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((256, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_1[grid(1024)](buf1, buf2, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
del buf1
return reinterpret_tensor(buf0, (256, 4), (4, 1), 0
), buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf2
class Hidden2DiscreteNew(nn.Module):
def __init__(self, input_size, y_size, k_size, is_lstm=False, has_bias=True
):
super(Hidden2DiscreteNew, self).__init__()
self.y_size = y_size
self.k_size = k_size
latent_size = self.k_size * self.y_size
if is_lstm:
self.p_h = nn.Linear(input_size, latent_size, bias=has_bias)
self.p_c = nn.Linear(input_size, latent_size, bias=has_bias)
else:
self.p_h = nn.Linear(input_size, latent_size, bias=has_bias)
self.is_lstm = is_lstm
def forward(self, input_0):
primals_1 = self.p_h.weight
primals_2 = self.p_h.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
ChrisGeishauser/ConvLab-2
|
Hidden2Discrete
| false
| 2,233
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
NormKLLoss
|
import torch
import torch.utils.data
import torch.nn.init
import torch as th
from torch.nn.modules.loss import _Loss
class NormKLLoss(_Loss):
def __init__(self, unit_average=False):
super(NormKLLoss, self).__init__()
self.unit_average = unit_average
def forward(self, recog_mu, recog_logvar, prior_mu, prior_logvar):
loss = 1.0 + (recog_logvar - prior_logvar)
loss -= th.div(th.pow(prior_mu - recog_mu, 2), th.exp(prior_logvar))
loss -= th.div(th.exp(recog_logvar), th.exp(prior_logvar))
if self.unit_average:
kl_loss = -0.5 * th.mean(loss, dim=1)
else:
kl_loss = -0.5 * th.sum(loss, dim=1)
avg_kl_loss = th.mean(kl_loss)
return avg_kl_loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
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.utils.data
import torch.nn.init
from torch.nn.modules.loss import _Loss
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_exp_mean_mul_pow_sub_sum_0(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr2 + (r0 + 64 * r1), None)
tmp6 = tl.load(in_ptr3 + (r0 + 64 * r1), None)
tmp15 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp19 = tl.load(in_ptr2 + (16 + r0 + 64 * r1), None)
tmp20 = tl.load(in_ptr3 + (16 + r0 + 64 * r1), None)
tmp30 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp31 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp34 = tl.load(in_ptr2 + (32 + r0 + 64 * r1), None)
tmp35 = tl.load(in_ptr3 + (32 + r0 + 64 * r1), None)
tmp45 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp46 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp49 = tl.load(in_ptr2 + (48 + r0 + 64 * r1), None)
tmp50 = tl.load(in_ptr3 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 - tmp1
tmp3 = 1.0
tmp4 = tmp2 + tmp3
tmp7 = tmp5 - tmp6
tmp8 = tmp7 * tmp7
tmp9 = tl_math.exp(tmp1)
tmp10 = tmp8 / tmp9
tmp11 = tmp4 - tmp10
tmp12 = tl_math.exp(tmp0)
tmp13 = tmp12 / tmp9
tmp14 = tmp11 - tmp13
tmp17 = tmp15 - tmp16
tmp18 = tmp17 + tmp3
tmp21 = tmp19 - tmp20
tmp22 = tmp21 * tmp21
tmp23 = tl_math.exp(tmp16)
tmp24 = tmp22 / tmp23
tmp25 = tmp18 - tmp24
tmp26 = tl_math.exp(tmp15)
tmp27 = tmp26 / tmp23
tmp28 = tmp25 - tmp27
tmp29 = tmp14 + tmp28
tmp32 = tmp30 - tmp31
tmp33 = tmp32 + tmp3
tmp36 = tmp34 - tmp35
tmp37 = tmp36 * tmp36
tmp38 = tl_math.exp(tmp31)
tmp39 = tmp37 / tmp38
tmp40 = tmp33 - tmp39
tmp41 = tl_math.exp(tmp30)
tmp42 = tmp41 / tmp38
tmp43 = tmp40 - tmp42
tmp44 = tmp29 + tmp43
tmp47 = tmp45 - tmp46
tmp48 = tmp47 + tmp3
tmp51 = tmp49 - tmp50
tmp52 = tmp51 * tmp51
tmp53 = tl_math.exp(tmp46)
tmp54 = tmp52 / tmp53
tmp55 = tmp48 - tmp54
tmp56 = tl_math.exp(tmp45)
tmp57 = tmp56 / tmp53
tmp58 = tmp55 - tmp57
tmp59 = tmp44 + tmp58
tmp60 = -0.5
tmp61 = tmp59 * tmp60
tmp62 = tl.broadcast_to(tmp61, [XBLOCK, RBLOCK])
tmp64 = tl.sum(tmp62, 1)[:, None]
tmp65 = 64.0
tmp66 = tmp64 / tmp65
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp66, None)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_div_exp_mean_mul_pow_sub_sum_0[grid(1)](buf2,
arg0_1, arg1_1, arg2_1, arg3_1, 1, 64, XBLOCK=1, num_warps=2,
num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
return buf2,
class NormKLLossNew(_Loss):
def __init__(self, unit_average=False):
super(NormKLLossNew, self).__init__()
self.unit_average = unit_average
def forward(self, input_0, input_1, input_2, input_3):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0]
|
ChrisGeishauser/ConvLab-2
|
NormKLLoss
| false
| 2,234
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
tofp16
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
import torch.optim
class tofp16(nn.Module):
"""
Model wrapper that implements::
def forward(self, input):
return input.half()
"""
def __init__(self):
super(tofp16, self).__init__()
def forward(self, input):
return input.half()
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
import torch.utils.data.distributed
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
@triton.jit
def triton_poi_fused__to_copy_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0.to(tl.float32)
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float16)
get_raw_stream(0)
triton_poi_fused__to_copy_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class tofp16New(nn.Module):
"""
Model wrapper that implements::
def forward(self, input):
return input.half()
"""
def __init__(self):
super(tofp16New, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
FDecaYed/apex
|
tofp16
| false
| 2,235
|
[
"BSD-3-Clause"
] | 0
|
789afd89fe2c5a3e772f557055a9cf0f5e9d1241
|
https://github.com/FDecaYed/apex/tree/789afd89fe2c5a3e772f557055a9cf0f5e9d1241
|
ConvBlock
|
import torch
import torch.nn as nn
class Conv3x3(nn.Module):
"""Layer to pad and convolve input
"""
def __init__(self, in_channels, out_channels, use_refl=True):
super(Conv3x3, self).__init__()
if use_refl:
self.pad = nn.ReflectionPad2d(1)
else:
self.pad = nn.ZeroPad2d(1)
self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)
def forward(self, x):
out = self.pad(x)
out = self.conv(out)
return out
class ConvBlock(nn.Module):
"""Layer to perform a convolution followed by ELU
"""
def __init__(self, in_channels, out_channels):
super(ConvBlock, self).__init__()
self.conv = Conv3x3(in_channels, out_channels)
self.nonlin = nn.ELU(inplace=True)
def forward(self, x):
out = self.conv(x)
out = self.nonlin(out)
return out
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.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_reflection_pad2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6 % 6
x2 = xindex // 36
x3 = xindex
tmp0 = tl.load(in_ptr0 + (15 + -1 * tl_math.abs(-3 + tl_math.abs(-1 +
x0)) + -4 * tl_math.abs(-3 + tl_math.abs(-1 + x1)) + 16 * x2),
xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_elu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 1.0
tmp6 = tmp2 * tmp5
tmp7 = libdevice.expm1(tmp6)
tmp8 = tmp7 * tmp5
tmp9 = tl.where(tmp4, tmp6, tmp8)
tl.store(in_out_ptr0 + x3, tmp9, 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,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_reflection_pad2d_0[grid(576)](primals_1, buf0, 576,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_elu_1[grid(256)](buf2, primals_3, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
return buf2, primals_2, buf0, buf2
class Conv3x3(nn.Module):
"""Layer to pad and convolve input
"""
def __init__(self, in_channels, out_channels, use_refl=True):
super(Conv3x3, self).__init__()
if use_refl:
self.pad = nn.ReflectionPad2d(1)
else:
self.pad = nn.ZeroPad2d(1)
self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)
def forward(self, x):
out = self.pad(x)
out = self.conv(out)
return out
class ConvBlockNew(nn.Module):
"""Layer to perform a convolution followed by ELU
"""
def __init__(self, in_channels, out_channels):
super(ConvBlockNew, self).__init__()
self.conv = Conv3x3(in_channels, out_channels)
self.nonlin = nn.ELU(inplace=True)
def forward(self, input_0):
primals_2 = self.conv.conv.weight
primals_3 = self.conv.conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-
|
ConvBlock
| false
| 2,236
|
[
"MIT"
] | 0
|
13fac05601efed16ae8b29989aad487e04cd90a7
|
https://github.com/Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-/tree/13fac05601efed16ae8b29989aad487e04cd90a7
|
PairwiseBCELoss
|
import torch
from abc import abstractmethod
import torch.utils.data.dataloader
import torch.nn.functional as F
import torch.nn as nn
import torch.nn
class SimilarityLoss(nn.Module):
def __init__(self):
super(SimilarityLoss, self).__init__()
@abstractmethod
def forward(self, inputs, targets):
pass
class PairwiseBCELoss(SimilarityLoss):
"""
Binary cross entropy between pair similarities and pair labels.
"""
def __init__(self, balanced=False):
super(PairwiseBCELoss, self).__init__()
self.balanced = balanced
def forward(self, inputs, targets):
n = inputs.shape[0]
neg_targets = torch.ones_like(targets) - targets
bce_loss = F.binary_cross_entropy_with_logits(inputs, targets,
reduction='none')
if self.balanced:
weight_matrix = n * (targets / 2.0 + neg_targets / (2.0 * (n - 1)))
bce_loss *= weight_matrix
loss = bce_loss.mean()
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 libdevice, math as tl_math
from abc import abstractmethod
import torch.utils.data.dataloader
import torch.nn as nn
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_binary_cross_entropy_with_logits_mean_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp2 * tmp3
tmp5 = 0.0
tmp6 = triton_helpers.minimum(tmp5, tmp3)
tmp7 = tl_math.abs(tmp3)
tmp8 = -tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = libdevice.log1p(tmp9)
tmp11 = tmp6 - tmp10
tmp12 = tmp4 - tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_with_logits_mean_0[grid(1)](buf1,
arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class SimilarityLoss(nn.Module):
def __init__(self):
super(SimilarityLoss, self).__init__()
@abstractmethod
def forward(self, inputs, targets):
pass
class PairwiseBCELossNew(SimilarityLoss):
"""
Binary cross entropy between pair similarities and pair labels.
"""
def __init__(self, balanced=False):
super(PairwiseBCELossNew, self).__init__()
self.balanced = balanced
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
FranziskaKuhls/flair
|
PairwiseBCELoss
| false
| 2,237
|
[
"MIT"
] | 0
|
2bd9e72c961651c7c020076cb8fd80cbbb36da7c
|
https://github.com/FranziskaKuhls/flair/tree/2bd9e72c961651c7c020076cb8fd80cbbb36da7c
|
Sine
|
import torch
import torch.nn as nn
class Sine(nn.Module):
"""
A wrapper for PyTorch sine function.
"""
def __init__(self, w0=1.0):
super().__init__()
self.w0 = w0
@staticmethod
def forward(x):
return torch.sin(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import 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_sin_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl_math.sin(tmp0)
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sin_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SineNew(nn.Module):
"""
A wrapper for PyTorch sine function.
"""
def __init__(self, w0=1.0):
super().__init__()
self.w0 = w0
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
FinbarArgus/phynn
|
Sine
| false
| 2,238
|
[
"Apache-2.0"
] | 0
|
436bfd6fa4ad86692bf12b4f76c92bc177626c40
|
https://github.com/FinbarArgus/phynn/tree/436bfd6fa4ad86692bf12b4f76c92bc177626c40
|
InvDepth
|
import torch
import torch.nn as nn
class InvDepth(nn.Module):
"""Inverse depth layer"""
def __init__(self, in_channels, out_channels=1, min_depth=0.5):
"""
Initializes an InvDepth object.
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
min_depth : float
Minimum depth value to calculate
"""
super().__init__()
self.min_depth = min_depth
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
stride=1)
self.pad = nn.ConstantPad2d([1] * 4, value=0)
self.activ = nn.Sigmoid()
def forward(self, x):
"""Runs the InvDepth layer."""
x = self.conv1(self.pad(x))
return self.activ(x) / self.min_depth
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 6 % 6
x0 = xindex % 6
x2 = xindex // 36
x4 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -1 + x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask,
other=0.0)
tl.store(out_ptr0 + x4, tmp11, xmask)
@triton.jit
def triton_poi_fused_convolution_div_sigmoid_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tmp5 = 2.0
tmp6 = tmp4 * tmp5
tl.store(in_out_ptr0 + x0, tmp3, xmask)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(576)](primals_1, buf0, 576,
XBLOCK=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, 1, 4, 4), (16, 16, 4, 1))
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32)
triton_poi_fused_convolution_div_sigmoid_1[grid(64)](buf2,
primals_3, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return buf3, primals_2, buf0, buf2
class InvDepthNew(nn.Module):
"""Inverse depth layer"""
def __init__(self, in_channels, out_channels=1, min_depth=0.5):
"""
Initializes an InvDepth object.
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
min_depth : float
Minimum depth value to calculate
"""
super().__init__()
self.min_depth = min_depth
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
stride=1)
self.pad = nn.ConstantPad2d([1] * 4, value=0)
self.activ = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-
|
InvDepth
| false
| 2,239
|
[
"MIT"
] | 0
|
13fac05601efed16ae8b29989aad487e04cd90a7
|
https://github.com/Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-/tree/13fac05601efed16ae8b29989aad487e04cd90a7
|
FeatNet
|
import torch
import torch.nn as nn
from itertools import product as product
class FeatNet(nn.Module):
def __init__(self):
super(FeatNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=
(3, 7), stride=1, padding=(1, 3), bias=False)
self.tanh1 = nn.Tanh()
self.Pool1 = nn.AvgPool2d(kernel_size=(2, 2), stride=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size
=(3, 5), stride=1, padding=(1, 2), bias=False)
self.tanh2 = nn.Tanh()
self.Upsample2 = nn.ConvTranspose2d(in_channels=32, out_channels=32,
kernel_size=4, stride=2, padding=1, groups=32)
self.Pool2 = nn.AvgPool2d(kernel_size=(2, 2), stride=2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size
=(3, 3), stride=1, padding=(1, 1), bias=False)
self.tanh3 = nn.Tanh()
self.Upsample3 = nn.ConvTranspose2d(in_channels=64, out_channels=64,
kernel_size=8, stride=4, padding=2, bias=False, groups=64)
self.conv4 = nn.Conv2d(in_channels=112, out_channels=1, kernel_size
=3, stride=1, padding=1, bias=False)
def forward(self, x):
x = self.conv1(x)
x = self.tanh1(x)
stack1 = x
x = self.Pool1(x)
x = self.conv2(x)
x = self.tanh2(x)
stack2 = self.Upsample2(x)
x = self.Pool2(x)
x = self.conv3(x)
x = self.tanh3(x)
stack3 = self.Upsample3(x)
x = torch.concat((stack1, stack2, stack3), 1)
output = self.conv4(x)
return output
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from itertools import product as product
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_tanh_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, None)
@triton.jit
def triton_poi_fused_avg_pool2d_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_tanh_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, None)
@triton.jit
def triton_poi_fused_avg_pool2d_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (32 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (33 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_tanh_4(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, None)
@triton.jit
def triton_poi_fused_cat_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 112
x0 = xindex % 4096
x2 = xindex // 458752
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 16, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 65536 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 48, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (x0 + 4096 * (-16 + x1) + 131072 * x2), tmp9,
other=0.0)
tmp11 = tl.load(in_ptr2 + (-16 + x1), tmp9, 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 = tmp0 >= tmp7
tl.full([1], 112, tl.int64)
tmp18 = tl.load(in_ptr3 + (x0 + 4096 * (-48 + x1) + 262144 * x2), tmp15,
other=0.0)
tmp19 = tl.where(tmp9, tmp14, tmp18)
tmp20 = tl.where(tmp4, tmp5, tmp19)
tl.store(out_ptr0 + x3, tmp20, None)
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, (16, 1, 3, 7), (21, 21, 7, 1))
assert_size_stride(primals_2, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_3, (32, 16, 3, 5), (240, 15, 5, 1))
assert_size_stride(primals_4, (32, 1, 4, 4), (16, 16, 4, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (64, 1, 8, 8), (64, 64, 8, 1))
assert_size_stride(primals_8, (1, 112, 3, 3), (1008, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,
1), padding=(1, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(262144)](buf1, 262144, XBLOCK=512,
num_warps=8, num_stages=1)
buf2 = empty_strided_cuda((4, 16, 32, 32), (16384, 1024, 32, 1),
torch.float32)
triton_poi_fused_avg_pool2d_1[grid(65536)](buf1, buf2, 65536,
XBLOCK=256, num_warps=4, num_stages=1)
buf3 = extern_kernels.convolution(buf2, primals_3, stride=(1, 1),
padding=(1, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf4 = buf3
del buf3
triton_poi_fused_tanh_2[grid(131072)](buf4, 131072, XBLOCK=512,
num_warps=8, num_stages=1)
buf5 = extern_kernels.convolution(buf4, primals_4, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=32, bias=None)
assert_size_stride(buf5, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf6 = empty_strided_cuda((4, 32, 16, 16), (8192, 256, 16, 1),
torch.float32)
triton_poi_fused_avg_pool2d_3[grid(32768)](buf4, buf6, 32768,
XBLOCK=256, num_warps=4, num_stages=1)
buf7 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 64, 16, 16), (16384, 256, 16, 1))
buf8 = buf7
del buf7
triton_poi_fused_tanh_4[grid(65536)](buf8, 65536, XBLOCK=256,
num_warps=4, num_stages=1)
buf9 = extern_kernels.convolution(buf8, primals_7, stride=(4, 4),
padding=(2, 2), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=64, bias=None)
assert_size_stride(buf9, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf10 = empty_strided_cuda((4, 112, 64, 64), (458752, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_5[grid(1835008)](buf1, buf5, primals_5, buf9,
buf10, 1835008, XBLOCK=1024, num_warps=4, num_stages=1)
del buf5
del buf9
del primals_5
buf11 = extern_kernels.convolution(buf10, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 1, 64, 64), (4096, 4096, 64, 1))
return (buf11, primals_1, primals_2, primals_3, primals_4, primals_6,
primals_7, primals_8, buf1, buf2, buf4, buf6, buf8, buf10)
class FeatNetNew(nn.Module):
def __init__(self):
super(FeatNetNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=
(3, 7), stride=1, padding=(1, 3), bias=False)
self.tanh1 = nn.Tanh()
self.Pool1 = nn.AvgPool2d(kernel_size=(2, 2), stride=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size
=(3, 5), stride=1, padding=(1, 2), bias=False)
self.tanh2 = nn.Tanh()
self.Upsample2 = nn.ConvTranspose2d(in_channels=32, out_channels=32,
kernel_size=4, stride=2, padding=1, groups=32)
self.Pool2 = nn.AvgPool2d(kernel_size=(2, 2), stride=2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size
=(3, 3), stride=1, padding=(1, 1), bias=False)
self.tanh3 = nn.Tanh()
self.Upsample3 = nn.ConvTranspose2d(in_channels=64, out_channels=64,
kernel_size=8, stride=4, padding=2, bias=False, groups=64)
self.conv4 = nn.Conv2d(in_channels=112, out_channels=1, kernel_size
=3, stride=1, padding=1, bias=False)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_3 = self.conv2.weight
primals_4 = self.Upsample2.weight
primals_5 = self.Upsample2.bias
primals_6 = self.conv3.weight
primals_7 = self.Upsample3.weight
primals_8 = self.conv4.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
DongChengdongHangZhou/caffe-to-pytorch
|
FeatNet
| false
| 2,240
|
[
"Apache-2.0"
] | 0
|
5e3104f3aa77d35bad5d2de235b067460c136fd5
|
https://github.com/DongChengdongHangZhou/caffe-to-pytorch/tree/5e3104f3aa77d35bad5d2de235b067460c136fd5
|
PaddedMaxPool2d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class PaddedMaxPool2d(nn.Module):
""" Maxpool layer with a replicating padding.
Args:
kernel_size (int or tuple): Kernel size for maxpooling
stride (int or tuple, optional): The stride of the window; Default ``kernel_size``
padding (tuple, optional): (left, right, top, bottom) padding; Default **None**
dilation (int or tuple, optional): A parameter that controls the stride of elements in the window
"""
def __init__(self, kernel_size, stride=None, padding=(0, 0, 0, 0),
dilation=1):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride or kernel_size
self.padding = padding
self.dilation = dilation
def extra_repr(self):
return (
f'kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}, dilation={self.dilation}'
)
def forward(self, x):
x = F.max_pool2d(F.pad(x, self.padding, mode='replicate'), self.
kernel_size, self.stride, 0, self.dilation)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'kernel_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp20 = triton_helpers.maximum(tmp19, tmp18)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = triton_helpers.maximum(tmp23, tmp22)
tmp26 = triton_helpers.maximum(tmp25, tmp24)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tl.store(out_ptr0 + x0, tmp30, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(16)](arg0_1, buf0,
16, XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
return buf0,
class PaddedMaxPool2dNew(nn.Module):
""" Maxpool layer with a replicating padding.
Args:
kernel_size (int or tuple): Kernel size for maxpooling
stride (int or tuple, optional): The stride of the window; Default ``kernel_size``
padding (tuple, optional): (left, right, top, bottom) padding; Default **None**
dilation (int or tuple, optional): A parameter that controls the stride of elements in the window
"""
def __init__(self, kernel_size, stride=None, padding=(0, 0, 0, 0),
dilation=1):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride or kernel_size
self.padding = padding
self.dilation = dilation
def extra_repr(self):
return (
f'kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}, dilation={self.dilation}'
)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
FenryrMKIII/objectDetection-lightnet
|
PaddedMaxPool2d
| false
| 2,241
|
[
"MIT"
] | 0
|
3a1fa7b77227210060714a9e22d7d241888b36b4
|
https://github.com/FenryrMKIII/objectDetection-lightnet/tree/3a1fa7b77227210060714a9e22d7d241888b36b4
|
Residual
|
import torch
import torch.nn as nn
class Residual(nn.Sequential):
""" Residual block that runs like a Sequential, but then adds the original input to the output tensor.
See :class:`torch.nn.Sequential` for more information.
Warning:
The dimension between the input and output of the module need to be the same
or need to be broadcastable from one to the other!
"""
def forward(self, x):
y = super().forward(x)
return x + y
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_add_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0 + tmp0
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ResidualNew(nn.Sequential):
""" Residual block that runs like a Sequential, but then adds the original input to the output tensor.
See :class:`torch.nn.Sequential` for more information.
Warning:
The dimension between the input and output of the module need to be the same
or need to be broadcastable from one to the other!
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
FenryrMKIII/objectDetection-lightnet
|
Residual
| false
| 2,242
|
[
"MIT"
] | 0
|
3a1fa7b77227210060714a9e22d7d241888b36b4
|
https://github.com/FenryrMKIII/objectDetection-lightnet/tree/3a1fa7b77227210060714a9e22d7d241888b36b4
|
CELossWeightedMasked
|
import torch
import torch.nn as nn
class WeightedLoss(nn.Module):
def __init__(self):
super(WeightedLoss, self).__init__()
self.weighted = False
def generate_weight_mask(self, mask, to_ignore=None):
""" Generates a weight mask where pixel weights are inversely proportional to
how many pixels are in the class
@param mask: a [N x ...] torch.FloatTensor with values in {0, 1, 2, ..., K+1}, where K is number of objects. {0,1} are background/table.
@param to_ignore: a list of classes (integers) to ignore when creating mask
@return: a torch.FloatTensor that is same shape as mask.
"""
N = mask.shape[0]
if self.weighted:
weight_mask = torch.zeros_like(mask).float()
for i in range(N):
unique_object_labels = torch.unique(mask[i])
for obj in unique_object_labels:
if to_ignore is not None and obj in to_ignore:
continue
num_pixels = torch.sum(mask[i] == obj, dtype=torch.float)
weight_mask[i, mask[i] == obj] = 1 / num_pixels
else:
weight_mask = torch.ones_like(mask)
if to_ignore is not None:
for obj in to_ignore:
weight_mask[mask == obj] = 0
return weight_mask
class CELossWeightedMasked(WeightedLoss):
""" Compute weighted CE loss with logits
"""
def __init__(self, weighted=False):
super(CELossWeightedMasked, self).__init__()
self.CrossEntropyLoss = nn.CrossEntropyLoss(reduction='none')
self.weighted = weighted
def forward(self, x, target, fg_mask):
""" Compute weighted cross entropy
@param x: a [N x C x H x W] torch.FloatTensor of values
@param target: a [N x H x W] torch.LongTensor of values
@param fg_mask: a [N x H x W] torch.LongTensor of values in {0, 1, 2, ...}
"""
temp = self.CrossEntropyLoss(x, target)
weight_mask = self.generate_weight_mask(fg_mask, to_ignore=[0, 1])
loss = torch.sum(temp * weight_mask) / torch.sum(weight_mask)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_mul_neg_sum_1(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp13 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp16 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp20 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp24 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp1 = tl_math.exp(tmp0)
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 + tmp3
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp4 + tmp6
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp0 - tmp11
tmp14 = tmp12 * tmp13
tmp15 = tmp2 - tmp11
tmp17 = tmp15 * tmp16
tmp18 = tmp14 + tmp17
tmp19 = tmp5 - tmp11
tmp21 = tmp19 * tmp20
tmp22 = tmp18 + tmp21
tmp23 = tmp8 - tmp11
tmp25 = tmp23 * tmp24
tmp26 = tmp22 + tmp25
tmp27 = -tmp26
tl.store(out_ptr0 + x2, tmp27, xmask)
@triton.jit
def triton_per_fused__log_softmax_div_index_put_lift_fresh_mul_neg_ones_like_sum_2(
in_out_ptr1, 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
r1 = rindex % 64
tmp0 = tl.load(in_ptr0 + r0, None)
tmp7 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp1 = 0.0
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = tl.where(tmp2, tmp1, tmp3)
tmp5 = tmp0 == tmp3
tmp6 = tl.where(tmp5, tmp1, tmp4)
tmp8 = tmp7 * tmp6
tmp9 = tl.broadcast_to(tmp8, [RBLOCK])
tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0))
tmp12 = tl.broadcast_to(tmp6, [RBLOCK])
tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0))
tmp15 = tmp11 / tmp14
tl.debug_barrier()
tl.store(in_out_ptr1 + tl.full([1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_mul_neg_sum_1[grid(64)](buf0, arg0_1,
buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del buf0
buf4 = empty_strided_cuda((), (), torch.float32)
buf6 = buf4
del buf4
triton_per_fused__log_softmax_div_index_put_lift_fresh_mul_neg_ones_like_sum_2[
grid(1)](buf6, arg2_1, buf3, 1, 256, num_warps=2, num_stages=1)
del arg2_1
del buf3
return buf6,
class WeightedLoss(nn.Module):
def __init__(self):
super(WeightedLoss, self).__init__()
self.weighted = False
def generate_weight_mask(self, mask, to_ignore=None):
""" Generates a weight mask where pixel weights are inversely proportional to
how many pixels are in the class
@param mask: a [N x ...] torch.FloatTensor with values in {0, 1, 2, ..., K+1}, where K is number of objects. {0,1} are background/table.
@param to_ignore: a list of classes (integers) to ignore when creating mask
@return: a torch.FloatTensor that is same shape as mask.
"""
N = mask.shape[0]
if self.weighted:
weight_mask = torch.zeros_like(mask).float()
for i in range(N):
unique_object_labels = torch.unique(mask[i])
for obj in unique_object_labels:
if to_ignore is not None and obj in to_ignore:
continue
num_pixels = torch.sum(mask[i] == obj, dtype=torch.float)
weight_mask[i, mask[i] == obj] = 1 / num_pixels
else:
weight_mask = torch.ones_like(mask)
if to_ignore is not None:
for obj in to_ignore:
weight_mask[mask == obj] = 0
return weight_mask
class CELossWeightedMaskedNew(WeightedLoss):
""" Compute weighted CE loss with logits
"""
def __init__(self, weighted=False):
super(CELossWeightedMaskedNew, self).__init__()
self.CrossEntropyLoss = nn.CrossEntropyLoss(reduction='none')
self.weighted = weighted
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]
|
FANG-Xiaolin/uois
|
CELossWeightedMasked
| false
| 2,243
|
[
"MIT"
] | 0
|
7489e69d1513faf2f3f030a441abdd33ca22304c
|
https://github.com/FANG-Xiaolin/uois/tree/7489e69d1513faf2f3f030a441abdd33ca22304c
|
upsample
|
import torch
import torch.nn as nn
class upsample(nn.Module):
def __init__(self, scale_factor):
super(upsample, self).__init__()
self.scale_factor = scale_factor
def forward(self, x):
return nn.functional.interpolate(x, scale_factor=self.scale_factor)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'scale_factor': 1.0}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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__unsafe_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
x1 = xindex // 4 % 4
x0 = xindex % 4
x2 = xindex // 16
x4 = xindex
tmp0 = x1
tmp1 = tmp0.to(tl.float32)
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = tmp3.to(tl.int32)
tmp5 = x0
tmp6 = tmp5.to(tl.float32)
tmp7 = tmp6 * tmp2
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.load(in_ptr0 + (tmp8 + 4 * tmp4 + 16 * x2), xmask,
eviction_policy='evict_last')
tl.store(out_ptr0 + x4, tmp9, xmask)
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__unsafe_index_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class upsampleNew(nn.Module):
def __init__(self, scale_factor):
super(upsampleNew, self).__init__()
self.scale_factor = scale_factor
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
FMsunyh/CornerNet-Lite
|
upsample
| false
| 2,244
|
[
"BSD-3-Clause"
] | 0
|
85770fa6682646d572a5bd2277a0075d6dd22b93
|
https://github.com/FMsunyh/CornerNet-Lite/tree/85770fa6682646d572a5bd2277a0075d6dd22b93
|
Conv3x3
|
import torch
import torch.nn as nn
class Conv3x3(nn.Module):
"""Layer to pad and convolve input
"""
def __init__(self, in_channels, out_channels, use_refl=True):
super(Conv3x3, self).__init__()
if use_refl:
self.pad = nn.ReflectionPad2d(1)
else:
self.pad = nn.ZeroPad2d(1)
self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)
def forward(self, x):
out = self.pad(x)
out = self.conv(out)
return out
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.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_reflection_pad2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6 % 6
x2 = xindex // 36
x3 = xindex
tmp0 = tl.load(in_ptr0 + (15 + -1 * tl_math.abs(-3 + tl_math.abs(-1 +
x0)) + -4 * tl_math.abs(-3 + tl_math.abs(-1 + x1)) + 16 * x2),
xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_reflection_pad2d_0[grid(576)](primals_1, buf0, 576,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(256)](buf2, primals_3, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
return buf2, primals_2, buf0
class Conv3x3New(nn.Module):
"""Layer to pad and convolve input
"""
def __init__(self, in_channels, out_channels, use_refl=True):
super(Conv3x3New, self).__init__()
if use_refl:
self.pad = nn.ReflectionPad2d(1)
else:
self.pad = nn.ZeroPad2d(1)
self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)
def forward(self, input_0):
primals_2 = self.conv.weight
primals_3 = self.conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-
|
Conv3x3
| false
| 2,245
|
[
"MIT"
] | 0
|
13fac05601efed16ae8b29989aad487e04cd90a7
|
https://github.com/Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-/tree/13fac05601efed16ae8b29989aad487e04cd90a7
|
Conv2d_GN_ReLUx2
|
import torch
import torch.nn as nn
class Conv2d_GN_ReLU(nn.Module):
""" Implements a module that performs
conv2d + groupnorm + ReLU +
Assumes kernel size is odd
"""
def __init__(self, in_channels, out_channels, num_groups, ksize=3, stride=1
):
super(Conv2d_GN_ReLU, self).__init__()
padding = 0 if ksize < 2 else ksize // 2
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=ksize,
stride=stride, padding=padding, bias=False)
self.gn1 = nn.GroupNorm(num_groups, out_channels)
self.relu1 = nn.ReLU(inplace=True)
def forward(self, x):
out = self.conv1(x)
out = self.gn1(out)
out = self.relu1(out)
return out
class Conv2d_GN_ReLUx2(nn.Module):
""" Implements a module that performs
conv2d + groupnorm + ReLU +
conv2d + groupnorm + ReLU
(and a possible downsampling operation)
Assumes kernel size is odd
"""
def __init__(self, in_channels, out_channels, num_groups, ksize=3, stride=1
):
super(Conv2d_GN_ReLUx2, self).__init__()
self.layer1 = Conv2d_GN_ReLU(in_channels, out_channels, num_groups,
ksize=ksize, stride=stride)
self.layer2 = Conv2d_GN_ReLU(out_channels, out_channels, num_groups,
ksize=ksize, stride=stride)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'num_groups': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_native_group_norm_relu_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
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 = tmp0 - tmp10
tmp18 = 64.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.full([1, 1], 0, tl.int32)
tmp29 = triton_helpers.maximum(tmp28, tmp27)
tl.store(out_ptr2 + (r1 + 64 * x0), tmp29, xmask)
tl.store(out_ptr3 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
@triton.jit
def triton_per_fused_native_group_norm_relu_threshold_backward_1(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr2, out_ptr3, out_ptr4, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
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 = tmp0 - tmp10
tmp18 = 64.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tmp28 = tl.full([1, 1], 0, tl.int32)
tmp29 = triton_helpers.maximum(tmp28, tmp27)
tmp30 = 0.0
tmp31 = tmp29 <= tmp30
tl.store(out_ptr2 + (r1 + 64 * x0), tmp29, xmask)
tl.store(out_ptr3 + (r1 + 64 * x0), tmp31, xmask)
tl.store(out_ptr4 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (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,))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
get_raw_stream(0)
triton_per_fused_native_group_norm_relu_0[grid(4)](buf0, primals_3,
primals_4, buf1, buf5, buf4, 4, 64, XBLOCK=1, num_warps=2,
num_stages=1)
del primals_4
buf6 = extern_kernels.convolution(buf5, primals_5, 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((4, 1, 1, 1), (1, 4, 4, 4), 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((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
triton_per_fused_native_group_norm_relu_threshold_backward_1[grid(4)](
buf6, primals_6, primals_7, buf7, buf11, buf12, buf10, 4, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del primals_7
return (buf11, primals_1, primals_2, primals_3, primals_5, primals_6,
buf0, reinterpret_tensor(buf1, (4, 1), (1, 1), 0),
reinterpret_tensor(buf4, (4, 1), (1, 1), 0), buf5, buf6,
reinterpret_tensor(buf7, (4, 1), (1, 1), 0), reinterpret_tensor(
buf10, (4, 1), (1, 1), 0), buf12)
class Conv2d_GN_ReLU(nn.Module):
""" Implements a module that performs
conv2d + groupnorm + ReLU +
Assumes kernel size is odd
"""
def __init__(self, in_channels, out_channels, num_groups, ksize=3, stride=1
):
super(Conv2d_GN_ReLU, self).__init__()
padding = 0 if ksize < 2 else ksize // 2
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=ksize,
stride=stride, padding=padding, bias=False)
self.gn1 = nn.GroupNorm(num_groups, out_channels)
self.relu1 = nn.ReLU(inplace=True)
def forward(self, x):
out = self.conv1(x)
out = self.gn1(out)
out = self.relu1(out)
return out
class Conv2d_GN_ReLUx2New(nn.Module):
""" Implements a module that performs
conv2d + groupnorm + ReLU +
conv2d + groupnorm + ReLU
(and a possible downsampling operation)
Assumes kernel size is odd
"""
def __init__(self, in_channels, out_channels, num_groups, ksize=3, stride=1
):
super(Conv2d_GN_ReLUx2New, self).__init__()
self.layer1 = Conv2d_GN_ReLU(in_channels, out_channels, num_groups,
ksize=ksize, stride=stride)
self.layer2 = Conv2d_GN_ReLU(out_channels, out_channels, num_groups,
ksize=ksize, stride=stride)
def forward(self, input_0):
primals_1 = self.layer1.conv1.weight
primals_3 = self.layer1.gn1.weight
primals_4 = self.layer1.gn1.bias
primals_5 = self.layer2.conv1.weight
primals_6 = self.layer2.gn1.weight
primals_7 = self.layer2.gn1.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
FANG-Xiaolin/uois
|
Conv2d_GN_ReLUx2
| false
| 2,246
|
[
"MIT"
] | 0
|
7489e69d1513faf2f3f030a441abdd33ca22304c
|
https://github.com/FANG-Xiaolin/uois/tree/7489e69d1513faf2f3f030a441abdd33ca22304c
|
Reorg
|
import torch
import torch.nn as nn
class Reorg(nn.Module):
""" This layer reorganizes a tensor according to a stride.
The dimensions 2,3 will be sliced by the stride and then stacked in dimension 1. (input must have 4 dimensions)
Args:
stride (int): stride to divide the input tensor
"""
def __init__(self, stride=2):
super().__init__()
self.stride = stride
if not isinstance(stride, int):
raise TypeError(f'stride is not an int [{type(stride)}]')
def extra_repr(self):
return f'stride={self.stride}'
def forward(self, x):
assert x.dim() == 4
B, C, H, W = x.size()
if H % self.stride != 0:
raise ValueError(
f'Dimension mismatch: {H} is not divisible by {self.stride}')
if W % self.stride != 0:
raise ValueError(
f'Dimension mismatch: {W} is not divisible by {self.stride}')
x = x.view(B, C // self.stride ** 2, H, self.stride, W, self.stride
).contiguous()
x = x.permute(0, 3, 5, 1, 2, 4).contiguous()
x = x.view(B, -1, H // self.stride, W // self.stride)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 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
x3 = xindex % 4
x4 = xindex // 4
y0 = yindex % 2
y1 = yindex // 2 % 2
y2 = yindex // 4
x6 = xindex
y5 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 2 * x3 + 8 * y1 + 16 * x4 + 64 * y2),
xmask & ymask)
tl.store(out_ptr0 + (x6 + 16 * y5), tmp0, xmask & ymask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 2, 1, 4, 4), (64, 32, 16, 16, 4, 1
), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 16)](arg0_1, buf0, 16, 16, XBLOCK
=16, YBLOCK=16, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 16, 2, 2), (64, 4, 2, 1), 0),
class ReorgNew(nn.Module):
""" This layer reorganizes a tensor according to a stride.
The dimensions 2,3 will be sliced by the stride and then stacked in dimension 1. (input must have 4 dimensions)
Args:
stride (int): stride to divide the input tensor
"""
def __init__(self, stride=2):
super().__init__()
self.stride = stride
if not isinstance(stride, int):
raise TypeError(f'stride is not an int [{type(stride)}]')
def extra_repr(self):
return f'stride={self.stride}'
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
FenryrMKIII/objectDetection-lightnet
|
Reorg
| false
| 2,247
|
[
"MIT"
] | 0
|
3a1fa7b77227210060714a9e22d7d241888b36b4
|
https://github.com/FenryrMKIII/objectDetection-lightnet/tree/3a1fa7b77227210060714a9e22d7d241888b36b4
|
LayerNorm
|
import torch
import torch.nn as nn
import torch.nn.parallel
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
if x.size(0) == 1:
mean = x.view(-1).mean().view(*shape)
std = x.view(-1).std().view(*shape)
else:
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_mean_mul_std_sub_0(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp28 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 64.0
tmp20 = tmp4 / tmp19
tmp21 = 63.0
tmp22 = tmp18 / tmp21
tmp23 = libdevice.sqrt(tmp22)
tmp24 = 1e-05
tmp25 = tmp23 + tmp24
tmp26 = tmp0 - tmp20
tmp27 = tmp26 / tmp25
tmp29 = tmp27 * tmp28
tmp31 = tmp29 + tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp25, xmask)
tl.store(out_ptr0 + (r1 + 64 * x0), tmp31, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = buf0
del buf0
buf5 = reinterpret_tensor(buf3, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf3
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_mean_mul_std_sub_0[grid(4)](buf1, buf5,
primals_1, primals_2, primals_3, buf6, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
del primals_2
del primals_3
return buf6, primals_1, reinterpret_tensor(buf1, (4, 1, 1, 1), (1, 1, 1,
1), 0), buf5
class LayerNormNew(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNormNew, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, input_0):
primals_2 = self.gamma
primals_3 = self.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
FUTUREEEEEE/S2R-DepthNet
|
LayerNorm
| false
| 2,248
|
[
"MIT"
] | 0
|
415cc40aef10f9540026ff435d14a9ba9e30ad74
|
https://github.com/FUTUREEEEEE/S2R-DepthNet/tree/415cc40aef10f9540026ff435d14a9ba9e30ad74
|
Conv2dBlock
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
class AdaptiveInstanceNorm2d(nn.Module):
def __init__(self, num_features, eps=1e-05, momentum=0.1):
super(AdaptiveInstanceNorm2d, self).__init__()
self.num_features = num_features
self.eps = eps
self.momentum = momentum
self.weight = None
self.bias = None
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
def forward(self, x):
assert self.weight is not None and self.bias is not None, 'Please assign weight and bias before calling AdaIN!'
b, c = x.size(0), x.size(1)
running_mean = self.running_mean.repeat(b)
running_var = self.running_var.repeat(b)
x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:])
out = F.batch_norm(x_reshaped, running_mean, running_var, self.
weight, self.bias, True, self.momentum, self.eps)
return out.view(b, c, *x.size()[2:])
def __repr__(self):
return self.__class__.__name__ + '(' + str(self.num_features) + ')'
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
if x.size(0) == 1:
mean = x.view(-1).mean().view(*shape)
std = x.view(-1).std().view(*shape)
else:
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
class Conv2dBlock(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, stride, padding=
0, norm='none', activation='relu', pad_type='zero'):
super(Conv2dBlock, self).__init__()
self.use_bias = True
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'replicate':
self.pad = nn.ReplicationPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, 'Unsupported padding type: {}'.format(pad_type)
norm_dim = output_dim
if norm == 'bn':
self.norm = nn.BatchNorm2d(norm_dim)
elif norm == 'in':
self.norm = nn.InstanceNorm2d(norm_dim)
elif norm == 'ln':
self.norm = LayerNorm(norm_dim)
elif norm == 'adain':
self.norm = AdaptiveInstanceNorm2d(norm_dim)
elif norm == 'none' or norm == 'sn':
self.norm = None
else:
assert 0, 'Unsupported normalization: {}'.format(norm)
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.2, inplace=True)
elif activation == 'prelu':
self.activation = nn.PReLU()
elif activation == 'selu':
self.activation = nn.SELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh()
elif activation == 'none':
self.activation = None
else:
assert 0, 'Unsupported activation: {}'.format(activation)
if norm == 'sn':
self.conv = SpectralNorm(nn.Conv2d(input_dim, output_dim,
kernel_size, stride, bias=self.use_bias))
else:
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size,
stride, bias=self.use_bias)
def forward(self, x):
x = self.pad(x)
x = self.conv(x)
if self.norm:
x = self.norm(x)
if self.activation:
x = self.activation(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 4, 'kernel_size': 4,
'stride': 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 torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_0(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = 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, 4, 1, 1), (4, 1, 1, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_convolution_relu_threshold_backward_0[grid(16)](buf1,
primals_3, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return buf1, primals_1, primals_2, buf2
class AdaptiveInstanceNorm2d(nn.Module):
def __init__(self, num_features, eps=1e-05, momentum=0.1):
super(AdaptiveInstanceNorm2d, self).__init__()
self.num_features = num_features
self.eps = eps
self.momentum = momentum
self.weight = None
self.bias = None
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
def forward(self, x):
assert self.weight is not None and self.bias is not None, 'Please assign weight and bias before calling AdaIN!'
b, c = x.size(0), x.size(1)
running_mean = self.running_mean.repeat(b)
running_var = self.running_var.repeat(b)
x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:])
out = F.batch_norm(x_reshaped, running_mean, running_var, self.
weight, self.bias, True, self.momentum, self.eps)
return out.view(b, c, *x.size()[2:])
def __repr__(self):
return self.__class__.__name__ + '(' + str(self.num_features) + ')'
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
if self.affine:
self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())
self.beta = nn.Parameter(torch.zeros(num_features))
def forward(self, x):
shape = [-1] + [1] * (x.dim() - 1)
if x.size(0) == 1:
mean = x.view(-1).mean().view(*shape)
std = x.view(-1).std().view(*shape)
else:
mean = x.view(x.size(0), -1).mean(1).view(*shape)
std = x.view(x.size(0), -1).std(1).view(*shape)
x = (x - mean) / (std + self.eps)
if self.affine:
shape = [1, -1] + [1] * (x.dim() - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
class Conv2dBlockNew(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, stride, padding=
0, norm='none', activation='relu', pad_type='zero'):
super(Conv2dBlockNew, self).__init__()
self.use_bias = True
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'replicate':
self.pad = nn.ReplicationPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, 'Unsupported padding type: {}'.format(pad_type)
norm_dim = output_dim
if norm == 'bn':
self.norm = nn.BatchNorm2d(norm_dim)
elif norm == 'in':
self.norm = nn.InstanceNorm2d(norm_dim)
elif norm == 'ln':
self.norm = LayerNorm(norm_dim)
elif norm == 'adain':
self.norm = AdaptiveInstanceNorm2d(norm_dim)
elif norm == 'none' or norm == 'sn':
self.norm = None
else:
assert 0, 'Unsupported normalization: {}'.format(norm)
if activation == 'relu':
self.activation = nn.ReLU(inplace=True)
elif activation == 'lrelu':
self.activation = nn.LeakyReLU(0.2, inplace=True)
elif activation == 'prelu':
self.activation = nn.PReLU()
elif activation == 'selu':
self.activation = nn.SELU(inplace=True)
elif activation == 'tanh':
self.activation = nn.Tanh()
elif activation == 'none':
self.activation = None
else:
assert 0, 'Unsupported activation: {}'.format(activation)
if norm == 'sn':
self.conv = SpectralNorm(nn.Conv2d(input_dim, output_dim,
kernel_size, stride, bias=self.use_bias))
else:
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size,
stride, bias=self.use_bias)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_3 = self.conv.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
FUTUREEEEEE/S2R-DepthNet
|
Conv2dBlock
| false
| 2,249
|
[
"MIT"
] | 0
|
415cc40aef10f9540026ff435d14a9ba9e30ad74
|
https://github.com/FUTUREEEEEE/S2R-DepthNet/tree/415cc40aef10f9540026ff435d14a9ba9e30ad74
|
Siren
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Sine(nn.Module):
"""
A wrapper for PyTorch sine function.
"""
def __init__(self, w0=1.0):
super().__init__()
self.w0 = w0
@staticmethod
def forward(x):
return torch.sin(x)
class Siren(nn.Module):
"""
An implementation of the Sine activation function known as Siren.
"""
def __init__(self, dim_in, dim_out, w0=30.0, c=6.0, is_first=False):
"""
:param dim_in: input dimension.
:param dim_out: output dimension.
:param w0: initial weight.
:param c: parameter to distribute the weights uniformly so that after sine activation the input is
arcsine-distributed.
:param is_first: boolean to check if it's the first layer.
"""
super().__init__()
self.dim_in = dim_in
self.is_first = is_first
weight = torch.zeros(dim_out, dim_in)
bias = torch.zeros(dim_out)
self.initialization(weight, bias, c=c, w0=w0)
self.weight = nn.Parameter(weight)
self.bias = nn.Parameter(bias)
self.activation = Sine(w0)
def initialization(self, weight, bias, c, w0):
dim = self.dim_in
w_std = 1 / dim if self.is_first else math.sqrt(c / dim) / w0
weight.uniform_(-w_std, w_std)
if bias is not None:
bias.uniform_(-w_std, w_std)
def forward(self, x):
out = F.linear(x, self.weight, self.bias)
out = self.activation(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import 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_sin_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl_math.sin(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,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sin_0[grid(256)](buf0, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0
class Sine(nn.Module):
"""
A wrapper for PyTorch sine function.
"""
def __init__(self, w0=1.0):
super().__init__()
self.w0 = w0
@staticmethod
def forward(x):
return torch.sin(x)
class SirenNew(nn.Module):
"""
An implementation of the Sine activation function known as Siren.
"""
def __init__(self, dim_in, dim_out, w0=30.0, c=6.0, is_first=False):
"""
:param dim_in: input dimension.
:param dim_out: output dimension.
:param w0: initial weight.
:param c: parameter to distribute the weights uniformly so that after sine activation the input is
arcsine-distributed.
:param is_first: boolean to check if it's the first layer.
"""
super().__init__()
self.dim_in = dim_in
self.is_first = is_first
weight = torch.zeros(dim_out, dim_in)
bias = torch.zeros(dim_out)
self.initialization(weight, bias, c=c, w0=w0)
self.weight = nn.Parameter(weight)
self.bias = nn.Parameter(bias)
self.activation = Sine(w0)
def initialization(self, weight, bias, c, w0):
dim = self.dim_in
w_std = 1 / dim if self.is_first else math.sqrt(c / dim) / w0
weight.uniform_(-w_std, w_std)
if bias is not None:
bias.uniform_(-w_std, w_std)
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]
|
FinbarArgus/phynn
|
Siren
| false
| 2,250
|
[
"Apache-2.0"
] | 0
|
436bfd6fa4ad86692bf12b4f76c92bc177626c40
|
https://github.com/FinbarArgus/phynn/tree/436bfd6fa4ad86692bf12b4f76c92bc177626c40
|
ResBlock
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
class AdaptiveInstanceNorm2d(nn.Module):
def __init__(self, num_features, eps=1e-05, momentum=0.1):
super(AdaptiveInstanceNorm2d, self).__init__()
self.num_features = num_features
self.eps = eps
self.momentum = momentum
self.weight = None
self.bias = None
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
def forward(self, x):
assert self.weight is not None and self.bias is not None, 'Please assign weight and bias before calling AdaIN!'
b, c = x.size(0), x.size(1)
running_mean = self.running_mean.repeat(b)
running_var = self.running_var.repeat(b)
x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:])
out = F.batch_norm(x_reshaped, running_mean, running_var, self.
weight, self.bias, True, self.momentum, self.eps)
return out.view(b, c, *x.size()[2:])
def __repr__(self):
return self.__class__.__name__ + '(' + str(self.num_features) + ')'
class ResBlock(nn.Module):
def __init__(self, dim, norm='in', activation='relu', pad_type='zero'):
super(ResBlock, self).__init__()
padding = 1
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'replicate':
self.pad = nn.ReplicationPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, 'Unsupported padding type: {}'.format(pad_type)
self.conv1 = nn.Conv2d(dim, dim, 3, 1, bias=True)
if norm == 'in':
self.norm1 = nn.InstanceNorm2d(dim)
elif norm == 'adain':
self.norm1 = AdaptiveInstanceNorm2d(dim)
self.relu1 = nn.LeakyReLU(0.2, inplace=True)
self.conv2 = nn.Conv2d(dim, dim, 3, 1, bias=True)
if norm == 'in':
self.norm2 = nn.InstanceNorm2d(dim)
elif norm == 'adain':
self.norm2 = AdaptiveInstanceNorm2d(dim)
def forward(self, x):
residual = x
x = self.conv1(self.pad(x))
x = self.norm1(x)
x = self.relu1(x)
x = self.conv2(self.pad(x))
out = self.norm2(x)
out += residual
return out
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.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 6 % 6
x0 = xindex % 6
x2 = xindex // 36
x4 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -1 + x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask,
other=0.0)
tl.store(out_ptr0 + x4, tmp11, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_convolution_1(in_out_ptr0,
in_out_ptr1, 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)
r2 = rindex
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tl.where(xmask, tmp3, 0)
tmp6 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 16.0
tmp20 = tmp18 / tmp19
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(in_out_ptr0 + (r2 + 16 * x3), tmp2, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp23, xmask)
tl.store(out_ptr0 + x3, tmp12, xmask)
@triton.jit
def triton_poi_fused_constant_pad_nd_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 6 % 6
x0 = xindex % 6
x2 = xindex // 36
x4 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -1 + x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask,
other=0.0)
tmp12 = tl.load(in_ptr1 + x2, tmp10 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp13 = tmp11 - tmp12
tmp14 = tl.load(in_ptr2 + x2, tmp10 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tmp13 * tmp14
tmp16 = 0.0
tmp17 = tmp15 > tmp16
tmp18 = 0.2
tmp19 = tmp15 * tmp18
tmp20 = tl.where(tmp17, tmp15, tmp19)
tmp21 = tl.full(tmp20.shape, 0.0, tmp20.dtype)
tmp22 = tl.where(tmp10, tmp20, tmp21)
tl.store(out_ptr0 + x4, tmp22, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_convolution_3(in_out_ptr0,
in_ptr0, in_ptr1, 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)
r2 = rindex
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr1 + (r2 + 16 * x3), xmask, other=0.0)
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tl.where(xmask, tmp3, 0)
tmp6 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = tmp2 - tmp12
tmp20 = 16.0
tmp21 = tmp18 / tmp20
tmp22 = 1e-05
tmp23 = tmp21 + tmp22
tmp24 = libdevice.rsqrt(tmp23)
tmp25 = tmp19 * tmp24
tmp27 = tmp25 + tmp26
tl.store(in_out_ptr0 + (r2 + 16 * x3), tmp2, xmask)
tl.store(out_ptr2 + (r2 + 16 * x3), tmp27, xmask)
tl.store(out_ptr3 + x3, tmp24, xmask)
tl.store(out_ptr0 + x3, tmp12, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 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 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(576)](primals_1, buf0, 576,
XBLOCK=256, num_warps=4, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf4 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf6 = reinterpret_tensor(buf4, (1, 16, 1, 1), (16, 1, 1, 1), 0)
del buf4
triton_per_fused__native_batch_norm_legit_convolution_1[grid(16)](buf2,
buf6, primals_3, buf3, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del primals_3
buf7 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
triton_poi_fused_constant_pad_nd_2[grid(576)](buf2, buf3, buf6,
buf7, 576, XBLOCK=128, num_warps=4, num_stages=1)
buf8 = extern_kernels.convolution(buf7, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 4, 4, 4), (64, 16, 4, 1))
buf9 = buf8
del buf8
buf10 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf13 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
triton_per_fused__native_batch_norm_legit_add_convolution_3[grid(16)](
buf9, primals_5, primals_1, buf10, buf14, buf13, 16, 16, XBLOCK
=1, num_warps=2, num_stages=1)
del primals_1
del primals_5
return (buf14, primals_2, primals_4, buf0, buf2, buf3, buf6, buf7, buf9,
reinterpret_tensor(buf13, (16,), (1,), 0), reinterpret_tensor(buf10,
(1, 16, 1, 1), (16, 1, 1, 1), 0))
class AdaptiveInstanceNorm2d(nn.Module):
def __init__(self, num_features, eps=1e-05, momentum=0.1):
super(AdaptiveInstanceNorm2d, self).__init__()
self.num_features = num_features
self.eps = eps
self.momentum = momentum
self.weight = None
self.bias = None
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
def forward(self, x):
assert self.weight is not None and self.bias is not None, 'Please assign weight and bias before calling AdaIN!'
b, c = x.size(0), x.size(1)
running_mean = self.running_mean.repeat(b)
running_var = self.running_var.repeat(b)
x_reshaped = x.contiguous().view(1, b * c, *x.size()[2:])
out = F.batch_norm(x_reshaped, running_mean, running_var, self.
weight, self.bias, True, self.momentum, self.eps)
return out.view(b, c, *x.size()[2:])
def __repr__(self):
return self.__class__.__name__ + '(' + str(self.num_features) + ')'
class ResBlockNew(nn.Module):
def __init__(self, dim, norm='in', activation='relu', pad_type='zero'):
super(ResBlockNew, self).__init__()
padding = 1
if pad_type == 'reflect':
self.pad = nn.ReflectionPad2d(padding)
elif pad_type == 'replicate':
self.pad = nn.ReplicationPad2d(padding)
elif pad_type == 'zero':
self.pad = nn.ZeroPad2d(padding)
else:
assert 0, 'Unsupported padding type: {}'.format(pad_type)
self.conv1 = nn.Conv2d(dim, dim, 3, 1, bias=True)
if norm == 'in':
self.norm1 = nn.InstanceNorm2d(dim)
elif norm == 'adain':
self.norm1 = AdaptiveInstanceNorm2d(dim)
self.relu1 = nn.LeakyReLU(0.2, inplace=True)
self.conv2 = nn.Conv2d(dim, dim, 3, 1, bias=True)
if norm == 'in':
self.norm2 = nn.InstanceNorm2d(dim)
elif norm == 'adain':
self.norm2 = AdaptiveInstanceNorm2d(dim)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
FUTUREEEEEE/S2R-DepthNet
|
ResBlock
| false
| 2,251
|
[
"MIT"
] | 0
|
415cc40aef10f9540026ff435d14a9ba9e30ad74
|
https://github.com/FUTUREEEEEE/S2R-DepthNet/tree/415cc40aef10f9540026ff435d14a9ba9e30ad74
|
UnpackLayerConv2d
|
import torch
import torch.nn as nn
class Conv2D(nn.Module):
"""
2D convolution with GroupNorm and ELU
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
kernel_size : int
Kernel size
stride : int
Stride
"""
def __init__(self, in_channels, out_channels, kernel_size, stride):
super().__init__()
self.kernel_size = kernel_size
self.conv_base = nn.Conv2d(in_channels, out_channels, kernel_size=
kernel_size, stride=stride)
self.pad = nn.ConstantPad2d([kernel_size // 2] * 4, value=0)
self.normalize = torch.nn.GroupNorm(16, out_channels)
self.activ = nn.ELU(inplace=True)
def forward(self, x):
"""Runs the Conv2D layer."""
x = self.conv_base(self.pad(x))
return self.activ(self.normalize(x))
class UnpackLayerConv2d(nn.Module):
"""
Unpacking layer with 2d convolutions. Takes a [B,C,H,W] tensor, convolves it
to produce [B,(r^2)C,H,W] and then unpacks it to produce [B,C,rH,rW].
"""
def __init__(self, in_channels, out_channels, kernel_size, r=2):
"""
Initializes a UnpackLayerConv2d object.
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
kernel_size : int
Kernel size
r : int
Packing ratio
"""
super().__init__()
self.conv = Conv2D(in_channels, out_channels * r ** 2, kernel_size, 1)
self.unpack = nn.PixelShuffle(r)
def forward(self, x):
"""Runs the UnpackLayerConv2d layer."""
x = self.conv(x)
x = self.unpack(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 8 % 8
x0 = xindex % 8
x2 = xindex // 64
x4 = xindex
tmp0 = -2 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -2 + x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (-10 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask,
other=0.0)
tl.store(out_ptr0 + x4, tmp11, xmask)
@triton.jit
def triton_per_fused_convolution_native_group_norm_pixel_shuffle_1(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 64
rnumel = 25
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
x3 = xindex
x0 = xindex % 16
r7 = rindex % 5
r8 = rindex // 5
x4 = xindex % 2
x5 = xindex // 2 % 2
x6 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + (r2 + 25 * x3), rmask & xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tl.where(rmask & xmask, tmp3, 0)
tmp6 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp8 = tl.where(rmask & xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 25, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(rmask & xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 25.0
tmp20 = tmp18 / tmp19
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tmp24 = tmp2 - tmp12
tmp25 = tmp24 * tmp23
tmp27 = tmp25 * tmp26
tmp29 = tmp27 + tmp28
tmp30 = 0.0
tmp31 = tmp29 > tmp30
tmp32 = 1.0
tmp33 = tmp29 * tmp32
tmp34 = libdevice.expm1(tmp33)
tmp35 = tmp34 * tmp32
tmp36 = tl.where(tmp31, tmp33, tmp35)
tl.store(in_out_ptr0 + (r2 + 25 * x3), tmp2, rmask & xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp23, xmask)
tl.store(out_ptr2 + (x4 + 2 * r7 + 10 * x5 + 20 * r8 + 100 * x6), tmp36,
rmask & xmask)
tl.store(out_ptr0 + x3, tmp12, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (16, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (16,), (1,))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (16,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(1024)](primals_1, buf0,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 16, 5, 5), (400, 25, 5, 1))
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf4 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 64, 64), torch.float32
)
buf6 = reinterpret_tensor(buf4, (4, 16, 1, 1), (16, 1, 1, 1), 0)
del buf4
buf8 = empty_strided_cuda((4, 4, 5, 2, 5, 2), (400, 100, 20, 10, 2,
1), torch.float32)
triton_per_fused_convolution_native_group_norm_pixel_shuffle_1[grid(64)
](buf2, buf6, primals_3, primals_4, primals_5, buf3, buf8, 64,
25, XBLOCK=1, num_warps=2, num_stages=1)
del primals_3
return reinterpret_tensor(buf8, (4, 4, 10, 10), (400, 100, 10, 1), 0
), primals_2, primals_4, primals_5, buf0, buf2, buf3, buf6
class Conv2D(nn.Module):
"""
2D convolution with GroupNorm and ELU
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
kernel_size : int
Kernel size
stride : int
Stride
"""
def __init__(self, in_channels, out_channels, kernel_size, stride):
super().__init__()
self.kernel_size = kernel_size
self.conv_base = nn.Conv2d(in_channels, out_channels, kernel_size=
kernel_size, stride=stride)
self.pad = nn.ConstantPad2d([kernel_size // 2] * 4, value=0)
self.normalize = torch.nn.GroupNorm(16, out_channels)
self.activ = nn.ELU(inplace=True)
def forward(self, x):
"""Runs the Conv2D layer."""
x = self.conv_base(self.pad(x))
return self.activ(self.normalize(x))
class UnpackLayerConv2dNew(nn.Module):
"""
Unpacking layer with 2d convolutions. Takes a [B,C,H,W] tensor, convolves it
to produce [B,(r^2)C,H,W] and then unpacks it to produce [B,C,rH,rW].
"""
def __init__(self, in_channels, out_channels, kernel_size, r=2):
"""
Initializes a UnpackLayerConv2d object.
Parameters
----------
in_channels : int
Number of input channels
out_channels : int
Number of output channels
kernel_size : int
Kernel size
r : int
Packing ratio
"""
super().__init__()
self.conv = Conv2D(in_channels, out_channels * r ** 2, kernel_size, 1)
self.unpack = nn.PixelShuffle(r)
def forward(self, input_0):
primals_2 = self.conv.conv_base.weight
primals_3 = self.conv.conv_base.bias
primals_4 = self.conv.normalize.weight
primals_5 = self.conv.normalize.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-
|
UnpackLayerConv2d
| false
| 2,252
|
[
"MIT"
] | 0
|
13fac05601efed16ae8b29989aad487e04cd90a7
|
https://github.com/Fatmangh/VIDEO-ACTION-CLASSIFICATION-USING-PRETAINED-SELF-SUPERVISED-DEPTH-AWARE-DENSE-PREDICTIVE-CODING-/tree/13fac05601efed16ae8b29989aad487e04cd90a7
|
DAInsHead
|
import torch
import torch.utils.data
import torch.nn.functional as F
from torch import nn
class DAInsHead(nn.Module):
"""
Adds a simple Instance-level Domain Classifier head
"""
def __init__(self, in_channels):
"""
Arguments:
in_channels (int): number of channels of the input feature
"""
super(DAInsHead, self).__init__()
self.fc1_da = nn.Linear(in_channels, 1024)
self.fc2_da = nn.Linear(1024, 1024)
self.fc3_da = nn.Linear(1024, 1)
for l in [self.fc1_da, self.fc2_da]:
nn.init.normal_(l.weight, std=0.01)
nn.init.constant_(l.bias, 0)
nn.init.normal_(self.fc3_da.weight, std=0.05)
nn.init.constant_(self.fc3_da.bias, 0)
def forward(self, x):
x = F.relu(self.fc1_da(x))
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu(self.fc2_da(x))
x = F.dropout(x, p=0.5, training=self.training)
x = self.fc3_da(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_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, (1, 1024), (1024, 1))
assert_size_stride(primals_7, (1,), (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
buf7 = 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, buf7, 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
buf6 = 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, buf6, 65536, XBLOCK=512, 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, 1024),
(1024, 1), 0), reinterpret_tensor(primals_6, (1024, 1), (1,
1024), 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, 1024), (1024, 1), 0
), reinterpret_tensor(buf3, (64, 1024), (1024, 1), 0
), primals_6, buf6, primals_4, buf7
class DAInsHeadNew(nn.Module):
"""
Adds a simple Instance-level Domain Classifier head
"""
def __init__(self, in_channels):
"""
Arguments:
in_channels (int): number of channels of the input feature
"""
super(DAInsHeadNew, self).__init__()
self.fc1_da = nn.Linear(in_channels, 1024)
self.fc2_da = nn.Linear(1024, 1024)
self.fc3_da = nn.Linear(1024, 1)
for l in [self.fc1_da, self.fc2_da]:
nn.init.normal_(l.weight, std=0.01)
nn.init.constant_(l.bias, 0)
nn.init.normal_(self.fc3_da.weight, std=0.05)
nn.init.constant_(self.fc3_da.bias, 0)
def forward(self, input_0):
primals_1 = self.fc1_da.weight
primals_2 = self.fc1_da.bias
primals_4 = self.fc2_da.weight
primals_5 = self.fc2_da.bias
primals_6 = self.fc3_da.weight
primals_7 = self.fc3_da.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
Feobi1999/unbiased-teacher
|
DAInsHead
| false
| 2,254
|
[
"MIT"
] | 0
|
9baacec16833bdff0dc089057e50903a92c700cb
|
https://github.com/Feobi1999/unbiased-teacher/tree/9baacec16833bdff0dc089057e50903a92c700cb
|
Network
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self, input_size, nb_action):
super(Network, self).__init__()
self.input_size = input_size
self.nb_action = nb_action
self.fc1 = nn.Linear(input_size, 30)
self.fc2 = nn.Linear(30, nb_action)
def forward(self, state):
x = F.relu(self.fc1(state))
q_values = self.fc2(x)
return q_values
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'nb_action': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1920
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 30
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 = args
args.clear()
assert_size_stride(primals_1, (30, 4), (4, 1))
assert_size_stride(primals_2, (30,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 30), (30, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 30), (30, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 30), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 30), (480, 120, 30, 1), 0)
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 30), (480, 120, 30, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(1920)](buf1,
primals_2, buf3, 1920, XBLOCK=256, 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, 30),
(30, 1), 0), reinterpret_tensor(primals_4, (30, 4), (1, 30), 0),
alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 30), (30, 1), 0), primals_4, buf3
class NetworkNew(nn.Module):
def __init__(self, input_size, nb_action):
super(NetworkNew, self).__init__()
self.input_size = input_size
self.nb_action = nb_action
self.fc1 = nn.Linear(input_size, 30)
self.fc2 = nn.Linear(30, nb_action)
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]
|
Flames-LLC/GX-V1NLPModule
|
Network
| false
| 2,255
|
[
"MIT"
] | 0
|
85e656c02269e57384b6e67ab4e4bceef4feb92e
|
https://github.com/Flames-LLC/GX-V1NLPModule/tree/85e656c02269e57384b6e67ab4e4bceef4feb92e
|
FocalLoss
|
import torch
import torch.utils.data
import torch.nn.functional as F
from torch import nn
class FocalLoss(nn.Module):
def __init__(self, weight=None, gamma=1.0, num_classes=80):
super(FocalLoss, self).__init__()
assert gamma >= 0
self.gamma = gamma
self.weight = weight
self.num_classes = num_classes
def forward(self, input, target):
CE = F.cross_entropy(input, target, reduction='none')
p = torch.exp(-CE)
loss = (1 - p) ** self.gamma * CE
return loss.sum()
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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_exp_mul_neg_pow_rsub_sum_1(in_ptr0,
in_ptr1, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp13 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp20 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp24 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp1 = tl_math.exp(tmp0)
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 + tmp3
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp4 + tmp6
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp0 - tmp11
tmp14 = tmp12 * tmp13
tmp15 = tmp2 - tmp11
tmp17 = tmp15 * tmp16
tmp18 = tmp14 + tmp17
tmp19 = tmp5 - tmp11
tmp21 = tmp19 * tmp20
tmp22 = tmp18 + tmp21
tmp23 = tmp8 - tmp11
tmp25 = tmp23 * tmp24
tmp26 = tmp22 + tmp25
tmp27 = -tmp26
tmp28 = -tmp27
tmp29 = tl_math.exp(tmp28)
tmp30 = 1.0
tmp31 = tmp30 - tmp29
tmp32 = tmp31 * tmp27
tmp33 = tl.broadcast_to(tmp32, [XBLOCK, RBLOCK])
tmp35 = tl.sum(tmp33, 1)[:, None]
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp35, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((), (), torch.float32)
triton_per_fused__log_softmax_exp_mul_neg_pow_rsub_sum_1[grid(1)](buf0,
arg0_1, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class FocalLossNew(nn.Module):
def __init__(self, weight=None, gamma=1.0, num_classes=80):
super(FocalLossNew, self).__init__()
assert gamma >= 0
self.gamma = gamma
self.weight = weight
self.num_classes = num_classes
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Feobi1999/unbiased-teacher
|
FocalLoss
| false
| 2,256
|
[
"MIT"
] | 0
|
9baacec16833bdff0dc089057e50903a92c700cb
|
https://github.com/Feobi1999/unbiased-teacher/tree/9baacec16833bdff0dc089057e50903a92c700cb
|
RankingLoss
|
import torch
from abc import abstractmethod
import torch.utils.data.dataloader
import torch.nn.functional as F
import torch.nn as nn
import torch.nn
class SimilarityLoss(nn.Module):
def __init__(self):
super(SimilarityLoss, self).__init__()
@abstractmethod
def forward(self, inputs, targets):
pass
class RankingLoss(SimilarityLoss):
"""
Triplet ranking loss between pair similarities and pair labels.
"""
def __init__(self, margin=0.1, direction_weights=[0.5, 0.5]):
super(RankingLoss, self).__init__()
self.margin = margin
self.direction_weights = direction_weights
def forward(self, inputs, targets):
n = inputs.shape[0]
neg_targets = torch.ones_like(targets) - targets
ranking_loss_matrix_01 = neg_targets * F.relu(self.margin + inputs -
torch.diag(inputs).view(n, 1))
ranking_loss_matrix_10 = neg_targets * F.relu(self.margin + inputs -
torch.diag(inputs).view(1, n))
neg_targets_01_sum = torch.sum(neg_targets, dim=1)
neg_targets_10_sum = torch.sum(neg_targets, dim=0)
loss = self.direction_weights[0] * torch.mean(torch.sum(
ranking_loss_matrix_01 / neg_targets_01_sum, dim=1)
) + self.direction_weights[1] * torch.mean(torch.sum(
ranking_loss_matrix_10 / neg_targets_10_sum, dim=0))
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from abc import abstractmethod
import torch.utils.data.dataloader
import torch.nn as nn
import torch.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_mul_ones_like_relu_sub_sum_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 * r0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + 5 * r0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + 0)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr0 + 1)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp18 = tl.load(in_ptr0 + 2)
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp22 = tl.load(in_ptr0 + 3)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK, RBLOCK])
tmp27 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp29 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr0 + 4)
tmp35 = tl.broadcast_to(tmp34, [XBLOCK, RBLOCK])
tmp37 = tl.load(in_ptr0 + 5)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp41 = tl.load(in_ptr0 + 6)
tmp42 = tl.broadcast_to(tmp41, [XBLOCK, RBLOCK])
tmp45 = tl.load(in_ptr0 + 7)
tmp46 = tl.broadcast_to(tmp45, [XBLOCK, RBLOCK])
tmp51 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp53 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp58 = tl.load(in_ptr0 + 8)
tmp59 = tl.broadcast_to(tmp58, [XBLOCK, RBLOCK])
tmp61 = tl.load(in_ptr0 + 9)
tmp62 = tl.broadcast_to(tmp61, [XBLOCK, RBLOCK])
tmp65 = tl.load(in_ptr0 + 10)
tmp66 = tl.broadcast_to(tmp65, [XBLOCK, RBLOCK])
tmp69 = tl.load(in_ptr0 + 11)
tmp70 = tl.broadcast_to(tmp69, [XBLOCK, RBLOCK])
tmp75 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp77 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp82 = tl.load(in_ptr0 + 12)
tmp83 = tl.broadcast_to(tmp82, [XBLOCK, RBLOCK])
tmp85 = tl.load(in_ptr0 + 13)
tmp86 = tl.broadcast_to(tmp85, [XBLOCK, RBLOCK])
tmp89 = tl.load(in_ptr0 + 14)
tmp90 = tl.broadcast_to(tmp89, [XBLOCK, RBLOCK])
tmp93 = tl.load(in_ptr0 + 15)
tmp94 = tl.broadcast_to(tmp93, [XBLOCK, RBLOCK])
tmp99 = tl.load(in_ptr0 + r0, None)
tmp101 = tl.load(in_ptr1 + r0, None)
tmp106 = tl.load(in_ptr0 + (4 + r0), None)
tmp109 = tl.load(in_ptr0 + (8 + r0), None)
tmp112 = tl.load(in_ptr0 + (12 + r0), None)
tmp116 = tl.load(in_ptr1 + (4 + r0), None)
tmp123 = tl.load(in_ptr1 + (8 + r0), None)
tmp130 = tl.load(in_ptr1 + (12 + r0), None)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = 0.1
tmp5 = tmp3 + tmp4
tmp7 = tmp5 - tmp6
tmp8 = tl.full([1, 1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tmp2 * tmp9
tmp13 = tmp1 - tmp12
tmp16 = tmp1 - tmp15
tmp17 = tmp13 + tmp16
tmp20 = tmp1 - tmp19
tmp21 = tmp17 + tmp20
tmp24 = tmp1 - tmp23
tmp25 = tmp21 + tmp24
tmp26 = tmp10 / tmp25
tmp28 = tmp1 - tmp27
tmp30 = tmp29 + tmp4
tmp31 = tmp30 - tmp6
tmp32 = triton_helpers.maximum(tmp8, tmp31)
tmp33 = tmp28 * tmp32
tmp36 = tmp1 - tmp35
tmp39 = tmp1 - tmp38
tmp40 = tmp36 + tmp39
tmp43 = tmp1 - tmp42
tmp44 = tmp40 + tmp43
tmp47 = tmp1 - tmp46
tmp48 = tmp44 + tmp47
tmp49 = tmp33 / tmp48
tmp50 = tmp26 + tmp49
tmp52 = tmp1 - tmp51
tmp54 = tmp53 + tmp4
tmp55 = tmp54 - tmp6
tmp56 = triton_helpers.maximum(tmp8, tmp55)
tmp57 = tmp52 * tmp56
tmp60 = tmp1 - tmp59
tmp63 = tmp1 - tmp62
tmp64 = tmp60 + tmp63
tmp67 = tmp1 - tmp66
tmp68 = tmp64 + tmp67
tmp71 = tmp1 - tmp70
tmp72 = tmp68 + tmp71
tmp73 = tmp57 / tmp72
tmp74 = tmp50 + tmp73
tmp76 = tmp1 - tmp75
tmp78 = tmp77 + tmp4
tmp79 = tmp78 - tmp6
tmp80 = triton_helpers.maximum(tmp8, tmp79)
tmp81 = tmp76 * tmp80
tmp84 = tmp1 - tmp83
tmp87 = tmp1 - tmp86
tmp88 = tmp84 + tmp87
tmp91 = tmp1 - tmp90
tmp92 = tmp88 + tmp91
tmp95 = tmp1 - tmp94
tmp96 = tmp92 + tmp95
tmp97 = tmp81 / tmp96
tmp98 = tmp74 + tmp97
tmp100 = tmp1 - tmp99
tmp102 = tmp101 + tmp4
tmp103 = tmp102 - tmp6
tmp104 = triton_helpers.maximum(tmp8, tmp103)
tmp105 = tmp100 * tmp104
tmp107 = tmp1 - tmp106
tmp108 = tmp100 + tmp107
tmp110 = tmp1 - tmp109
tmp111 = tmp108 + tmp110
tmp113 = tmp1 - tmp112
tmp114 = tmp111 + tmp113
tmp115 = tmp105 / tmp114
tmp117 = tmp116 + tmp4
tmp118 = tmp117 - tmp6
tmp119 = triton_helpers.maximum(tmp8, tmp118)
tmp120 = tmp107 * tmp119
tmp121 = tmp120 / tmp114
tmp122 = tmp115 + tmp121
tmp124 = tmp123 + tmp4
tmp125 = tmp124 - tmp6
tmp126 = triton_helpers.maximum(tmp8, tmp125)
tmp127 = tmp110 * tmp126
tmp128 = tmp127 / tmp114
tmp129 = tmp122 + tmp128
tmp131 = tmp130 + tmp4
tmp132 = tmp131 - tmp6
tmp133 = triton_helpers.maximum(tmp8, tmp132)
tmp134 = tmp113 * tmp133
tmp135 = tmp134 / tmp114
tmp136 = tmp129 + tmp135
tmp137 = tl.broadcast_to(tmp98, [XBLOCK, RBLOCK])
tmp139 = tl.sum(tmp137, 1)[:, None]
tmp140 = tl.broadcast_to(tmp136, [XBLOCK, RBLOCK])
tmp142 = tl.sum(tmp140, 1)[:, None]
tmp143 = 4.0
tmp144 = tmp139 / tmp143
tmp145 = 0.5
tmp146 = tmp144 * tmp145
tmp147 = tmp142 / tmp143
tmp148 = tmp147 * tmp145
tmp149 = tmp146 + tmp148
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp149, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf4 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_div_mean_mul_ones_like_relu_sub_sum_0[grid(1)](
buf4, arg1_1, arg0_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf4,
class SimilarityLoss(nn.Module):
def __init__(self):
super(SimilarityLoss, self).__init__()
@abstractmethod
def forward(self, inputs, targets):
pass
class RankingLossNew(SimilarityLoss):
"""
Triplet ranking loss between pair similarities and pair labels.
"""
def __init__(self, margin=0.1, direction_weights=[0.5, 0.5]):
super(RankingLossNew, self).__init__()
self.margin = margin
self.direction_weights = direction_weights
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
FranziskaKuhls/flair
|
RankingLoss
| false
| 2,257
|
[
"MIT"
] | 0
|
2bd9e72c961651c7c020076cb8fd80cbbb36da7c
|
https://github.com/FranziskaKuhls/flair/tree/2bd9e72c961651c7c020076cb8fd80cbbb36da7c
|
KeyValueAttention
|
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.utils.data
import torch.nn.init
class KeyValueAttention(nn.Module):
def __init__(self, query_size, key_size, value_size, hid_size, init_range):
super(KeyValueAttention, self).__init__()
self.key2hid = nn.Linear(key_size, hid_size)
self.query2hid = nn.Linear(query_size, hid_size)
self.hid2output = nn.Linear(hid_size, 1)
self.key2hid.weight.data.uniform_(-init_range, init_range)
self.key2hid.bias.data.fill_(0)
self.query2hid.weight.data.uniform_(-init_range, init_range)
self.query2hid.bias.data.fill_(0)
self.hid2output.weight.data.uniform_(-init_range, init_range)
self.hid2output.bias.data.fill_(0)
def _bottle(self, linear, x):
y = linear(x.view(-1, x.size(-1)))
return y.view(x.size(0), x.size(1), -1)
def forward_attn(self, h):
logit = self.attn(h.view(-1, h.size(2))).view(h.size(0), h.size(1))
return logit
def forward(self, q, k, v, mask=None):
k = k.transpose(0, 1).contiguous()
v = v.transpose(0, 1).contiguous()
h_k = self._bottle(self.key2hid, k)
h_q = self.query2hid(q)
h = F.tanh(h_k + h_q.unsqueeze(1).expand_as(h_k))
logit = self._bottle(self.hid2output, h).squeeze(2)
logit = logit.sub(logit.max(1, keepdim=True)[0].expand_as(logit))
if mask is not None:
logit = torch.add(logit, Variable(mask))
p = F.softmax(logit)
w = p.unsqueeze(2).expand_as(v)
h = torch.sum(torch.mul(v, w), 1, keepdim=True)
h = h.transpose(0, 1).contiguous()
return h, p
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'query_size': 4, 'key_size': 4, 'value_size': 4,
'hid_size': 4, 'init_range': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.utils.data
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_clone_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 % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_tanh_1(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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = libdevice.tanh(tmp6)
tl.store(in_out_ptr0 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_max_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp32 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 > tmp1
tmp3 = tmp0 == tmp1
tmp4 = tmp0 != tmp0
tmp5 = tmp1 != tmp1
tmp6 = tmp4 > tmp5
tmp7 = tmp2 | tmp6
tmp8 = tmp4 & tmp5
tmp9 = tmp3 | tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = tl.full([1], 1, tl.int64)
tmp12 = tmp10 < tmp11
tmp13 = tmp9 & tmp12
tmp14 = tmp7 | tmp13
tmp15 = tl.where(tmp14, tmp0, tmp1)
tmp16 = tl.where(tmp14, tmp10, tmp11)
tmp18 = tmp15 > tmp17
tmp19 = tmp15 == tmp17
tmp20 = tmp15 != tmp15
tmp21 = tmp17 != tmp17
tmp22 = tmp20 > tmp21
tmp23 = tmp18 | tmp22
tmp24 = tmp20 & tmp21
tmp25 = tmp19 | tmp24
tmp26 = tl.full([1], 2, tl.int64)
tmp27 = tmp16 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tmp23 | tmp28
tmp30 = tl.where(tmp29, tmp15, tmp17)
tmp31 = tl.where(tmp29, tmp16, tmp26)
tmp33 = tmp30 > tmp32
tmp34 = tmp30 == tmp32
tmp35 = tmp30 != tmp30
tmp36 = tmp32 != tmp32
tmp37 = tmp35 > tmp36
tmp38 = tmp33 | tmp37
tmp39 = tmp35 & tmp36
tmp40 = tmp34 | tmp39
tmp41 = tl.full([1], 3, tl.int64)
tmp42 = tmp31 < tmp41
tmp43 = tmp40 & tmp42
tmp44 = tmp38 | tmp43
tl.where(tmp44, tmp30, tmp32)
tmp46 = tl.where(tmp44, tmp31, tmp41)
tl.store(out_ptr0 + x0, tmp46, xmask)
@triton.jit
def triton_poi_fused_sub_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
tl.store(out_ptr0 + x2, tmp8, 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 = 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_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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_mul_sum_6(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x2), xmask)
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x2), xmask)
tmp8 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x2), xmask)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x2, tmp14, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = 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, 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,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (1, 4), (4, 1))
assert_size_stride(primals_9, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_7, reinterpret_tensor(primals_5, (4, 4),
(1, 4), 0), out=buf2)
del primals_5
buf3 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused_add_tanh_1[grid(64)](buf3, primals_4, buf2,
primals_6, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_4
del primals_6
buf5 = reinterpret_tensor(buf2, (16, 1), (1, 1), 0)
del buf2
extern_kernels.addmm(primals_9, reinterpret_tensor(buf3, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_8, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf5)
del primals_9
buf6 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused_max_2[grid(4)](buf5, buf6, 4, XBLOCK=4, num_warps=
1, num_stages=1)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_sub_3[grid(16)](buf5, buf7, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf5, (4, 4), (4, 1), 0)
del buf5
triton_poi_fused__softmax_4[grid(16)](buf7, buf8, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused__softmax_5[grid(16)](buf8, buf9, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf10 = reinterpret_tensor(buf8, (4, 1, 4), (4, 4, 1), 0)
del buf8
triton_poi_fused_clone_mul_sum_6[grid(16)](primals_2, buf9, buf10,
16, XBLOCK=16, num_warps=1, num_stages=1)
return reinterpret_tensor(buf10, (1, 4, 4), (4, 4, 1), 0
), buf9, primals_2, primals_7, reinterpret_tensor(buf0, (16, 4), (4,
1), 0), buf3, buf6, buf9, primals_8
class KeyValueAttentionNew(nn.Module):
def __init__(self, query_size, key_size, value_size, hid_size, init_range):
super(KeyValueAttentionNew, self).__init__()
self.key2hid = nn.Linear(key_size, hid_size)
self.query2hid = nn.Linear(query_size, hid_size)
self.hid2output = nn.Linear(hid_size, 1)
self.key2hid.weight.data.uniform_(-init_range, init_range)
self.key2hid.bias.data.fill_(0)
self.query2hid.weight.data.uniform_(-init_range, init_range)
self.query2hid.bias.data.fill_(0)
self.hid2output.weight.data.uniform_(-init_range, init_range)
self.hid2output.bias.data.fill_(0)
def _bottle(self, linear, x):
y = linear(x.view(-1, x.size(-1)))
return y.view(x.size(0), x.size(1), -1)
def forward_attn(self, h):
logit = self.attn(h.view(-1, h.size(2))).view(h.size(0), h.size(1))
return logit
def forward(self, input_0, input_1, input_2):
primals_3 = self.key2hid.weight
primals_4 = self.key2hid.bias
primals_5 = self.query2hid.weight
primals_6 = self.query2hid.bias
primals_8 = self.hid2output.weight
primals_9 = self.hid2output.bias
primals_7 = input_0
primals_1 = input_1
primals_2 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0], output[1]
|
ChrisGeishauser/ConvLab-2
|
KeyValueAttention
| false
| 2,258
|
[
"Apache-2.0"
] | 0
|
8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
https://github.com/ChrisGeishauser/ConvLab-2/tree/8f55d033c6e2453fdc092c4f504be3973a55e7ea
|
NodeAdaptiveEncoder
|
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
class NodeAdaptiveEncoder(nn.Module):
def __init__(self, num_features, dropout=0.5):
super(NodeAdaptiveEncoder, self).__init__()
self.fc = nn.Parameter(torch.zeros(size=(num_features, 1)))
nn.init.xavier_normal_(self.fc.data, gain=1.414)
self.bf = nn.Parameter(torch.zeros(size=(1,)))
self.dropout = torch.nn.Dropout(dropout)
def forward(self, x):
h = torch.mm(x, self.fc) + self.bf
h = F.sigmoid(h)
h = self.dropout(h)
return torch.where(x < 0, torch.zeros_like(x), x) + h * torch.where(
x > 0, torch.zeros_like(x), x)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'num_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_poi_fused_add_gt_lt_mul_sigmoid_where_zeros_like_0(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
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp1 = 0.0
tmp2 = tmp0 < tmp1
tmp3 = tl.where(tmp2, tmp1, tmp0)
tmp7 = tmp4 + tmp6
tmp8 = tl.sigmoid(tmp7)
tmp9 = tmp0 > tmp1
tmp10 = tl.where(tmp9, tmp1, tmp0)
tmp11 = tmp8 * tmp10
tmp12 = tmp3 + tmp11
tl.store(out_ptr0 + x2, tmp12, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 1), (1, 1))
assert_size_stride(primals_2, (4, 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, 1), (1, 1), torch.float32)
extern_kernels.mm(primals_2, primals_1, out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_gt_lt_mul_sigmoid_where_zeros_like_0[grid(16)](
primals_2, buf0, primals_3, buf1, 16, XBLOCK=16, num_warps=1,
num_stages=1)
return buf1, primals_2, primals_3, buf0
class NodeAdaptiveEncoderNew(nn.Module):
def __init__(self, num_features, dropout=0.5):
super(NodeAdaptiveEncoderNew, self).__init__()
self.fc = nn.Parameter(torch.zeros(size=(num_features, 1)))
nn.init.xavier_normal_(self.fc.data, gain=1.414)
self.bf = nn.Parameter(torch.zeros(size=(1,)))
self.dropout = torch.nn.Dropout(dropout)
def forward(self, input_0):
primals_1 = self.fc
primals_3 = self.bf
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Brickser/cogdl
|
NodeAdaptiveEncoder
| false
| 2,259
|
[
"MIT"
] | 0
|
3952dd11075634cc0f3b669996cfc780635ce026
|
https://github.com/Brickser/cogdl/tree/3952dd11075634cc0f3b669996cfc780635ce026
|
Wide
|
import math
import torch
from torch import Tensor
from torch import nn
class Wide(nn.Module):
"""Wide component
Linear model implemented via an Embedding layer connected to the output
neuron(s).
Parameters
-----------
wide_dim: int
size of the Embedding layer. `wide_dim` is the summation of all the
individual values for all the features that go through the wide
component. For example, if the wide component receives 2 features with
5 individual values each, `wide_dim = 10`
pred_dim: int
size of the ouput tensor containing the predictions
Attributes
-----------
wide_linear: :obj:`nn.Module`
the linear layer that comprises the wide branch of the model
Examples
--------
>>> import torch
>>> from pytorch_widedeep.models import Wide
>>> X = torch.empty(4, 4).random_(6)
>>> wide = Wide(wide_dim=X.unique().size(0), pred_dim=1)
>>> out = wide(X)
"""
def __init__(self, wide_dim: 'int', pred_dim: 'int'=1):
super(Wide, self).__init__()
self.wide_linear = nn.Embedding(wide_dim + 1, pred_dim, padding_idx=0)
self.bias = nn.Parameter(torch.zeros(pred_dim))
self._reset_parameters()
def _reset_parameters(self) ->None:
"""initialize Embedding and bias like nn.Linear. See `original
implementation
<https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear>`_.
"""
nn.init.kaiming_uniform_(self.wide_linear.weight, a=math.sqrt(5))
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.wide_linear.
weight)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, X: 'Tensor') ->Tensor:
"""Forward pass. Simply connecting the Embedding layer with the ouput
neuron(s)"""
out = self.wide_linear(X.long()).sum(dim=1) + self.bias
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'wide_dim': 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 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__to_copy_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0.to(tl.int64)
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_poi_fused_add_embedding_sum_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 % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp7 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp14 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp21 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp28 = tl.load(in_ptr2 + 0)
tmp29 = tl.broadcast_to(tmp28, [XBLOCK])
tmp1 = tl.full([XBLOCK], 5, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 5) | ~xmask,
'index out of bounds: 0 <= tmp4 < 5')
tmp6 = tl.load(in_ptr1 + tmp4, xmask, eviction_policy='evict_last')
tmp8 = tmp7 + tmp1
tmp9 = tmp7 < 0
tmp10 = tl.where(tmp9, tmp8, tmp7)
tl.device_assert((0 <= tmp10) & (tmp10 < 5) | ~xmask,
'index out of bounds: 0 <= tmp10 < 5')
tmp12 = tl.load(in_ptr1 + tmp10, xmask, eviction_policy='evict_last')
tmp13 = tmp6 + tmp12
tmp15 = tmp14 + tmp1
tmp16 = tmp14 < 0
tmp17 = tl.where(tmp16, tmp15, tmp14)
tl.device_assert((0 <= tmp17) & (tmp17 < 5) | ~xmask,
'index out of bounds: 0 <= tmp17 < 5')
tmp19 = tl.load(in_ptr1 + tmp17, xmask, eviction_policy='evict_last')
tmp20 = tmp13 + tmp19
tmp22 = tmp21 + tmp1
tmp23 = tmp21 < 0
tmp24 = tl.where(tmp23, tmp22, tmp21)
tl.device_assert((0 <= tmp24) & (tmp24 < 5) | ~xmask,
'index out of bounds: 0 <= tmp24 < 5')
tmp26 = tl.load(in_ptr1 + tmp24, xmask, eviction_policy='evict_last')
tmp27 = tmp20 + tmp26
tmp30 = tmp27 + tmp29
tl.store(out_ptr0 + x2, tmp30, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (5, 1), (1, 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.int64)
get_raw_stream(0)
triton_poi_fused__to_copy_0[grid(256)](primals_1, buf0, 256, XBLOCK
=256, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_add_embedding_sum_1[grid(64)](buf0, primals_2,
primals_3, buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
del primals_3
return buf1, buf0
class WideNew(nn.Module):
"""Wide component
Linear model implemented via an Embedding layer connected to the output
neuron(s).
Parameters
-----------
wide_dim: int
size of the Embedding layer. `wide_dim` is the summation of all the
individual values for all the features that go through the wide
component. For example, if the wide component receives 2 features with
5 individual values each, `wide_dim = 10`
pred_dim: int
size of the ouput tensor containing the predictions
Attributes
-----------
wide_linear: :obj:`nn.Module`
the linear layer that comprises the wide branch of the model
Examples
--------
>>> import torch
>>> from pytorch_widedeep.models import Wide
>>> X = torch.empty(4, 4).random_(6)
>>> wide = Wide(wide_dim=X.unique().size(0), pred_dim=1)
>>> out = wide(X)
"""
def __init__(self, wide_dim: 'int', pred_dim: 'int'=1):
super(WideNew, self).__init__()
self.wide_linear = nn.Embedding(wide_dim + 1, pred_dim, padding_idx=0)
self.bias = nn.Parameter(torch.zeros(pred_dim))
self._reset_parameters()
def _reset_parameters(self) ->None:
"""initialize Embedding and bias like nn.Linear. See `original
implementation
<https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html#Linear>`_.
"""
nn.init.kaiming_uniform_(self.wide_linear.weight, a=math.sqrt(5))
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.wide_linear.
weight)
bound = 1 / math.sqrt(fan_in)
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input_0):
primals_3 = self.bias
primals_2 = self.wide_linear.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
FlyingWing/pytorch-widedeep
|
Wide
| false
| 2,260
|
[
"MIT"
] | 0
|
91a255d08bc9bdd5a05669465b7cf0313849ec9c
|
https://github.com/FlyingWing/pytorch-widedeep/tree/91a255d08bc9bdd5a05669465b7cf0313849ec9c
|
Classifier
|
import torch
import torch.utils.data
import torch.nn as nn
class Classifier(nn.Module):
def __init__(self, n_hid, n_out):
super(Classifier, self).__init__()
self.n_hid = n_hid
self.n_out = n_out
self.linear = nn.Linear(n_hid, n_out)
def forward(self, x):
tx = self.linear(x)
return torch.log_softmax(tx.squeeze(), dim=-1)
def __repr__(self):
return '{}(n_hid={}, n_out={})'.format(self.__class__.__name__,
self.n_hid, self.n_out)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_hid': 4, 'n_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
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
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
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 = 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 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__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_3, (64, 4), (4, 1), 0), buf2
class ClassifierNew(nn.Module):
def __init__(self, n_hid, n_out):
super(ClassifierNew, self).__init__()
self.n_hid = n_hid
self.n_out = n_out
self.linear = nn.Linear(n_hid, n_out)
def __repr__(self):
return '{}(n_hid={}, n_out={})'.format(self.__class__.__name__,
self.n_hid, self.n_out)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Brickser/cogdl
|
Classifier
| false
| 2,261
|
[
"MIT"
] | 0
|
3952dd11075634cc0f3b669996cfc780635ce026
|
https://github.com/Brickser/cogdl/tree/3952dd11075634cc0f3b669996cfc780635ce026
|
DistMultLayer
|
import torch
import torch.utils.data
import torch.nn as nn
class DistMultLayer(nn.Module):
def __init__(self):
super(DistMultLayer, self).__init__()
def forward(self, sub_emb, obj_emb, rel_emb):
return torch.sum(sub_emb * obj_emb * rel_emb, dim=-1)
def predict(self, sub_emb, obj_emb, rel_emb):
return torch.matmul(sub_emb * rel_emb, obj_emb.t())
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
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_poi_fused_mul_sum_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
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_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp4 = tmp2 * tmp3
tmp7 = tmp5 * tmp6
tmp9 = tmp7 * tmp8
tmp10 = tmp4 + tmp9
tmp13 = tmp11 * tmp12
tmp15 = tmp13 * tmp14
tmp16 = tmp10 + tmp15
tmp19 = tmp17 * tmp18
tmp21 = tmp19 * tmp20
tmp22 = tmp16 + tmp21
tl.store(out_ptr0 + x0, tmp22, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sum_0[grid(64)](arg0_1, arg1_1, arg2_1, buf0,
64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf0,
class DistMultLayerNew(nn.Module):
def __init__(self):
super(DistMultLayerNew, self).__init__()
def predict(self, sub_emb, obj_emb, rel_emb):
return torch.matmul(sub_emb * rel_emb, obj_emb.t())
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]
|
Brickser/cogdl
|
DistMultLayer
| false
| 2,262
|
[
"MIT"
] | 0
|
3952dd11075634cc0f3b669996cfc780635ce026
|
https://github.com/Brickser/cogdl/tree/3952dd11075634cc0f3b669996cfc780635ce026
|
StdConv2d
|
import torch
import torch.nn as 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-05)
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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_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-05
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]
|
GUOSHU-COOL/TransUNet
|
StdConv2d
| false
| 2,263
|
[
"Apache-2.0"
] | 0
|
6cb2c2f35eb6a571b12edbd095de5dda16c25015
|
https://github.com/GUOSHU-COOL/TransUNet/tree/6cb2c2f35eb6a571b12edbd095de5dda16c25015
|
clip_nonlinear
|
import torch
import torch.nn as nn
def quantize_a(x):
x = Q_A.apply(x)
return x
def fa(x, bitA):
if bitA == 32:
return x
return quantize_a(x)
class Q_A(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
out = x.new(x.size())
out[x > 0] = 1
out[x < 0] = -1
out[x == 0] = 0
return out
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
grad_input = grad_output.clone()
grad_input.masked_fill_(input > 1.0, 0.0)
grad_input.masked_fill_(input < -1.0, 0.0)
mask_pos = (input >= 0.0) & (input < 1.0)
mask_neg = (input < 0.0) & (input >= -1.0)
grad_input.masked_scatter_(mask_pos, input[mask_pos].mul_(-2.0).
add_(2.0))
grad_input.masked_scatter_(mask_neg, input[mask_neg].mul_(2.0).add_
(2.0))
return grad_input * grad_output
class clip_nonlinear(nn.Module):
def __init__(self, bitA):
super(clip_nonlinear, self).__init__()
self.bitA = bitA
def forward(self, input):
return fa(input, self.bitA)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'bitA': 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_poi_fused_index_put_lift_fresh_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 1.0
tmp4 = float('nan')
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tmp0 < tmp1
tmp7 = -1.0
tmp8 = tl.where(tmp6, tmp7, tmp5)
tmp9 = tmp0 == tmp1
tmp10 = tl.where(tmp9, tmp1, tmp8)
tl.store(in_out_ptr0 + x0, tmp10, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf2 = buf1
del buf1
buf3 = buf2
del buf2
get_raw_stream(0)
triton_poi_fused_index_put_lift_fresh_0[grid(256)](buf3, arg0_1,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf3,
def quantize_a(x):
x = Q_A.apply(x)
return x
def fa(x, bitA):
if bitA == 32:
return x
return quantize_a(x)
class Q_A(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
out = x.new(x.size())
out[x > 0] = 1
out[x < 0] = -1
out[x == 0] = 0
return out
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
grad_input = grad_output.clone()
grad_input.masked_fill_(input > 1.0, 0.0)
grad_input.masked_fill_(input < -1.0, 0.0)
mask_pos = (input >= 0.0) & (input < 1.0)
mask_neg = (input < 0.0) & (input >= -1.0)
grad_input.masked_scatter_(mask_pos, input[mask_pos].mul_(-2.0).
add_(2.0))
grad_input.masked_scatter_(mask_neg, input[mask_neg].mul_(2.0).add_
(2.0))
return grad_input * grad_output
class clip_nonlinearNew(nn.Module):
def __init__(self, bitA):
super(clip_nonlinearNew, self).__init__()
self.bitA = bitA
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
GakkiChen/TWB-Net
|
clip_nonlinear
| false
| 2,264
|
[
"MIT"
] | 0
|
bb4917c697c09585bb3fe163a8b429b6dd250f18
|
https://github.com/GakkiChen/TWB-Net/tree/bb4917c697c09585bb3fe163a8b429b6dd250f18
|
GELU
|
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
class GELU(nn.Module):
"""
Paper Section 3.4, last paragraph notice that BERT used the GELU instead of RELU
"""
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x +
0.044715 * torch.pow(x, 3))))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
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_pow_tanh_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 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp7 * tmp8
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x0, tmp13, 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_mul_pow_tanh_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class GELUNew(nn.Module):
"""
Paper Section 3.4, last paragraph notice that BERT used the GELU instead of RELU
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
EddieMG/LateTemporalModeling3DCNN
|
GELU
| false
| 2,265
|
[
"MIT"
] | 0
|
94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
https://github.com/EddieMG/LateTemporalModeling3DCNN/tree/94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
ChannelPool
|
import torch
import torch.nn as nn
import torch.onnx
import torch.nn.parallel
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat((torch.max(x, 1)[0].unsqueeze(1), torch.mean(x, 1)
.unsqueeze(1)), dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.onnx
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 2
x0 = xindex % 16
x2 = xindex // 32
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 2, tl.int64)
tmp17 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp18 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp19 = tmp17 + tmp18
tmp20 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = tmp19 + tmp20
tmp22 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp23 = tmp21 + tmp22
tmp24 = 4.0
tmp25 = tmp23 / tmp24
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp14, tmp25, tmp26)
tmp28 = tl.where(tmp4, tmp13, tmp27)
tl.store(out_ptr0 + x3, tmp28, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(128)](arg0_1, buf0, 128, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ChannelPoolNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Ganzooo/soil_segmentation
|
ChannelPool
| false
| 2,266
|
[
"MIT"
] | 0
|
56f410e3e184f24e52dd4b542ea309f0d203ca00
|
https://github.com/Ganzooo/soil_segmentation/tree/56f410e3e184f24e52dd4b542ea309f0d203ca00
|
BERTEmbedding4
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
class LearnedPositionalEmbedding3(nn.Module):
def __init__(self, d_model, max_len=512):
super().__init__()
pe = torch.zeros(max_len, d_model).float()
self.a_2 = nn.Parameter(torch.ones_like(pe))
self.b_2 = nn.Parameter(torch.zeros_like(pe))
pe.require_grad = True
pe = pe.unsqueeze(0)
self.pe = nn.Parameter(pe)
torch.nn.init.normal_(self.pe, std=d_model ** -0.5)
def forward(self, x):
return self.a_2 * self.pe[:, :x.size(1)] + self.b_2
class BERTEmbedding4(nn.Module):
"""
BERT Embedding which is consisted with under features
1. PositionalEmbedding : adding positional information using sin, cos
sum of all these features are output of BERTEmbedding
"""
def __init__(self, input_dim, max_len, dropout=0.1):
"""
:param vocab_size: total vocab size
:param embed_size: embedding size of token embedding
:param dropout: dropout rate
"""
super().__init__()
self.learnedPosition = LearnedPositionalEmbedding3(d_model=
input_dim, max_len=max_len)
self.dropout = nn.Dropout(p=dropout)
def forward(self, sequence):
x = self.learnedPosition(sequence) + sequence
return self.dropout(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'max_len': 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.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, 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
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x2, xmask)
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tl.store(out_ptr0 + x2, tmp6, 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, (1, 4, 4), (16, 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((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(256)](primals_1, primals_2,
primals_4, primals_3, buf0, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_3
del primals_4
return buf0, primals_1, primals_2
class LearnedPositionalEmbedding3(nn.Module):
def __init__(self, d_model, max_len=512):
super().__init__()
pe = torch.zeros(max_len, d_model).float()
self.a_2 = nn.Parameter(torch.ones_like(pe))
self.b_2 = nn.Parameter(torch.zeros_like(pe))
pe.require_grad = True
pe = pe.unsqueeze(0)
self.pe = nn.Parameter(pe)
torch.nn.init.normal_(self.pe, std=d_model ** -0.5)
def forward(self, x):
return self.a_2 * self.pe[:, :x.size(1)] + self.b_2
class BERTEmbedding4New(nn.Module):
"""
BERT Embedding which is consisted with under features
1. PositionalEmbedding : adding positional information using sin, cos
sum of all these features are output of BERTEmbedding
"""
def __init__(self, input_dim, max_len, dropout=0.1):
"""
:param vocab_size: total vocab size
:param embed_size: embedding size of token embedding
:param dropout: dropout rate
"""
super().__init__()
self.learnedPosition = LearnedPositionalEmbedding3(d_model=
input_dim, max_len=max_len)
self.dropout = nn.Dropout(p=dropout)
def forward(self, input_0):
primals_1 = self.learnedPosition.a_2
primals_4 = self.learnedPosition.b_2
primals_2 = self.learnedPosition.pe
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
EddieMG/LateTemporalModeling3DCNN
|
BERTEmbedding4
| false
| 2,267
|
[
"MIT"
] | 0
|
94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
https://github.com/EddieMG/LateTemporalModeling3DCNN/tree/94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
BERTEmbedding3
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
class LearnedPositionalEmbedding(nn.Module):
def __init__(self, d_model, max_len=512):
super().__init__()
pe = torch.zeros(max_len, d_model).float()
pe.require_grad = True
pe = pe.unsqueeze(0)
self.pe = nn.Parameter(pe)
torch.nn.init.normal_(self.pe, std=d_model ** -0.5)
def forward(self, x):
return self.pe[:, :x.size(1)]
class BERTEmbedding3(nn.Module):
"""
BERT Embedding which is consisted with under features
1. PositionalEmbedding : adding positional information using sin, cos
sum of all these features are output of BERTEmbedding
"""
def __init__(self, input_dim, max_len, dropout=0.1):
"""
:param vocab_size: total vocab size
:param embed_size: embedding size of token embedding
:param dropout: dropout rate
"""
super().__init__()
self.learnedPosition = LearnedPositionalEmbedding(d_model=input_dim,
max_len=max_len)
self.dropout = nn.Dropout(p=dropout)
def forward(self, sequence):
x = self.learnedPosition(sequence) + sequence
return self.dropout(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'max_len': 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.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
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
x0 = xindex % 16
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, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](primals_1, primals_2, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
return buf0,
class LearnedPositionalEmbedding(nn.Module):
def __init__(self, d_model, max_len=512):
super().__init__()
pe = torch.zeros(max_len, d_model).float()
pe.require_grad = True
pe = pe.unsqueeze(0)
self.pe = nn.Parameter(pe)
torch.nn.init.normal_(self.pe, std=d_model ** -0.5)
def forward(self, x):
return self.pe[:, :x.size(1)]
class BERTEmbedding3New(nn.Module):
"""
BERT Embedding which is consisted with under features
1. PositionalEmbedding : adding positional information using sin, cos
sum of all these features are output of BERTEmbedding
"""
def __init__(self, input_dim, max_len, dropout=0.1):
"""
:param vocab_size: total vocab size
:param embed_size: embedding size of token embedding
:param dropout: dropout rate
"""
super().__init__()
self.learnedPosition = LearnedPositionalEmbedding(d_model=input_dim,
max_len=max_len)
self.dropout = nn.Dropout(p=dropout)
def forward(self, input_0):
primals_1 = self.learnedPosition.pe
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
EddieMG/LateTemporalModeling3DCNN
|
BERTEmbedding3
| false
| 2,268
|
[
"MIT"
] | 0
|
94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
https://github.com/EddieMG/LateTemporalModeling3DCNN/tree/94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
Network
|
import torch
import torch.nn as nn
class Network(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv3d(in_channels=1, out_channels=3, kernel_size=3)
def forward(self, x):
return self.conv(x)
def get_inputs():
return [torch.rand([4, 1, 64, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 2859936
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 238328 % 3
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (3, 1, 3, 3, 3), (27, 27, 9, 3, 1))
assert_size_stride(primals_2, (3,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64, 64), (262144, 262144, 4096,
64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1, 1), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 3, 62, 62, 62), (714984, 238328, 3844,
62, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(2859936)](buf1, primals_2,
2859936, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class NetworkNew(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv3d(in_channels=1, out_channels=3, kernel_size=3)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
GReguig/torchio
|
Network
| false
| 2,269
|
[
"Apache-2.0"
] | 0
|
0cd4f3105408410adda4fddf4873eb8c12883ecc
|
https://github.com/GReguig/torchio/tree/0cd4f3105408410adda4fddf4873eb8c12883ecc
|
DiceLoss
|
import torch
import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self, loss_weight=1.0):
super(DiceLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, input, target, mask, reduce=True):
batch_size = input.size(0)
input = torch.sigmoid(input)
input = input.contiguous().view(batch_size, -1)
target = target.contiguous().view(batch_size, -1).float()
mask = mask.contiguous().view(batch_size, -1).float()
input = input * mask
target = target * mask
a = torch.sum(input * target, dim=1)
b = torch.sum(input * input, dim=1) + 0.001
c = torch.sum(target * target, dim=1) + 0.001
d = 2 * a / (b + c)
loss = 1 - d
loss = self.loss_weight * loss
if reduce:
loss = torch.mean(loss)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mul_sum_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp2 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp4 = tl.load(in_ptr2 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp5 = tmp4 * tmp2
tmp6 = tmp3 * tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tmp3 * tmp3
tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
tmp14 = tl.where(xmask, tmp12, 0)
tmp15 = tl.sum(tmp14, 1)[:, None]
tmp16 = tmp5 * tmp5
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = tl.where(xmask, tmp17, 0)
tmp20 = tl.sum(tmp19, 1)[:, None]
tl.store(out_ptr0 + x0, tmp10, xmask)
tl.store(out_ptr1 + x0, tmp15, xmask)
tl.store(out_ptr2 + x0, tmp20, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_1(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp6 = tl.load(in_ptr2 + r0, None)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp4 = 0.001
tmp5 = tmp3 + tmp4
tmp7 = tmp6 + tmp4
tmp8 = tmp5 + tmp7
tmp9 = tmp2 / tmp8
tmp10 = 1.0
tmp11 = tmp10 - tmp9
tmp12 = tmp11 * tmp10
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.sum(tmp13, 1)[:, None]
tmp16 = 4.0
tmp17 = tmp15 / tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 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)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(4)](arg0_1, arg2_1, arg1_1, buf0,
buf1, buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
triton_per_fused_add_div_mean_mul_rsub_1[grid(1)](buf4, buf0, buf1,
buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf2
return buf4,
class DiceLossNew(nn.Module):
def __init__(self, loss_weight=1.0):
super(DiceLossNew, self).__init__()
self.loss_weight = loss_weight
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]
|
GaroneHuang/pan_pp.pytorch
|
DiceLoss
| false
| 2,270
|
[
"Apache-2.0"
] | 0
|
dde41ad652179433ad8a9650f671dc6742b783f9
|
https://github.com/GaroneHuang/pan_pp.pytorch/tree/dde41ad652179433ad8a9650f671dc6742b783f9
|
CMVN
|
import torch
import torch.nn as nn
class CMVN(nn.Module):
__constants__ = ['mode', 'dim', 'eps']
def __init__(self, mode='global', dim=2, eps=1e-10):
super(CMVN, self).__init__()
if mode != 'global':
raise NotImplementedError(
'Only support global mean variance normalization.')
self.mode = mode
self.dim = dim
self.eps = eps
def forward(self, x):
if self.mode == 'global':
return (x - x.mean(self.dim, keepdim=True)) / (self.eps + x.std
(self.dim, keepdim=True))
def extra_repr(self):
return 'mode={}, dim={}, eps={}'.format(self.mode, self.dim, self.eps)
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_add_div_mean_std_sub_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 % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tmp11 = tmp1 - tmp9
tmp12 = tmp11 * tmp11
tmp13 = tmp2 - tmp9
tmp14 = tmp13 * tmp13
tmp15 = tmp12 + tmp14
tmp16 = tmp4 - tmp9
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp19 = tmp6 - tmp9
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = 3.0
tmp23 = tmp21 / tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = 1e-10
tmp26 = tmp24 + tmp25
tmp27 = tmp10 / tmp26
tl.store(out_ptr0 + x3, tmp27, 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_mean_std_sub_0[grid(256)](arg0_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class CMVNNew(nn.Module):
__constants__ = ['mode', 'dim', 'eps']
def __init__(self, mode='global', dim=2, eps=1e-10):
super(CMVNNew, self).__init__()
if mode != 'global':
raise NotImplementedError(
'Only support global mean variance normalization.')
self.mode = mode
self.dim = dim
self.eps = eps
def extra_repr(self):
return 'mode={}, dim={}, eps={}'.format(self.mode, self.dim, self.eps)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Ethan07902050/s3prl
|
CMVN
| false
| 2,271
|
[
"MIT"
] | 0
|
854aff0b3062fc2cff531401923b8745f64701e7
|
https://github.com/Ethan07902050/s3prl/tree/854aff0b3062fc2cff531401923b8745f64701e7
|
Block
|
import torch
import torch.nn as nn
import torch.autograd
def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
'survival rate' as the argument.
"""
if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.
device)
random_tensor.floor_()
output = x.div(keep_prob) * random_tensor
return output
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training)
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None,
attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads
).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False,
qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn
.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias,
qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer, drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (4 + y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tmp14 * tmp1
tmp16 = tl_math.exp(tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused__softmax_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (8 + y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 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_native_layer_norm_8(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_9(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_gelu_10(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.7071067811865476
tmp4 = tmp0 * tmp3
tmp5 = libdevice.erf(tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_11(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
) = 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, (12, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (16, 4), (4, 1))
assert_size_stride(primals_10, (16,), (1,))
assert_size_stride(primals_11, (4, 16), (16, 1))
assert_size_stride(primals_12, (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, 12), (12, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 12), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_2[grid(16, 4)](buf3, buf4, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf3, buf5, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
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, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(256)](buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf6
triton_poi_fused__softmax_5[grid(256)](buf7, buf8, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_6[grid(16, 4)](buf3, buf9, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf3
buf10 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_7[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf11, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf12)
buf13 = buf1
del buf1
buf14 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_8[grid(16)](primals_3, buf12,
primals_6, buf13, buf14, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_9[grid(64)](primals_3, buf12,
primals_6, buf13, buf14, primals_7, primals_8, buf15, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf13
del buf14
del primals_8
buf16 = reinterpret_tensor(buf7, (16, 16), (16, 1), 0)
del buf7
extern_kernels.addmm(primals_10, reinterpret_tensor(buf15, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_9, (4, 16), (1, 4), 0),
alpha=1, beta=1, out=buf16)
del primals_10
buf17 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_gelu_10[grid(256)](buf16, buf17, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf18 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf17, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_11, (16, 4), (1, 16), 0), out=buf18)
buf19 = reinterpret_tensor(buf18, (4, 4, 4), (16, 4, 1), 0)
del buf18
triton_poi_fused_add_11[grid(64)](buf19, primals_3, buf12,
primals_6, primals_12, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_12
return buf19, primals_3, primals_6, primals_7, reinterpret_tensor(buf2,
(16, 4), (4, 1), 0), buf8, reinterpret_tensor(buf11, (16, 4), (4, 1), 0
), buf12, reinterpret_tensor(buf15, (16, 4), (4, 1), 0
), buf16, reinterpret_tensor(buf17, (16, 16), (16, 1), 0
), primals_11, primals_9, primals_5, reinterpret_tensor(buf9, (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_4
def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
'survival rate' as the argument.
"""
if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.
device)
random_tensor.floor_()
output = x.div(keep_prob) * random_tensor
return output
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training)
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None,
attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads
).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class BlockNew(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False,
qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn
.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias,
qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim,
act_layer=act_layer, drop=drop)
def forward(self, input_0):
primals_1 = self.norm1.weight
primals_2 = self.norm1.bias
primals_4 = self.attn.qkv.weight
primals_5 = self.attn.proj.weight
primals_6 = self.attn.proj.bias
primals_7 = self.norm2.weight
primals_8 = self.norm2.bias
primals_9 = self.mlp.fc1.weight
primals_10 = self.mlp.fc1.bias
primals_11 = self.mlp.fc2.weight
primals_12 = self.mlp.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
FelixWUS/TransReID
|
Block
| false
| 2,272
|
[
"MIT"
] | 0
|
9b0c6f30bd726677a4ce44450cb89427f05df9b1
|
https://github.com/FelixWUS/TransReID/tree/9b0c6f30bd726677a4ce44450cb89427f05df9b1
|
StableBCELoss
|
import torch
class StableBCELoss(torch.nn.modules.Module):
def __init__(self):
super(StableBCELoss, self).__init__()
def forward(self, input, target):
neg_abs = -input.abs()
loss = input.clamp(min=0) - input * target + (1 + neg_abs.exp()).log()
return loss.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_add_clamp_exp_log_mean_mul_neg_sub_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 0.0
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = tmp0 * tmp3
tmp5 = tmp2 - tmp4
tmp6 = tl_math.abs(tmp0)
tmp7 = -tmp6
tmp8 = tl_math.exp(tmp7)
tmp9 = 1.0
tmp10 = tmp8 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 + tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_abs_add_clamp_exp_log_mean_mul_neg_sub_0[grid(1)](buf1
, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class StableBCELossNew(torch.nn.modules.Module):
def __init__(self):
super(StableBCELossNew, 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]
|
GenoM87/hubmap
|
StableBCELoss
| false
| 2,273
|
[
"MIT"
] | 0
|
4acd11c373c6bb136ea9c6627a174ff02afa5986
|
https://github.com/GenoM87/hubmap/tree/4acd11c373c6bb136ea9c6627a174ff02afa5986
|
ConsinSimilarityLoss
|
import torch
import torch.nn as nn
class ConsinSimilarityLoss(nn.Module):
def __init__(self, dim: 'int'=1, eps: 'float'=1e-08, min_zero: 'bool'=True
):
super().__init__()
self.criterion = nn.CosineSimilarity(dim, eps)
self.min_zero = min_zero
def forward(self, output: 'torch.Tensor', target: 'torch.Tensor'):
cossim = self.criterion(output, target).mean()
if self.min_zero:
cossim = -cossim + 1
return cossim
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + x3, xmask)
tmp17 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-08
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp18 = tmp17 * tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = triton_helpers.maximum(tmp28, tmp13)
tmp30 = tmp16 / tmp29
tmp31 = tmp15 * tmp30
tl.store(out_ptr0 + x3, tmp31, xmask)
@triton.jit
def triton_per_fused_add_mean_neg_sum_1(in_out_ptr0, in_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp3 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp10 = 64.0
tmp11 = tmp9 / tmp10
tmp12 = -tmp11
tmp13 = 1.0
tmp14 = tmp12 + tmp13
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0[grid(256)](
arg1_1, arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_add_mean_neg_sum_1[grid(1)](buf2, buf0, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del buf0
return buf2,
class ConsinSimilarityLossNew(nn.Module):
def __init__(self, dim: 'int'=1, eps: 'float'=1e-08, min_zero: 'bool'=True
):
super().__init__()
self.criterion = nn.CosineSimilarity(dim, eps)
self.min_zero = min_zero
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Geson-anko/VQ_AutoEncoder
|
ConsinSimilarityLoss
| false
| 2,274
|
[
"MIT"
] | 0
|
62e1694de38ea6f152891e19abc190ad4048e587
|
https://github.com/Geson-anko/VQ_AutoEncoder/tree/62e1694de38ea6f152891e19abc190ad4048e587
|
SDNE_layer
|
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
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
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]
|
Brickser/cogdl
|
SDNE_layer
| false
| 2,275
|
[
"MIT"
] | 0
|
3952dd11075634cc0f3b669996cfc780635ce026
|
https://github.com/Brickser/cogdl/tree/3952dd11075634cc0f3b669996cfc780635ce026
|
MaxPool
|
import torch
import torch.utils.data
import torch.nn as nn
from torch import optim as optim
import torch.nn.parallel
class MaxPool(nn.Module):
def __init__(self, kernel_size, stride=1, padding=1, zero_pad=False):
super(MaxPool, self).__init__()
self.zero_pad = nn.ZeroPad2d((1, 0, 1, 0)) if zero_pad else None
self.pool = nn.MaxPool2d(kernel_size, stride=stride, padding=padding)
def forward(self, x):
if self.zero_pad:
x = self.zero_pad(x)
x = self.pool(x)
if self.zero_pad:
x = x[:, :, 1:, 1:]
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'kernel_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn as nn
from torch import optim as optim
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 3 % 3
x0 = xindex % 3
x2 = xindex // 9
x4 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask,
other=float('-inf'))
tmp12 = x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-4 + x0 + 4 * x1 + 16 * x2), tmp16 & xmask,
other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-3 + x0 + 4 * x1 + 16 * x2), tmp23 & xmask,
other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = 2 + x0
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp5 & tmp29
tmp31 = tl.load(in_ptr0 + (-2 + x0 + 4 * x1 + 16 * x2), tmp30 & xmask,
other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = x1
tmp34 = tmp33 >= tmp1
tmp35 = tmp33 < tmp3
tmp36 = tmp34 & tmp35
tmp37 = tmp36 & tmp9
tmp38 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1 + 16 * x2), tmp37 & xmask,
other=float('-inf'))
tmp39 = triton_helpers.maximum(tmp38, tmp32)
tmp40 = tmp36 & tmp15
tmp41 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp40 & xmask, other
=float('-inf'))
tmp42 = triton_helpers.maximum(tmp41, tmp39)
tmp43 = tmp36 & tmp22
tmp44 = tl.load(in_ptr0 + (1 + x0 + 4 * x1 + 16 * x2), tmp43 & xmask,
other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp42)
tmp46 = tmp36 & tmp29
tmp47 = tl.load(in_ptr0 + (2 + x0 + 4 * x1 + 16 * x2), tmp46 & xmask,
other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = 1 + x1
tmp50 = tmp49 >= tmp1
tmp51 = tmp49 < tmp3
tmp52 = tmp50 & tmp51
tmp53 = tmp52 & tmp9
tmp54 = tl.load(in_ptr0 + (3 + x0 + 4 * x1 + 16 * x2), tmp53 & xmask,
other=float('-inf'))
tmp55 = triton_helpers.maximum(tmp54, tmp48)
tmp56 = tmp52 & tmp15
tmp57 = tl.load(in_ptr0 + (4 + x0 + 4 * x1 + 16 * x2), tmp56 & xmask,
other=float('-inf'))
tmp58 = triton_helpers.maximum(tmp57, tmp55)
tmp59 = tmp52 & tmp22
tmp60 = tl.load(in_ptr0 + (5 + x0 + 4 * x1 + 16 * x2), tmp59 & xmask,
other=float('-inf'))
tmp61 = triton_helpers.maximum(tmp60, tmp58)
tmp62 = tmp52 & tmp29
tmp63 = tl.load(in_ptr0 + (6 + x0 + 4 * x1 + 16 * x2), tmp62 & xmask,
other=float('-inf'))
tmp64 = triton_helpers.maximum(tmp63, tmp61)
tmp65 = 2 + x1
tmp66 = tmp65 >= tmp1
tmp67 = tmp65 < tmp3
tmp68 = tmp66 & tmp67
tmp69 = tmp68 & tmp9
tmp70 = tl.load(in_ptr0 + (7 + x0 + 4 * x1 + 16 * x2), tmp69 & xmask,
other=float('-inf'))
tmp71 = triton_helpers.maximum(tmp70, tmp64)
tmp72 = tmp68 & tmp15
tmp73 = tl.load(in_ptr0 + (8 + x0 + 4 * x1 + 16 * x2), tmp72 & xmask,
other=float('-inf'))
tmp74 = triton_helpers.maximum(tmp73, tmp71)
tmp75 = tmp68 & tmp22
tmp76 = tl.load(in_ptr0 + (9 + x0 + 4 * x1 + 16 * x2), tmp75 & xmask,
other=float('-inf'))
tmp77 = triton_helpers.maximum(tmp76, tmp74)
tmp78 = tmp68 & tmp29
tmp79 = tl.load(in_ptr0 + (10 + x0 + 4 * x1 + 16 * x2), tmp78 & xmask,
other=float('-inf'))
tmp80 = triton_helpers.maximum(tmp79, tmp77)
tl.store(out_ptr0 + x4, tmp80, 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, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(144)](arg0_1, buf0,
144, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class MaxPoolNew(nn.Module):
def __init__(self, kernel_size, stride=1, padding=1, zero_pad=False):
super(MaxPoolNew, self).__init__()
self.zero_pad = nn.ZeroPad2d((1, 0, 1, 0)) if zero_pad else None
self.pool = nn.MaxPool2d(kernel_size, stride=stride, padding=padding)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Exir-lxr/crldr-prune-pytorch
|
MaxPool
| false
| 2,276
|
[
"Apache-2.0"
] | 0
|
adeb5e0b24ce66ff9531d4d947f72412c1b5c033
|
https://github.com/Exir-lxr/crldr-prune-pytorch/tree/adeb5e0b24ce66ff9531d4d947f72412c1b5c033
|
SelfAttentionPooling
|
import torch
import torch.nn as nn
class SelfAttentionPooling(nn.Module):
"""
Implementation of SelfAttentionPooling
Original Paper: Self-Attention Encoding and Pooling for Speaker Recognition
https://arxiv.org/pdf/2008.01077v1.pdf
"""
def __init__(self, input_dim):
super(SelfAttentionPooling, self).__init__()
self.W = nn.Linear(input_dim, 1)
def forward(self, batch_rep):
"""
input:
batch_rep : size (N, T, H), N: batch size, T: sequence length, H: Hidden dimension
attention_weight:
att_w : size (N, T, 1)
return:
utter_rep: size (N, H)
"""
softmax = nn.functional.softmax
att_w = softmax(self.W(batch_rep).squeeze(-1)).unsqueeze(-1)
utter_rep = torch.sum(batch_rep * att_w, dim=1)
return utter_rep
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask)
tmp1 = tl.load(in_ptr1 + (x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask)
tmp8 = tl.load(in_ptr1 + (8 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask)
tmp12 = tl.load(in_ptr1 + (12 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x4, tmp14, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_1
del primals_2
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = buf2
del buf2
triton_poi_fused_mul_sum_2[grid(64)](primals_3, buf3, buf4, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf3
return buf4, primals_3, buf1
class SelfAttentionPoolingNew(nn.Module):
"""
Implementation of SelfAttentionPooling
Original Paper: Self-Attention Encoding and Pooling for Speaker Recognition
https://arxiv.org/pdf/2008.01077v1.pdf
"""
def __init__(self, input_dim):
super(SelfAttentionPoolingNew, self).__init__()
self.W = nn.Linear(input_dim, 1)
def forward(self, input_0):
primals_1 = self.W.weight
primals_2 = self.W.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Ethan07902050/s3prl
|
SelfAttentionPooling
| false
| 2,277
|
[
"MIT"
] | 0
|
854aff0b3062fc2cff531401923b8745f64701e7
|
https://github.com/Ethan07902050/s3prl/tree/854aff0b3062fc2cff531401923b8745f64701e7
|
CossimLoss
|
import torch
import torch.nn as nn
class CossimLoss(nn.Module):
def __init__(self, dim: 'int'=1, eps: 'float'=1e-08):
super().__init__()
self.cos_sim = nn.CosineSimilarity(dim, eps)
def forward(self, output, target):
return -self.cos_sim(output, target).mean() + 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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + x3, xmask)
tmp17 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-08
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp18 = tmp17 * tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = triton_helpers.maximum(tmp28, tmp13)
tmp30 = tmp16 / tmp29
tmp31 = tmp15 * tmp30
tl.store(out_ptr0 + x3, tmp31, xmask)
@triton.jit
def triton_per_fused_add_mean_neg_sum_1(in_out_ptr0, in_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp3 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp10 = 64.0
tmp11 = tmp9 / tmp10
tmp12 = -tmp11
tmp13 = 1.0
tmp14 = tmp12 + tmp13
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0[grid(256)](
arg1_1, arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_add_mean_neg_sum_1[grid(1)](buf2, buf0, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del buf0
return buf2,
class CossimLossNew(nn.Module):
def __init__(self, dim: 'int'=1, eps: 'float'=1e-08):
super().__init__()
self.cos_sim = nn.CosineSimilarity(dim, eps)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Geson-anko/VQ_AutoEncoder
|
CossimLoss
| false
| 2,278
|
[
"MIT"
] | 0
|
62e1694de38ea6f152891e19abc190ad4048e587
|
https://github.com/Geson-anko/VQ_AutoEncoder/tree/62e1694de38ea6f152891e19abc190ad4048e587
|
MovingAverage
|
import torch
from torch import Tensor
import torch as pt
from torch import nn
class MovingAverage(nn.Module):
def __init__(self, cond_size: 'int', pred_size: 'int') ->None:
super().__init__()
self.left_window = cond_size // 2
self.right_window = cond_size - self.left_window
def forward(self, data: 'Tensor'):
smoothing = []
for step in range(data.size(1)):
left = max(step - self.left_window, 0)
right = min(step + self.right_window, data.size(1))
ma = data[:, left:right].sum(dim=1).div(right - left)
smoothing.append(ma)
smoothing = pt.stack(smoothing, dim=1)
residue = data - smoothing
return smoothing, residue
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'cond_size': 4, 'pred_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch 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_stack_sub_0(in_ptr0, out_ptr0, out_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 16
x0 = xindex % 4
x2 = xindex // 64
x3 = xindex
tmp54 = tl.load(in_ptr0 + x3, xmask)
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 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 4 * x1 + 64 * x2), tmp4 & xmask,
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = 0.5
tmp9 = tmp7 * tmp8
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tmp13 = tl.full([1], 8, tl.int64)
tmp14 = tmp0 < tmp13
tmp15 = tmp12 & tmp14
tmp16 = tl.load(in_ptr0 + (x0 + 4 * (-4 + x1) + 64 * x2), tmp15 & xmask,
other=0.0)
tmp17 = tl.load(in_ptr0 + (16 + x0 + 4 * (-4 + x1) + 64 * x2), tmp15 &
xmask, other=0.0)
tmp18 = tmp16 + tmp17
tmp19 = tl.load(in_ptr0 + (32 + x0 + 4 * (-4 + x1) + 64 * x2), tmp15 &
xmask, other=0.0)
tmp20 = tmp18 + tmp19
tmp21 = 0.3333333333333333
tmp22 = tmp20 * tmp21
tmp23 = tl.full(tmp22.shape, 0.0, tmp22.dtype)
tmp24 = tl.where(tmp15, tmp22, tmp23)
tmp25 = tmp0 >= tmp13
tmp26 = tl.full([1], 12, tl.int64)
tmp27 = tmp0 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tl.load(in_ptr0 + (x0 + 4 * (-8 + x1) + 64 * x2), tmp28 & xmask,
other=0.0)
tmp30 = tl.load(in_ptr0 + (16 + x0 + 4 * (-8 + x1) + 64 * x2), tmp28 &
xmask, other=0.0)
tmp31 = tmp29 + tmp30
tmp32 = tl.load(in_ptr0 + (32 + x0 + 4 * (-8 + x1) + 64 * x2), tmp28 &
xmask, other=0.0)
tmp33 = tmp31 + tmp32
tmp34 = tl.load(in_ptr0 + (48 + x0 + 4 * (-8 + x1) + 64 * x2), tmp28 &
xmask, other=0.0)
tmp35 = tmp33 + tmp34
tmp36 = 0.25
tmp37 = tmp35 * tmp36
tmp38 = tl.full(tmp37.shape, 0.0, tmp37.dtype)
tmp39 = tl.where(tmp28, tmp37, tmp38)
tmp40 = tmp0 >= tmp26
tl.full([1], 16, tl.int64)
tmp43 = tl.load(in_ptr0 + (16 + x0 + 4 * (-12 + x1) + 64 * x2), tmp40 &
xmask, other=0.0)
tmp44 = tl.load(in_ptr0 + (32 + x0 + 4 * (-12 + x1) + 64 * x2), tmp40 &
xmask, other=0.0)
tmp45 = tmp43 + tmp44
tmp46 = tl.load(in_ptr0 + (48 + x0 + 4 * (-12 + x1) + 64 * x2), tmp40 &
xmask, other=0.0)
tmp47 = tmp45 + tmp46
tmp48 = tmp47 * tmp21
tmp49 = tl.full(tmp48.shape, 0.0, tmp48.dtype)
tmp50 = tl.where(tmp40, tmp48, tmp49)
tmp51 = tl.where(tmp28, tmp39, tmp50)
tmp52 = tl.where(tmp15, tmp24, tmp51)
tmp53 = tl.where(tmp4, tmp11, tmp52)
tmp55 = tmp54 - tmp53
tl.store(out_ptr0 + x3, tmp53, xmask)
tl.store(out_ptr1 + x3, tmp55, 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, 4), (64, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_stack_sub_0[grid(256)](arg0_1, buf0, buf1, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0), buf1
class MovingAverageNew(nn.Module):
def __init__(self, cond_size: 'int', pred_size: 'int') ->None:
super().__init__()
self.left_window = cond_size // 2
self.right_window = cond_size - self.left_window
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1]
|
Gandor26/cacovid
|
MovingAverage
| false
| 2,279
|
[
"MIT"
] | 0
|
2b966579dba1eac6e33f439515de6de9e802d08a
|
https://github.com/Gandor26/cacovid/tree/2b966579dba1eac6e33f439515de6de9e802d08a
|
MaskNet
|
import torch
import torch.nn as nn
from itertools import product as product
class MaskNet(nn.Module):
def __init__(self):
super(MaskNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=
5, stride=1, padding=2)
self.relu1 = nn.ReLU()
self.Pool1 = nn.MaxPool2d(kernel_size=(2, 2), stride=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size
=3, stride=1, padding=1)
self.relu2 = nn.ReLU()
self.conv2s = nn.Conv2d(in_channels=32, out_channels=2, kernel_size
=1, stride=1, padding=0)
self.Pool2 = nn.MaxPool2d(kernel_size=(2, 2), stride=2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size
=(3, 3), stride=1, padding=1)
self.relu3 = nn.ReLU()
self.conv3s = nn.Conv2d(in_channels=64, out_channels=2, kernel_size
=1, stride=1, padding=0)
self.Pool3 = nn.MaxPool2d(kernel_size=(4, 4), stride=4)
self.conv4 = nn.Conv2d(in_channels=64, out_channels=128,
kernel_size=(3, 3), stride=1, padding=1)
self.relu4 = nn.ReLU()
self.conv4s = nn.Conv2d(in_channels=128, out_channels=2,
kernel_size=1, stride=1, padding=0)
self.Upsample1 = nn.ConvTranspose2d(in_channels=2, out_channels=2,
kernel_size=8, stride=4, padding=2, bias=False, groups=2)
self.Upsample2 = nn.ConvTranspose2d(in_channels=2, out_channels=2,
kernel_size=4, stride=2, padding=1, bias=False, groups=2)
self.Upsample3 = nn.ConvTranspose2d(in_channels=2, out_channels=2,
kernel_size=4, stride=2, padding=1, bias=False, groups=2)
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.Pool1(x)
x = self.conv2(x)
x = self.relu2(x)
branch1 = self.conv2s(x)
x = self.Pool2(x)
x = self.conv3(x)
x = self.relu3(x)
branch2 = self.conv3s(x)
x = self.Pool3(x)
x = self.conv4(x)
x = self.relu4(x)
x = self.conv4s(x)
branch3 = self.Upsample1(x)
branch_intermediate1 = branch2 + branch3
branch_intermediate2 = self.Upsample2(branch_intermediate1)
branch_intermediate3 = branch_intermediate2 + branch1
output = self.Upsample3(branch_intermediate3)
return output
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
from itertools import product as product
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 = 512
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 16
y1 = yindex // 16
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 16 * x2 + 144 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 32
y1 = yindex // 32
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 32 * x2 + 288 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_3(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 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]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 16
y1 = yindex // 16
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (y0 + 16 * x2 + 65536 * y1), tmp4, ymask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_4(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16 % 32
x2 = xindex // 512
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 32 * x1 + 2048 * x2), None)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 32 * x1 + 2048 * x2), None)
tmp3 = tl.load(in_ptr0 + (1024 + x0 + 32 * x1 + 2048 * x2), None)
tmp5 = tl.load(in_ptr0 + (1040 + x0 + 32 * x1 + 2048 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 32
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_max_pool2d_with_indices_6(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32 % 16
x2 = xindex // 512
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1 + 2048 * x2), None)
tmp1 = tl.load(in_ptr0 + (32 + x0 + 64 * x1 + 2048 * x2), None)
tmp3 = tl.load(in_ptr0 + (1024 + x0 + 64 * x1 + 2048 * x2), None)
tmp5 = tl.load(in_ptr0 + (1056 + x0 + 64 * x1 + 2048 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_7(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_8(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 64
x1 = xindex // 64 % 4
x2 = xindex // 256
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * x1 + 4096 * x2), None)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 256 * x1 + 4096 * x2), None)
tmp3 = tl.load(in_ptr0 + (128 + x0 + 256 * x1 + 4096 * x2), None)
tmp5 = tl.load(in_ptr0 + (192 + x0 + 256 * x1 + 4096 * x2), None)
tmp7 = tl.load(in_ptr0 + (1024 + x0 + 256 * x1 + 4096 * x2), None)
tmp9 = tl.load(in_ptr0 + (1088 + x0 + 256 * x1 + 4096 * x2), None)
tmp11 = tl.load(in_ptr0 + (1152 + x0 + 256 * x1 + 4096 * x2), None)
tmp13 = tl.load(in_ptr0 + (1216 + x0 + 256 * x1 + 4096 * x2), None)
tmp15 = tl.load(in_ptr0 + (2048 + x0 + 256 * x1 + 4096 * x2), None)
tmp17 = tl.load(in_ptr0 + (2112 + x0 + 256 * x1 + 4096 * x2), None)
tmp19 = tl.load(in_ptr0 + (2176 + x0 + 256 * x1 + 4096 * x2), None)
tmp21 = tl.load(in_ptr0 + (2240 + x0 + 256 * x1 + 4096 * x2), None)
tmp23 = tl.load(in_ptr0 + (3072 + x0 + 256 * x1 + 4096 * x2), None)
tmp25 = tl.load(in_ptr0 + (3136 + x0 + 256 * x1 + 4096 * x2), None)
tmp27 = tl.load(in_ptr0 + (3200 + x0 + 256 * x1 + 4096 * x2), None)
tmp29 = tl.load(in_ptr0 + (3264 + x0 + 256 * x1 + 4096 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp20 = triton_helpers.maximum(tmp19, tmp18)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = triton_helpers.maximum(tmp23, tmp22)
tmp26 = triton_helpers.maximum(tmp25, tmp24)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tmp31 = tmp1 > tmp0
tmp32 = tl.full([1], 1, tl.int8)
tmp33 = tl.full([1], 0, tl.int8)
tmp34 = tl.where(tmp31, tmp32, tmp33)
tmp35 = tmp3 > tmp2
tmp36 = tl.full([1], 2, tl.int8)
tmp37 = tl.where(tmp35, tmp36, tmp34)
tmp38 = tmp5 > tmp4
tmp39 = tl.full([1], 3, tl.int8)
tmp40 = tl.where(tmp38, tmp39, tmp37)
tmp41 = tmp7 > tmp6
tmp42 = tl.full([1], 4, tl.int8)
tmp43 = tl.where(tmp41, tmp42, tmp40)
tmp44 = tmp9 > tmp8
tmp45 = tl.full([1], 5, tl.int8)
tmp46 = tl.where(tmp44, tmp45, tmp43)
tmp47 = tmp11 > tmp10
tmp48 = tl.full([1], 6, tl.int8)
tmp49 = tl.where(tmp47, tmp48, tmp46)
tmp50 = tmp13 > tmp12
tmp51 = tl.full([1], 7, tl.int8)
tmp52 = tl.where(tmp50, tmp51, tmp49)
tmp53 = tmp15 > tmp14
tmp54 = tl.full([1], 8, tl.int8)
tmp55 = tl.where(tmp53, tmp54, tmp52)
tmp56 = tmp17 > tmp16
tmp57 = tl.full([1], 9, tl.int8)
tmp58 = tl.where(tmp56, tmp57, tmp55)
tmp59 = tmp19 > tmp18
tmp60 = tl.full([1], 10, tl.int8)
tmp61 = tl.where(tmp59, tmp60, tmp58)
tmp62 = tmp21 > tmp20
tmp63 = tl.full([1], 11, tl.int8)
tmp64 = tl.where(tmp62, tmp63, tmp61)
tmp65 = tmp23 > tmp22
tmp66 = tl.full([1], 12, tl.int8)
tmp67 = tl.where(tmp65, tmp66, tmp64)
tmp68 = tmp25 > tmp24
tmp69 = tl.full([1], 13, tl.int8)
tmp70 = tl.where(tmp68, tmp69, tmp67)
tmp71 = tmp27 > tmp26
tmp72 = tl.full([1], 14, tl.int8)
tmp73 = tl.where(tmp71, tmp72, tmp70)
tmp74 = tmp29 > tmp28
tmp75 = tl.full([1], 15, tl.int8)
tmp76 = tl.where(tmp74, tmp75, tmp73)
tl.store(out_ptr0 + x3, tmp30, None)
tl.store(out_ptr1 + x3, tmp76, None)
@triton.jit
def triton_poi_fused_convolution_relu_9(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_10(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 % 2
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_convolution_11(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_add_convolution_12(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x2, None)
tmp2 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_13(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 8
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y0 = yindex % 2
y1 = yindex // 2
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 2 * x2 + 8192 * y1), ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp0, ymask)
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, (16, 1, 5, 5), (25, 25, 5, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (32, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (2, 32, 1, 1), (32, 1, 1, 1))
assert_size_stride(primals_7, (2,), (1,))
assert_size_stride(primals_8, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (2, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_11, (2,), (1,))
assert_size_stride(primals_12, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_13, (128,), (1,))
assert_size_stride(primals_14, (2, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_15, (2,), (1,))
assert_size_stride(primals_16, (2, 1, 8, 8), (64, 64, 8, 1))
assert_size_stride(primals_17, (2, 1, 4, 4), (16, 16, 4, 1))
assert_size_stride(primals_18, (2, 1, 4, 4), (16, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((32, 16, 3, 3), (144, 1, 48, 16), torch.
float32)
get_raw_stream(0)
triton_poi_fused_0[grid(512, 9)](primals_4, buf0, 512, 9, XBLOCK=16,
YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf1 = empty_strided_cuda((64, 32, 3, 3), (288, 1, 96, 32), torch.
float32)
triton_poi_fused_1[grid(2048, 9)](primals_8, buf1, 2048, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf2 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_2[grid(8192, 9)](primals_12, buf2, 8192, 9, XBLOCK
=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_12
buf3 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf4 = empty_strided_cuda((4, 16, 64, 64), (65536, 1, 1024, 16),
torch.float32)
triton_poi_fused_convolution_relu_3[grid(64, 4096)](buf3, primals_2,
buf4, 64, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del buf3
del primals_2
buf5 = empty_strided_cuda((4, 16, 32, 32), (16384, 1, 512, 16),
torch.float32)
buf6 = empty_strided_cuda((4, 16, 32, 32), (16384, 1, 512, 16),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_4[grid(65536)](buf4, buf5,
buf6, 65536, XBLOCK=256, num_warps=4, num_stages=1)
buf7 = extern_kernels.convolution(buf5, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 32, 32, 32), (32768, 1, 1024, 32))
buf8 = buf7
del buf7
triton_poi_fused_convolution_relu_5[grid(131072)](buf8, primals_5,
131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf9 = extern_kernels.convolution(buf8, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 2, 32, 32), (2048, 1, 64, 2))
buf10 = empty_strided_cuda((4, 32, 16, 16), (8192, 1, 512, 32),
torch.float32)
buf11 = empty_strided_cuda((4, 32, 16, 16), (8192, 1, 512, 32),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_6[grid(32768)](buf8, buf10,
buf11, 32768, XBLOCK=256, num_warps=4, num_stages=1)
buf12 = extern_kernels.convolution(buf10, buf1, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 64, 16, 16), (16384, 1, 1024, 64))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_7[grid(65536)](buf13, primals_9,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_9
buf14 = extern_kernels.convolution(buf13, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 2, 16, 16), (512, 1, 32, 2))
buf15 = empty_strided_cuda((4, 64, 4, 4), (1024, 1, 256, 64), torch
.float32)
buf16 = empty_strided_cuda((4, 64, 4, 4), (1024, 1, 256, 64), torch
.int8)
triton_poi_fused_max_pool2d_with_indices_8[grid(4096)](buf13, buf15,
buf16, 4096, XBLOCK=128, num_warps=4, num_stages=1)
buf17 = extern_kernels.convolution(buf15, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 128, 4, 4), (2048, 1, 512, 128))
buf18 = buf17
del buf17
triton_poi_fused_convolution_relu_9[grid(8192)](buf18, primals_13,
8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_13
buf19 = extern_kernels.convolution(buf18, primals_14, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 2, 4, 4), (32, 1, 8, 2))
buf20 = buf19
del buf19
triton_poi_fused_convolution_10[grid(128)](buf20, primals_15, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_15
buf21 = extern_kernels.convolution(buf20, primals_16, stride=(4, 4),
padding=(2, 2), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=2, bias=None)
assert_size_stride(buf21, (4, 2, 16, 16), (512, 1, 32, 2))
buf22 = buf14
del buf14
triton_poi_fused_add_convolution_11[grid(2048)](buf22, primals_11,
buf21, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del buf21
del primals_11
buf23 = extern_kernels.convolution(buf22, primals_17, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=2, bias=None)
assert_size_stride(buf23, (4, 2, 32, 32), (2048, 1, 64, 2))
buf24 = buf23
del buf23
triton_poi_fused_add_convolution_12[grid(8192)](buf24, buf9,
primals_7, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del buf9
del primals_7
buf25 = extern_kernels.convolution(buf24, primals_18, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=2, bias=None)
assert_size_stride(buf25, (4, 2, 64, 64), (8192, 1, 128, 2))
buf26 = empty_strided_cuda((4, 2, 64, 64), (8192, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_13[grid(8, 4096)](buf25, buf26, 8,
4096, XBLOCK=128, YBLOCK=8, num_warps=4, num_stages=1)
del buf25
return (buf26, primals_1, primals_3, buf0, primals_6, buf1, primals_10,
buf2, primals_14, primals_16, primals_17, primals_18, buf4, buf5,
buf6, buf8, buf10, buf11, buf13, buf15, buf16, buf18, buf20, buf22,
buf24)
class MaskNetNew(nn.Module):
def __init__(self):
super(MaskNetNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=
5, stride=1, padding=2)
self.relu1 = nn.ReLU()
self.Pool1 = nn.MaxPool2d(kernel_size=(2, 2), stride=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size
=3, stride=1, padding=1)
self.relu2 = nn.ReLU()
self.conv2s = nn.Conv2d(in_channels=32, out_channels=2, kernel_size
=1, stride=1, padding=0)
self.Pool2 = nn.MaxPool2d(kernel_size=(2, 2), stride=2)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size
=(3, 3), stride=1, padding=1)
self.relu3 = nn.ReLU()
self.conv3s = nn.Conv2d(in_channels=64, out_channels=2, kernel_size
=1, stride=1, padding=0)
self.Pool3 = nn.MaxPool2d(kernel_size=(4, 4), stride=4)
self.conv4 = nn.Conv2d(in_channels=64, out_channels=128,
kernel_size=(3, 3), stride=1, padding=1)
self.relu4 = nn.ReLU()
self.conv4s = nn.Conv2d(in_channels=128, out_channels=2,
kernel_size=1, stride=1, padding=0)
self.Upsample1 = nn.ConvTranspose2d(in_channels=2, out_channels=2,
kernel_size=8, stride=4, padding=2, bias=False, groups=2)
self.Upsample2 = nn.ConvTranspose2d(in_channels=2, out_channels=2,
kernel_size=4, stride=2, padding=1, bias=False, groups=2)
self.Upsample3 = nn.ConvTranspose2d(in_channels=2, out_channels=2,
kernel_size=4, stride=2, padding=1, bias=False, groups=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_6 = self.conv2s.weight
primals_7 = self.conv2s.bias
primals_8 = self.conv3.weight
primals_9 = self.conv3.bias
primals_10 = self.conv3s.weight
primals_11 = self.conv3s.bias
primals_12 = self.conv4.weight
primals_13 = self.conv4.bias
primals_14 = self.conv4s.weight
primals_15 = self.conv4s.bias
primals_16 = self.Upsample1.weight
primals_17 = self.Upsample2.weight
primals_18 = self.Upsample3.weight
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])
return output[0]
|
DongChengdongHangZhou/caffe-to-pytorch
|
MaskNet
| false
| 2,280
|
[
"Apache-2.0"
] | 0
|
5e3104f3aa77d35bad5d2de235b067460c136fd5
|
https://github.com/DongChengdongHangZhou/caffe-to-pytorch/tree/5e3104f3aa77d35bad5d2de235b067460c136fd5
|
self_conv
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def quantize_w(x):
x = Q_W.apply(x)
return x
def fw(x, bitW):
if bitW == 32:
return x
x = quantize_w(x)
return x
class Q_W(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x.sign() * x.abs().mean()
@staticmethod
def backward(ctx, grad):
return grad
class self_conv(nn.Conv2d):
def __init__(self, in_channels, out_channels, bitW, kernel_size, stride
=1, padding=0, bias=False):
super(self_conv, self).__init__(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, bias=bias)
self.bitW = bitW
self.padding = padding
self.stride = stride
def forward(self, input):
if self.padding > 0:
padding_shape = (self.padding, self.padding, self.padding, self
.padding)
input = F.pad(input, padding_shape, 'constant', 1)
output = F.conv2d(input, fw(self.weight, self.bitW), bias=self.bias,
stride=self.stride, dilation=self.dilation, groups=self.groups)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'bitW': 4,
'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_mean_mul_sign_0(in_ptr0, out_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl_math.abs(tmp0)
tmp2 = tl.broadcast_to(tmp1, [RBLOCK])
tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0))
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = tmp5 < tmp0
tmp7 = tmp6.to(tl.int8)
tmp8 = tmp0 < tmp5
tmp9 = tmp8.to(tl.int8)
tmp10 = tmp7 - tmp9
tmp11 = tmp10.to(tmp0.dtype)
tmp12 = 256.0
tmp13 = tmp4 / tmp12
tmp14 = tmp11 * tmp13
tl.store(out_ptr1 + tl.broadcast_to(r0, [RBLOCK]), tmp14, None)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_abs_mean_mul_sign_0[grid(1)](primals_1, buf1, 1,
256, num_warps=2, num_stages=1)
del primals_1
buf2 = extern_kernels.convolution(primals_2, buf1, 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, 1, 1), (4, 1, 1, 1))
return buf2, primals_2, buf1
def quantize_w(x):
x = Q_W.apply(x)
return x
def fw(x, bitW):
if bitW == 32:
return x
x = quantize_w(x)
return x
class Q_W(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x.sign() * x.abs().mean()
@staticmethod
def backward(ctx, grad):
return grad
class self_convNew(nn.Conv2d):
def __init__(self, in_channels, out_channels, bitW, kernel_size, stride
=1, padding=0, bias=False):
super(self_convNew, self).__init__(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, bias=bias)
self.bitW = bitW
self.padding = padding
self.stride = stride
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
GakkiChen/TWB-Net
|
self_conv
| false
| 2,281
|
[
"MIT"
] | 0
|
bb4917c697c09585bb3fe163a8b429b6dd250f18
|
https://github.com/GakkiChen/TWB-Net/tree/bb4917c697c09585bb3fe163a8b429b6dd250f18
|
Fp32GroupNorm
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Fp32GroupNorm(nn.GroupNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, input):
output = F.group_norm(input.float(), self.num_groups, self.weight.
float() if self.weight is not None else None, self.bias.float() if
self.bias is not None else None, self.eps)
return output.type_as(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_groups': 1, 'num_channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
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_native_group_norm_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
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 = tmp0 - tmp10
tmp18 = 64.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tl.store(out_ptr2 + (r1 + 64 * x0), tmp27, xmask)
tl.store(out_ptr3 + 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,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
get_raw_stream(0)
triton_per_fused_native_group_norm_0[grid(4)](primals_1, primals_2,
primals_3, buf0, buf3, buf4, 4, 64, XBLOCK=1, num_warps=2,
num_stages=1)
del primals_2
del primals_3
return buf3, primals_1, reinterpret_tensor(buf0, (4, 1, 1), (1, 1, 1), 0
), reinterpret_tensor(buf4, (4, 1, 1), (1, 1, 1), 0)
class Fp32GroupNormNew(nn.GroupNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, input_0):
primals_2 = self.weight
primals_3 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Ethan07902050/s3prl
|
Fp32GroupNorm
| false
| 2,282
|
[
"MIT"
] | 0
|
854aff0b3062fc2cff531401923b8745f64701e7
|
https://github.com/Ethan07902050/s3prl/tree/854aff0b3062fc2cff531401923b8745f64701e7
|
BiTemperedLogisticLoss
|
import torch
import torch.nn as nn
def log_t(u, t):
"""Compute log_t for `u'."""
if t == 1.0:
return u.log()
else:
return (u.pow(1.0 - t) - 1.0) / (1.0 - t)
def exp_t(u, t):
"""Compute exp_t for `u'."""
if t == 1:
return u.exp()
else:
return (1.0 + (1.0 - t) * u).relu().pow(1.0 / (1.0 - t))
def compute_normalization_binary_search(activations, t, num_iters):
"""Returns the normalization value for each example (t < 1.0).
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature 2 (< 1.0 for finite support).
num_iters: Number of iterations to run the method.
Return: A tensor of same rank as activation with the last dimension being 1.
"""
mu, _ = torch.max(activations, -1, keepdim=True)
normalized_activations = activations - mu
effective_dim = torch.sum((normalized_activations > -1.0 / (1.0 - t)).
to(torch.int32), dim=-1, keepdim=True)
shape_partition = activations.shape[:-1] + (1,)
lower = torch.zeros(shape_partition, dtype=activations.dtype, device=
activations.device)
upper = -log_t(1.0 / effective_dim, t) * torch.ones_like(lower)
for _ in range(num_iters):
logt_partition = (upper + lower) / 2.0
sum_probs = torch.sum(exp_t(normalized_activations - logt_partition,
t), dim=-1, keepdim=True)
update = sum_probs < 1.0
lower = torch.reshape(lower * update + (1.0 - update) *
logt_partition, shape_partition)
upper = torch.reshape(upper * (1.0 - update) + update *
logt_partition, shape_partition)
logt_partition = (upper + lower) / 2.0
return logt_partition + mu
def compute_normalization_fixed_point(activations, t, num_iters):
"""Returns the normalization value for each example (t > 1.0).
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature 2 (> 1.0 for tail heaviness).
num_iters: Number of iterations to run the method.
Return: A tensor of same shape as activation with the last dimension being 1.
"""
mu, _ = torch.max(activations, -1, keepdim=True)
normalized_activations_step_0 = activations - mu
normalized_activations = normalized_activations_step_0
for _ in range(num_iters):
logt_partition = torch.sum(exp_t(normalized_activations, t), -1,
keepdim=True)
normalized_activations = (normalized_activations_step_0 *
logt_partition.pow(1.0 - t))
logt_partition = torch.sum(exp_t(normalized_activations, t), -1,
keepdim=True)
normalization_constants = -log_t(1.0 / logt_partition, t) + mu
return normalization_constants
def compute_normalization(activations, t, num_iters=5):
"""Returns the normalization value for each example.
Backward pass is implemented.
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
num_iters: Number of iterations to run the method.
Return: A tensor of same rank as activation with the last dimension being 1.
"""
return ComputeNormalization.apply(activations, t, num_iters)
def tempered_softmax(activations, t, num_iters=5):
"""Tempered softmax function.
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature > 1.0.
num_iters: Number of iterations to run the method.
Returns:
A probabilities tensor.
"""
if t == 1.0:
return activations.softmax(dim=-1)
normalization_constants = compute_normalization(activations, t, num_iters)
return exp_t(activations - normalization_constants, t)
def bi_tempered_logistic_loss(activations, labels, t1, t2, label_smoothing=
0.0, num_iters=5, reduction='mean'):
"""Bi-Tempered Logistic Loss.
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
labels: A tensor with shape and dtype as activations (onehot),
or a long tensor of one dimension less than activations (pytorch standard)
t1: Temperature 1 (< 1.0 for boundedness).
t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
label_smoothing: Label smoothing parameter between [0, 1). Default 0.0.
num_iters: Number of iterations to run the method. Default 5.
reduction: ``'none'`` | ``'mean'`` | ``'sum'``. Default ``'mean'``.
``'none'``: No reduction is applied, return shape is shape of
activations without the last dimension.
``'mean'``: Loss is averaged over minibatch. Return shape (1,)
``'sum'``: Loss is summed over minibatch. Return shape (1,)
Returns:
A loss tensor.
"""
if len(labels.shape) < len(activations.shape):
labels_onehot = torch.zeros_like(activations)
labels_onehot.scatter_(1, labels[..., None], 1)
else:
labels_onehot = labels
if label_smoothing > 0:
num_classes = labels_onehot.shape[-1]
labels_onehot = (1 - label_smoothing * num_classes / (num_classes - 1)
) * labels_onehot + label_smoothing / (num_classes - 1)
probabilities = tempered_softmax(activations, t2, num_iters)
loss_values = labels_onehot * log_t(labels_onehot + 1e-10, t1
) - labels_onehot * log_t(probabilities, t1) - labels_onehot.pow(
2.0 - t1) / (2.0 - t1) + probabilities.pow(2.0 - t1) / (2.0 - t1)
loss_values = loss_values.sum(dim=-1)
if reduction == 'none':
return loss_values
if reduction == 'sum':
return loss_values.sum()
if reduction == 'mean':
return loss_values.mean()
class ComputeNormalization(torch.autograd.Function):
"""
Class implementing custom backward pass for compute_normalization. See compute_normalization.
"""
@staticmethod
def forward(ctx, activations, t, num_iters):
if t < 1.0:
normalization_constants = compute_normalization_binary_search(
activations, t, num_iters)
else:
normalization_constants = compute_normalization_fixed_point(
activations, t, num_iters)
ctx.save_for_backward(activations, normalization_constants)
ctx.t = t
return normalization_constants
@staticmethod
def backward(ctx, grad_output):
activations, normalization_constants = ctx.saved_tensors
t = ctx.t
normalized_activations = activations - normalization_constants
probabilities = exp_t(normalized_activations, t)
escorts = probabilities.pow(t)
escorts = escorts / escorts.sum(dim=-1, keepdim=True)
grad_input = escorts * grad_output
return grad_input, None, None
class BiTemperedLogisticLoss(nn.Module):
def __init__(self, t1, t2, smoothing=0.0):
super(BiTemperedLogisticLoss, self).__init__()
self.t1 = t1
self.t2 = t2
self.smoothing = smoothing
def forward(self, logit_label, truth_label):
loss_label = bi_tempered_logistic_loss(logit_label, truth_label, t1
=self.t1, t2=self.t2, label_smoothing=self.smoothing, reduction
='none')
loss_label = loss_label.mean()
return loss_label
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'t1': 4, 't2': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_max_sub_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_poi_fused_add_mul_pow_relu_sum_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')
tmp10 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = -3.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 + tmp4
tmp6 = tl.full([1], 0, tl.int32)
tmp7 = triton_helpers.maximum(tmp6, tmp5)
tmp8 = -0.3333333333333333
tmp9 = libdevice.pow(tmp7, tmp8)
tmp11 = tmp10 * tmp2
tmp12 = tmp11 + tmp4
tmp13 = triton_helpers.maximum(tmp6, tmp12)
tmp14 = libdevice.pow(tmp13, tmp8)
tmp15 = tmp9 + tmp14
tmp17 = tmp16 * tmp2
tmp18 = tmp17 + tmp4
tmp19 = triton_helpers.maximum(tmp6, tmp18)
tmp20 = libdevice.pow(tmp19, tmp8)
tmp21 = tmp15 + tmp20
tmp23 = tmp22 * tmp2
tmp24 = tmp23 + tmp4
tmp25 = triton_helpers.maximum(tmp6, tmp24)
tmp26 = libdevice.pow(tmp25, tmp8)
tmp27 = tmp21 + tmp26
tmp28 = tl.full([1], 1, tl.int32)
tmp29 = tmp28 / tmp27
tmp30 = tmp29 * tmp29
tmp31 = tmp30 * tmp29
tmp32 = tmp0 * tmp31
tl.store(out_ptr0 + x2, tmp32, xmask)
@triton.jit
def triton_poi_fused_add_mul_pow_relu_sum_2(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = -3.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 + tmp4
tmp6 = tl.full([1], 0, tl.int32)
tmp7 = triton_helpers.maximum(tmp6, tmp5)
tmp8 = -0.3333333333333333
tmp9 = libdevice.pow(tmp7, tmp8)
tmp11 = tmp10 * tmp2
tmp12 = tmp11 + tmp4
tmp13 = triton_helpers.maximum(tmp6, tmp12)
tmp14 = libdevice.pow(tmp13, tmp8)
tmp15 = tmp9 + tmp14
tmp17 = tmp16 * tmp2
tmp18 = tmp17 + tmp4
tmp19 = triton_helpers.maximum(tmp6, tmp18)
tmp20 = libdevice.pow(tmp19, tmp8)
tmp21 = tmp15 + tmp20
tmp23 = tmp22 * tmp2
tmp24 = tmp23 + tmp4
tmp25 = triton_helpers.maximum(tmp6, tmp24)
tmp26 = libdevice.pow(tmp25, tmp8)
tmp27 = tmp21 + tmp26
tmp28 = tl.full([1], 1, tl.int32)
tmp29 = tmp28 / tmp27
tmp30 = tmp29 * tmp29
tmp31 = tmp30 * tmp29
tmp32 = tmp0 * tmp31
tl.store(out_ptr0 + x2, tmp32, xmask)
@triton.jit
def triton_poi_fused_add_mul_pow_relu_sum_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = -3.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 + tmp4
tmp6 = tl.full([1], 0, tl.int32)
tmp7 = triton_helpers.maximum(tmp6, tmp5)
tmp8 = -0.3333333333333333
tmp9 = libdevice.pow(tmp7, tmp8)
tmp11 = tmp10 * tmp2
tmp12 = tmp11 + tmp4
tmp13 = triton_helpers.maximum(tmp6, tmp12)
tmp14 = libdevice.pow(tmp13, tmp8)
tmp15 = tmp9 + tmp14
tmp17 = tmp16 * tmp2
tmp18 = tmp17 + tmp4
tmp19 = triton_helpers.maximum(tmp6, tmp18)
tmp20 = libdevice.pow(tmp19, tmp8)
tmp21 = tmp15 + tmp20
tmp23 = tmp22 * tmp2
tmp24 = tmp23 + tmp4
tmp25 = triton_helpers.maximum(tmp6, tmp24)
tmp26 = libdevice.pow(tmp25, tmp8)
tmp27 = tmp21 + tmp26
tmp28 = tl.full([1], 1, tl.int32)
tmp29 = tmp28 / tmp27
tmp30 = tmp29 * tmp29
tmp31 = tmp30 * tmp29
tmp32 = tmp0 * tmp31
tl.store(in_out_ptr0 + x2, tmp32, xmask)
@triton.jit
def triton_poi_fused_add_div_max_mul_neg_pow_reciprocal_relu_sub_sum_4(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp37 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp39 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp41 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = -3.0
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 + tmp3
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = -0.3333333333333333
tmp8 = libdevice.pow(tmp6, tmp7)
tmp10 = tmp9 * tmp1
tmp11 = tmp10 + tmp3
tmp12 = triton_helpers.maximum(tmp5, tmp11)
tmp13 = libdevice.pow(tmp12, tmp7)
tmp14 = tmp8 + tmp13
tmp16 = tmp15 * tmp1
tmp17 = tmp16 + tmp3
tmp18 = triton_helpers.maximum(tmp5, tmp17)
tmp19 = libdevice.pow(tmp18, tmp7)
tmp20 = tmp14 + tmp19
tmp22 = tmp21 * tmp1
tmp23 = tmp22 + tmp3
tmp24 = triton_helpers.maximum(tmp5, tmp23)
tmp25 = libdevice.pow(tmp24, tmp7)
tmp26 = tmp20 + tmp25
tmp27 = tl.full([1], 1, tl.int32)
tmp28 = tmp27 / tmp26
tmp29 = tmp28 * tmp3
tmp30 = tmp27 / tmp29
tmp31 = tmp30 * tmp30
tmp32 = tmp31 * tmp30
tmp33 = tmp32 - tmp3
tmp34 = tmp33 * tmp7
tmp35 = -tmp34
tmp38 = triton_helpers.maximum(tmp36, tmp37)
tmp40 = triton_helpers.maximum(tmp38, tmp39)
tmp42 = triton_helpers.maximum(tmp40, tmp41)
tmp43 = tmp35 + tmp42
tl.store(in_out_ptr0 + x0, tmp43, xmask)
@triton.jit
def triton_poi_fused_add_div_max_mul_neg_pow_relu_sub_5(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
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp12 = tl.load(in_ptr1 + x2, xmask)
tmp13 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp1 = 1e-10
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 1, tl.int32)
tmp4 = tmp3 / tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp5 * tmp4
tmp7 = 1.0
tmp8 = tmp6 - tmp7
tmp9 = -0.3333333333333333
tmp10 = tmp8 * tmp9
tmp11 = tmp0 * tmp10
tmp14 = tmp12 - tmp13
tmp15 = -3.0
tmp16 = tmp14 * tmp15
tmp17 = tmp16 + tmp7
tmp18 = tl.full([1], 0, tl.int32)
tmp19 = triton_helpers.maximum(tmp18, tmp17)
tmp20 = libdevice.pow(tmp19, tmp9)
tmp21 = tmp3 / tmp20
tmp22 = tmp21 * tmp21
tmp23 = tmp22 * tmp21
tmp24 = tmp23 - tmp7
tmp25 = tmp24 * tmp9
tmp26 = tmp0 * tmp25
tmp27 = tmp11 - tmp26
tmp28 = tmp3 / tmp0
tmp29 = tmp28 * tmp28
tmp30 = -0.5
tmp31 = tmp29 * tmp30
tmp32 = tmp27 - tmp31
tl.store(out_ptr0 + x2, tmp32, xmask)
@triton.jit
def triton_per_fused_add_div_max_mean_mul_neg_pow_relu_sub_sum_6(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp2 = tl.load(in_out_ptr0 + r0, None)
tmp18 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp42 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp43 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp3 = tmp1 - tmp2
tmp4 = -3.0
tmp5 = tmp3 * tmp4
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1, 1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = -0.3333333333333333
tmp11 = libdevice.pow(tmp9, tmp10)
tmp12 = tl.full([1, 1], 1, tl.int32)
tmp13 = tmp12 / tmp11
tmp14 = tmp13 * tmp13
tmp15 = -0.5
tmp16 = tmp14 * tmp15
tmp17 = tmp0 + tmp16
tmp20 = tmp19 - tmp2
tmp21 = tmp20 * tmp4
tmp22 = tmp21 + tmp6
tmp23 = triton_helpers.maximum(tmp8, tmp22)
tmp24 = libdevice.pow(tmp23, tmp10)
tmp25 = tmp12 / tmp24
tmp26 = tmp25 * tmp25
tmp27 = tmp26 * tmp15
tmp28 = tmp18 + tmp27
tmp29 = tmp17 + tmp28
tmp32 = tmp31 - tmp2
tmp33 = tmp32 * tmp4
tmp34 = tmp33 + tmp6
tmp35 = triton_helpers.maximum(tmp8, tmp34)
tmp36 = libdevice.pow(tmp35, tmp10)
tmp37 = tmp12 / tmp36
tmp38 = tmp37 * tmp37
tmp39 = tmp38 * tmp15
tmp40 = tmp30 + tmp39
tmp41 = tmp29 + tmp40
tmp44 = tmp43 - tmp2
tmp45 = tmp44 * tmp4
tmp46 = tmp45 + tmp6
tmp47 = triton_helpers.maximum(tmp8, tmp46)
tmp48 = libdevice.pow(tmp47, tmp10)
tmp49 = tmp12 / tmp48
tmp50 = tmp49 * tmp49
tmp51 = tmp50 * tmp15
tmp52 = tmp42 + tmp51
tmp53 = tmp41 + tmp52
tmp54 = tl.broadcast_to(tmp53, [XBLOCK, RBLOCK])
tmp56 = tl.sum(tmp54, 1)[:, None]
tmp57 = 64.0
tmp58 = tmp56 / tmp57
tl.debug_barrier()
tl.store(in_out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp58, 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_max_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_pow_relu_sum_1[grid(256)](buf0, buf1, 256,
XBLOCK=128, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_pow_relu_sum_2[grid(256)](buf0, buf1, buf2,
256, XBLOCK=128, num_warps=4, num_stages=1)
buf3 = buf1
del buf1
triton_poi_fused_add_mul_pow_relu_sum_2[grid(256)](buf0, buf2, buf3,
256, XBLOCK=128, num_warps=4, num_stages=1)
buf4 = buf2
del buf2
triton_poi_fused_add_mul_pow_relu_sum_2[grid(256)](buf0, buf3, buf4,
256, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
buf5 = buf0
del buf0
triton_poi_fused_add_mul_pow_relu_sum_3[grid(256)](buf5, buf4, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del buf4
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf7 = buf6
del buf6
triton_poi_fused_add_div_max_mul_neg_pow_reciprocal_relu_sub_sum_4[grid
(64)](buf7, buf5, arg0_1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf8 = buf5
del buf5
triton_poi_fused_add_div_max_mul_neg_pow_relu_sub_5[grid(256)](arg1_1,
arg0_1, buf7, buf8, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
buf9 = reinterpret_tensor(buf7, (4, 4, 4), (16, 4, 1), 0)
del buf7
buf10 = empty_strided_cuda((), (), torch.float32)
buf11 = buf10
del buf10
triton_per_fused_add_div_max_mean_mul_neg_pow_relu_sub_sum_6[grid(1)](
buf9, buf11, buf8, arg0_1, 1, 64, XBLOCK=1, num_warps=2,
num_stages=1)
del arg0_1
del buf8
del buf9
return buf11,
def log_t(u, t):
"""Compute log_t for `u'."""
if t == 1.0:
return u.log()
else:
return (u.pow(1.0 - t) - 1.0) / (1.0 - t)
def exp_t(u, t):
"""Compute exp_t for `u'."""
if t == 1:
return u.exp()
else:
return (1.0 + (1.0 - t) * u).relu().pow(1.0 / (1.0 - t))
def compute_normalization_binary_search(activations, t, num_iters):
"""Returns the normalization value for each example (t < 1.0).
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature 2 (< 1.0 for finite support).
num_iters: Number of iterations to run the method.
Return: A tensor of same rank as activation with the last dimension being 1.
"""
mu, _ = torch.max(activations, -1, keepdim=True)
normalized_activations = activations - mu
effective_dim = torch.sum((normalized_activations > -1.0 / (1.0 - t)).
to(torch.int32), dim=-1, keepdim=True)
shape_partition = activations.shape[:-1] + (1,)
lower = torch.zeros(shape_partition, dtype=activations.dtype, device=
activations.device)
upper = -log_t(1.0 / effective_dim, t) * torch.ones_like(lower)
for _ in range(num_iters):
logt_partition = (upper + lower) / 2.0
sum_probs = torch.sum(exp_t(normalized_activations - logt_partition,
t), dim=-1, keepdim=True)
update = sum_probs < 1.0
lower = torch.reshape(lower * update + (1.0 - update) *
logt_partition, shape_partition)
upper = torch.reshape(upper * (1.0 - update) + update *
logt_partition, shape_partition)
logt_partition = (upper + lower) / 2.0
return logt_partition + mu
def compute_normalization_fixed_point(activations, t, num_iters):
"""Returns the normalization value for each example (t > 1.0).
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature 2 (> 1.0 for tail heaviness).
num_iters: Number of iterations to run the method.
Return: A tensor of same shape as activation with the last dimension being 1.
"""
mu, _ = torch.max(activations, -1, keepdim=True)
normalized_activations_step_0 = activations - mu
normalized_activations = normalized_activations_step_0
for _ in range(num_iters):
logt_partition = torch.sum(exp_t(normalized_activations, t), -1,
keepdim=True)
normalized_activations = (normalized_activations_step_0 *
logt_partition.pow(1.0 - t))
logt_partition = torch.sum(exp_t(normalized_activations, t), -1,
keepdim=True)
normalization_constants = -log_t(1.0 / logt_partition, t) + mu
return normalization_constants
def compute_normalization(activations, t, num_iters=5):
"""Returns the normalization value for each example.
Backward pass is implemented.
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
num_iters: Number of iterations to run the method.
Return: A tensor of same rank as activation with the last dimension being 1.
"""
return ComputeNormalization.apply(activations, t, num_iters)
def tempered_softmax(activations, t, num_iters=5):
"""Tempered softmax function.
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
t: Temperature > 1.0.
num_iters: Number of iterations to run the method.
Returns:
A probabilities tensor.
"""
if t == 1.0:
return activations.softmax(dim=-1)
normalization_constants = compute_normalization(activations, t, num_iters)
return exp_t(activations - normalization_constants, t)
def bi_tempered_logistic_loss(activations, labels, t1, t2, label_smoothing=
0.0, num_iters=5, reduction='mean'):
"""Bi-Tempered Logistic Loss.
Args:
activations: A multi-dimensional tensor with last dimension `num_classes`.
labels: A tensor with shape and dtype as activations (onehot),
or a long tensor of one dimension less than activations (pytorch standard)
t1: Temperature 1 (< 1.0 for boundedness).
t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
label_smoothing: Label smoothing parameter between [0, 1). Default 0.0.
num_iters: Number of iterations to run the method. Default 5.
reduction: ``'none'`` | ``'mean'`` | ``'sum'``. Default ``'mean'``.
``'none'``: No reduction is applied, return shape is shape of
activations without the last dimension.
``'mean'``: Loss is averaged over minibatch. Return shape (1,)
``'sum'``: Loss is summed over minibatch. Return shape (1,)
Returns:
A loss tensor.
"""
if len(labels.shape) < len(activations.shape):
labels_onehot = torch.zeros_like(activations)
labels_onehot.scatter_(1, labels[..., None], 1)
else:
labels_onehot = labels
if label_smoothing > 0:
num_classes = labels_onehot.shape[-1]
labels_onehot = (1 - label_smoothing * num_classes / (num_classes - 1)
) * labels_onehot + label_smoothing / (num_classes - 1)
probabilities = tempered_softmax(activations, t2, num_iters)
loss_values = labels_onehot * log_t(labels_onehot + 1e-10, t1
) - labels_onehot * log_t(probabilities, t1) - labels_onehot.pow(
2.0 - t1) / (2.0 - t1) + probabilities.pow(2.0 - t1) / (2.0 - t1)
loss_values = loss_values.sum(dim=-1)
if reduction == 'none':
return loss_values
if reduction == 'sum':
return loss_values.sum()
if reduction == 'mean':
return loss_values.mean()
class ComputeNormalization(torch.autograd.Function):
"""
Class implementing custom backward pass for compute_normalization. See compute_normalization.
"""
@staticmethod
def forward(ctx, activations, t, num_iters):
if t < 1.0:
normalization_constants = compute_normalization_binary_search(
activations, t, num_iters)
else:
normalization_constants = compute_normalization_fixed_point(
activations, t, num_iters)
ctx.save_for_backward(activations, normalization_constants)
ctx.t = t
return normalization_constants
@staticmethod
def backward(ctx, grad_output):
activations, normalization_constants = ctx.saved_tensors
t = ctx.t
normalized_activations = activations - normalization_constants
probabilities = exp_t(normalized_activations, t)
escorts = probabilities.pow(t)
escorts = escorts / escorts.sum(dim=-1, keepdim=True)
grad_input = escorts * grad_output
return grad_input, None, None
class BiTemperedLogisticLossNew(nn.Module):
def __init__(self, t1, t2, smoothing=0.0):
super(BiTemperedLogisticLossNew, self).__init__()
self.t1 = t1
self.t2 = t2
self.smoothing = smoothing
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
GenoM87/cassava_leaf
|
BiTemperedLogisticLoss
| false
| 2,283
|
[
"MIT"
] | 0
|
51cc78b99a687b2d38be1930c40fc8aef3105b42
|
https://github.com/GenoM87/cassava_leaf/tree/51cc78b99a687b2d38be1930c40fc8aef3105b42
|
NextSentencePrediction
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
class NextSentencePrediction(nn.Module):
"""
2-class classification model : is_next, is_not_next
"""
def __init__(self, hidden):
"""
:param hidden: BERT model output size
"""
super().__init__()
self.linear = nn.Linear(hidden, 2)
self.softmax = nn.LogSoftmax(dim=-1)
def forward(self, x):
return self.softmax(self.linear(x[:, 0]))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden': 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
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
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 = 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)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused__log_softmax_add_1(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
x2 = xindex
x0 = xindex % 2
x1 = xindex // 2
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp7 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + 1)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp6 = tmp3 + tmp5
tmp10 = tmp7 + tmp9
tmp11 = triton_helpers.maximum(tmp6, tmp10)
tmp12 = tmp2 - tmp11
tl.store(out_ptr0 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 2
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp6 = tl_math.log(tmp5)
tmp7 = tmp0 - tmp6
tl.store(out_ptr0 + x2, tmp7, 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), (4, 1))
assert_size_stride(primals_3, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 2), (1, 4), 0), out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32)
triton_poi_fused__log_softmax_add_1[grid(32)](buf1, primals_3, buf2,
32, XBLOCK=32, num_warps=1, num_stages=1)
del primals_3
buf3 = reinterpret_tensor(buf1, (4, 4, 2), (8, 2, 1), 0)
del buf1
triton_poi_fused__log_softmax_2[grid(32)](buf2, buf3, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del buf2
return buf3, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf3
class NextSentencePredictionNew(nn.Module):
"""
2-class classification model : is_next, is_not_next
"""
def __init__(self, hidden):
"""
:param hidden: BERT model output size
"""
super().__init__()
self.linear = nn.Linear(hidden, 2)
self.softmax = nn.LogSoftmax(dim=-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]
|
EddieMG/LateTemporalModeling3DCNN
|
NextSentencePrediction
| false
| 2,284
|
[
"MIT"
] | 0
|
94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
https://github.com/EddieMG/LateTemporalModeling3DCNN/tree/94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
PositionwiseFeedForward
|
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
class GELU(nn.Module):
"""
Paper Section 3.4, last paragraph notice that BERT used the GELU instead of RELU
"""
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x +
0.044715 * torch.pow(x, 3))))
class PositionwiseFeedForward(nn.Module):
"""Implements FFN equation."""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
self.activation = GELU()
def forward(self, x):
return self.w_2(self.dropout(self.activation(self.w_1(x))))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'd_ff': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
from itertools import chain as chain
import torch.hub
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_pow_tanh_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 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp7 * tmp8
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x0, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_pow_tanh_0[grid(256)](buf0, buf1, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf1, (64, 4), (4, 1), 0), primals_4
class GELU(nn.Module):
"""
Paper Section 3.4, last paragraph notice that BERT used the GELU instead of RELU
"""
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x +
0.044715 * torch.pow(x, 3))))
class PositionwiseFeedForwardNew(nn.Module):
"""Implements FFN equation."""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForwardNew, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = nn.Dropout(dropout)
self.activation = GELU()
def forward(self, input_0):
primals_1 = self.w_1.weight
primals_2 = self.w_1.bias
primals_4 = self.w_2.weight
primals_5 = self.w_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
EddieMG/LateTemporalModeling3DCNN
|
PositionwiseFeedForward
| false
| 2,285
|
[
"MIT"
] | 0
|
94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
https://github.com/EddieMG/LateTemporalModeling3DCNN/tree/94c87dc1d31d09bc310d0e735a2e55453976cb0d
|
MaxPoolPad
|
import torch
import torch.utils.data
import torch.nn as nn
from torch import optim as optim
import torch.nn.parallel
class MaxPoolPad(nn.Module):
def __init__(self):
super(MaxPoolPad, self).__init__()
self.pad = nn.ZeroPad2d((1, 0, 1, 0))
self.pool = nn.MaxPool2d(3, stride=2, padding=1)
def forward(self, x):
x = self.pad(x)
x = self.pool(x)
x = x[:, :, 1:, 1:]
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn as nn
from torch import optim as optim
import torch.nn.parallel
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_max_pool2d_with_indices_0(in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 3 % 3
x0 = xindex % 3
x2 = xindex // 9
x4 = xindex
tmp0 = -1 + 2 * x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 5, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + 2 * x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = -2 + 2 * x1
tmp12 = tmp11 >= tmp1
tmp13 = -2 + 2 * x0
tmp14 = tmp13 >= tmp1
tmp15 = tmp12 & tmp14
tmp16 = tmp15 & tmp10
tmp17 = tl.load(in_ptr0 + (-10 + 2 * x0 + 8 * x1 + 16 * x2), tmp16 &
xmask, eviction_policy='evict_last', other=0.0)
tmp18 = tl.full(tmp17.shape, float('-inf'), tmp17.dtype)
tmp19 = tl.where(tmp10, tmp17, tmp18)
tmp20 = 2 * x0
tmp21 = tmp20 >= tmp1
tmp22 = tmp20 < tmp3
tmp23 = tmp21 & tmp22
tmp24 = tmp5 & tmp23
tmp25 = tmp12 & tmp7
tmp26 = tmp25 & tmp24
tmp27 = tl.load(in_ptr0 + (-9 + 2 * x0 + 8 * x1 + 16 * x2), tmp26 &
xmask, eviction_policy='evict_last', other=0.0)
tmp28 = tl.full(tmp27.shape, float('-inf'), tmp27.dtype)
tmp29 = tl.where(tmp24, tmp27, tmp28)
tmp30 = triton_helpers.maximum(tmp29, tmp19)
tmp31 = 1 + 2 * x0
tmp32 = tmp31 >= tmp1
tmp33 = tmp31 < tmp3
tmp34 = tmp32 & tmp33
tmp35 = tmp5 & tmp34
tmp36 = tmp12 & tmp21
tmp37 = tmp36 & tmp35
tmp38 = tl.load(in_ptr0 + (-8 + 2 * x0 + 8 * x1 + 16 * x2), tmp37 &
xmask, eviction_policy='evict_last', other=0.0)
tmp39 = tl.full(tmp38.shape, float('-inf'), tmp38.dtype)
tmp40 = tl.where(tmp35, tmp38, tmp39)
tmp41 = triton_helpers.maximum(tmp40, tmp30)
tmp42 = 2 * x1
tmp43 = tmp42 >= tmp1
tmp44 = tmp42 < tmp3
tmp45 = tmp43 & tmp44
tmp46 = tmp45 & tmp9
tmp47 = tmp2 & tmp14
tmp48 = tmp47 & tmp46
tmp49 = tl.load(in_ptr0 + (-6 + 2 * x0 + 8 * x1 + 16 * x2), tmp48 &
xmask, eviction_policy='evict_last', other=0.0)
tmp50 = tl.full(tmp49.shape, float('-inf'), tmp49.dtype)
tmp51 = tl.where(tmp46, tmp49, tmp50)
tmp52 = triton_helpers.maximum(tmp51, tmp41)
tmp53 = tmp45 & tmp23
tmp54 = tmp2 & tmp7
tmp55 = tmp54 & tmp53
tmp56 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x1 + 16 * x2), tmp55 &
xmask, eviction_policy='evict_last', other=0.0)
tmp57 = tl.full(tmp56.shape, float('-inf'), tmp56.dtype)
tmp58 = tl.where(tmp53, tmp56, tmp57)
tmp59 = triton_helpers.maximum(tmp58, tmp52)
tmp60 = tmp45 & tmp34
tmp61 = tmp2 & tmp21
tmp62 = tmp61 & tmp60
tmp63 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x1 + 16 * x2), tmp62 &
xmask, eviction_policy='evict_last', other=0.0)
tmp64 = tl.full(tmp63.shape, float('-inf'), tmp63.dtype)
tmp65 = tl.where(tmp60, tmp63, tmp64)
tmp66 = triton_helpers.maximum(tmp65, tmp59)
tmp67 = 1 + 2 * x1
tmp68 = tmp67 >= tmp1
tmp69 = tmp67 < tmp3
tmp70 = tmp68 & tmp69
tmp71 = tmp70 & tmp9
tmp72 = tmp43 & tmp14
tmp73 = tmp72 & tmp71
tmp74 = tl.load(in_ptr0 + (-2 + 2 * x0 + 8 * x1 + 16 * x2), tmp73 &
xmask, eviction_policy='evict_last', other=0.0)
tmp75 = tl.full(tmp74.shape, float('-inf'), tmp74.dtype)
tmp76 = tl.where(tmp71, tmp74, tmp75)
tmp77 = triton_helpers.maximum(tmp76, tmp66)
tmp78 = tmp70 & tmp23
tmp79 = tmp43 & tmp7
tmp80 = tmp79 & tmp78
tmp81 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x1 + 16 * x2), tmp80 &
xmask, eviction_policy='evict_last', other=0.0)
tmp82 = tl.full(tmp81.shape, float('-inf'), tmp81.dtype)
tmp83 = tl.where(tmp78, tmp81, tmp82)
tmp84 = triton_helpers.maximum(tmp83, tmp77)
tmp85 = tmp70 & tmp34
tmp86 = tmp43 & tmp21
tmp87 = tmp86 & tmp85
tmp88 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2), tmp87 & xmask,
eviction_policy='evict_last', other=0.0)
tmp89 = tl.full(tmp88.shape, float('-inf'), tmp88.dtype)
tmp90 = tl.where(tmp85, tmp88, tmp89)
tmp91 = triton_helpers.maximum(tmp90, tmp84)
tl.store(out_ptr0 + x4, tmp91, 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, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_max_pool2d_with_indices_0[grid(144)](
arg0_1, buf0, 144, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4, 2, 2), (36, 9, 3, 1), 4),
class MaxPoolPadNew(nn.Module):
def __init__(self):
super(MaxPoolPadNew, self).__init__()
self.pad = nn.ZeroPad2d((1, 0, 1, 0))
self.pool = nn.MaxPool2d(3, stride=2, padding=1)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Exir-lxr/crldr-prune-pytorch
|
MaxPoolPad
| false
| 2,286
|
[
"Apache-2.0"
] | 0
|
adeb5e0b24ce66ff9531d4d947f72412c1b5c033
|
https://github.com/Exir-lxr/crldr-prune-pytorch/tree/adeb5e0b24ce66ff9531d4d947f72412c1b5c033
|
DiceLoss
|
import torch
import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self, size_average=True, ignore_index=-100, reduce=True):
super(DiceLoss, self).__init__()
self.size_average = size_average
self.ignore_index = ignore_index
self.reduce = reduce
self.softMax = nn.Softmax(dim=1)
def forward(self, input, target, weight=None):
self.weight = weight
num_classes = input.size(1)
input = self.softMax(input)
one_hot = target.new(num_classes, num_classes).fill_(0)
for i in range(num_classes):
one_hot[i, i] = 1
target_onehot = one_hot[target]
target_onehot = target_onehot.unsqueeze(1).transpose(1, -1).squeeze(-1)
target_onehot = target_onehot.float()
input = input.float()
loss = self.dice_loss(input, target_onehot, self.weight)
return loss
def dice_loss(self, input, target, weight=None):
smooth = 1.0
loss = 0.0
n_classes = input.size(1)
for c in range(n_classes):
iflat = input[:, c].contiguous().view(-1)
tflat = target[:, c].contiguous().view(-1)
intersection = (iflat * tflat).sum()
if weight is not None:
w = weight[c]
else:
w = 1 / n_classes
w = torch.tensor(w)
w = w.float()
loss += w * (1 - (2.0 * intersection + smooth) / (iflat.sum() +
tflat.sum() + smooth))
return loss
def get_inputs():
return [torch.rand([64, 4, 4, 4]), torch.ones([1024], dtype=torch.int64)]
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
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), None, eviction_policy='evict_last'
)
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), None, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), None, 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, None)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), None, eviction_policy='evict_last'
)
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), None, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), None, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, None)
@triton.jit
def triton_poi_fused_index_2(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 // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4),
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tmp4
tmp7 = tl.full([1], 3, tl.int32)
tmp8 = tmp6 == tmp7
tmp9 = x0
tmp10 = tmp9 == tmp7
tmp11 = tl.full([1], 2, tl.int32)
tmp12 = tmp7 == tmp11
tmp13 = tmp9 == tmp11
tmp14 = tl.full([1], 1, tl.int32)
tmp15 = tmp11 == tmp14
tmp16 = tmp9 == tmp14
tmp17 = tl.full([1], 0, tl.int32)
tmp18 = tmp14 == tmp17
tmp19 = tmp9 == tmp17
tmp20 = tl.full([1], 1, tl.int64)
tmp21 = tl.full([1], 0, tl.int64)
tmp22 = tl.where(tmp19, tmp20, tmp21)
tmp23 = tl.where(tmp18, tmp22, tmp21)
tmp24 = tl.where(tmp16, tmp20, tmp23)
tmp25 = tmp11 == tmp17
tmp26 = tl.where(tmp25, tmp22, tmp21)
tmp27 = tl.where(tmp15, tmp24, tmp26)
tmp28 = tl.where(tmp13, tmp20, tmp27)
tmp29 = tmp7 == tmp14
tmp30 = tmp7 == tmp17
tmp31 = tl.where(tmp30, tmp22, tmp21)
tmp32 = tl.where(tmp29, tmp24, tmp31)
tmp33 = tl.where(tmp12, tmp28, tmp32)
tmp34 = tl.where(tmp10, tmp20, tmp33)
tmp35 = tmp6 == tmp11
tmp36 = tmp6 == tmp14
tmp37 = tmp6 == tmp17
tmp38 = tl.where(tmp37, tmp22, tmp21)
tmp39 = tl.where(tmp36, tmp24, tmp38)
tmp40 = tl.where(tmp35, tmp28, tmp39)
tmp41 = tl.where(tmp8, tmp34, tmp40)
tl.store(out_ptr0 + x2, tmp41, None)
@triton.jit
def triton_per_fused_add_clone_div_lift_fresh_mul_rsub_sum_view_3(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 1024
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 + (64 * (r0 // 16) + r0 % 16), None)
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr0 + (16 + 64 * (r0 // 16) + r0 % 16), None)
tmp14 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr0 + (48 + 64 * (r0 // 16) + r0 % 16), None)
tmp27 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp39 = tl.load(in_ptr0 + (32 + 64 * (r0 // 16) + r0 % 16), None)
tmp40 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp1.to(tl.float32)
tmp3 = tmp0 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = tl.broadcast_to(tmp2, [RBLOCK])
tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0))
tmp10 = tl.broadcast_to(tmp0, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp13 * tmp15
tmp17 = tl.broadcast_to(tmp16, [RBLOCK])
tmp19 = triton_helpers.promote_to_tensor(tl.sum(tmp17, 0))
tmp20 = tl.broadcast_to(tmp15, [RBLOCK])
tmp22 = triton_helpers.promote_to_tensor(tl.sum(tmp20, 0))
tmp23 = tl.broadcast_to(tmp13, [RBLOCK])
tmp25 = triton_helpers.promote_to_tensor(tl.sum(tmp23, 0))
tmp28 = tmp27.to(tl.float32)
tmp29 = tmp26 * tmp28
tmp30 = tl.broadcast_to(tmp29, [RBLOCK])
tmp32 = triton_helpers.promote_to_tensor(tl.sum(tmp30, 0))
tmp33 = tl.broadcast_to(tmp28, [RBLOCK])
tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0))
tmp36 = tl.broadcast_to(tmp26, [RBLOCK])
tmp38 = triton_helpers.promote_to_tensor(tl.sum(tmp36, 0))
tmp41 = tmp40.to(tl.float32)
tmp42 = tmp39 * tmp41
tmp43 = tl.broadcast_to(tmp42, [RBLOCK])
tmp45 = triton_helpers.promote_to_tensor(tl.sum(tmp43, 0))
tmp46 = tl.broadcast_to(tmp41, [RBLOCK])
tmp48 = triton_helpers.promote_to_tensor(tl.sum(tmp46, 0))
tmp49 = tl.broadcast_to(tmp39, [RBLOCK])
tmp51 = triton_helpers.promote_to_tensor(tl.sum(tmp49, 0))
tmp52 = 2.0
tmp53 = tmp6 * tmp52
tmp54 = 1.0
tmp55 = tmp53 + tmp54
tmp56 = tmp12 + tmp9
tmp57 = tmp56 + tmp54
tmp58 = tmp55 / tmp57
tmp59 = tmp54 - tmp58
tmp60 = 0.25
tmp61 = tmp60 * tmp59
tmp62 = 0.0
tmp63 = tmp61 + tmp62
tmp64 = tmp19 * tmp52
tmp65 = tmp64 + tmp54
tmp66 = tmp25 + tmp22
tmp67 = tmp66 + tmp54
tmp68 = tmp65 / tmp67
tmp69 = tmp54 - tmp68
tmp70 = tmp60 * tmp69
tmp71 = tmp63 + tmp70
tmp72 = tmp45 * tmp52
tmp73 = tmp72 + tmp54
tmp74 = tmp51 + tmp48
tmp75 = tmp74 + tmp54
tmp76 = tmp73 / tmp75
tmp77 = tmp54 - tmp76
tmp78 = tmp60 * tmp77
tmp79 = tmp71 + tmp78
tmp80 = tmp32 * tmp52
tmp81 = tmp80 + tmp54
tmp82 = tmp38 + tmp35
tmp83 = tmp82 + tmp54
tmp84 = tmp81 / tmp83
tmp85 = tmp54 - tmp84
tmp86 = tmp60 * tmp85
tmp87 = tmp79 + tmp86
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp87, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (64, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (1024,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(4096)](arg0_1, buf0, 4096, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((64, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(4096)](buf0, buf1, 4096, XBLOCK=
256, num_warps=4, num_stages=1)
del buf0
buf3 = empty_strided_cuda((1024, 4), (4, 1), torch.int64)
triton_poi_fused_index_2[grid(4096)](arg1_1, buf3, 4096, XBLOCK=128,
num_warps=4, num_stages=1)
del arg1_1
buf10 = empty_strided_cuda((), (), torch.float32)
buf13 = buf10
del buf10
buf17 = buf13
del buf13
triton_per_fused_add_clone_div_lift_fresh_mul_rsub_sum_view_3[grid(1)](
buf17, buf1, buf3, 1, 1024, num_warps=8, num_stages=1)
del buf1
del buf3
return buf17,
class DiceLossNew(nn.Module):
def __init__(self, size_average=True, ignore_index=-100, reduce=True):
super(DiceLossNew, self).__init__()
self.size_average = size_average
self.ignore_index = ignore_index
self.reduce = reduce
self.softMax = nn.Softmax(dim=1)
def dice_loss(self, input, target, weight=None):
smooth = 1.0
loss = 0.0
n_classes = input.size(1)
for c in range(n_classes):
iflat = input[:, c].contiguous().view(-1)
tflat = target[:, c].contiguous().view(-1)
intersection = (iflat * tflat).sum()
if weight is not None:
w = weight[c]
else:
w = 1 / n_classes
w = torch.tensor(w)
w = w.float()
loss += w * (1 - (2.0 * intersection + smooth) / (iflat.sum() +
tflat.sum() + smooth))
return loss
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
GTreeSoftware/DB-Enhance
|
DiceLoss
| false
| 2,287
|
[
"MIT"
] | 0
|
98332c62297db7756f5385c038089bb8736a27c0
|
https://github.com/GTreeSoftware/DB-Enhance/tree/98332c62297db7756f5385c038089bb8736a27c0
|
ConvTransposeInstanceNorm2d
|
import torch
import torch.nn as nn
from typing import Tuple
from typing import Union
class ConvTransposeInstanceNorm2d(nn.Module):
def __init__(self, in_channels: 'int', out_channels: 'int', kernel_size:
'Union[int, Tuple[int]]', stride: 'Union[int, Tuple[int]]'=1,
padding: 'Union[int, Tuple[int]]'=0, output_padding:
'Union[int, Tuple[int]]'=0, dilation: 'Union[int, Tuple[int]]'=1,
groups: 'int'=1, bias: 'bool'=True, padding_mode: 'str'='zeros'):
super().__init__()
self.dconv = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size, stride, padding, output_padding, groups, bias,
dilation, padding_mode)
self.norm = nn.InstanceNorm2d(out_channels)
def forward(self, x):
x = self.dconv(x)
x = self.norm(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from typing import Tuple
from typing import Union
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_convolution_0(in_out_ptr0,
in_ptr0, out_ptr0, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr
):
xnumel = 16
rnumel = 49
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, :]
rmask = rindex < rnumel
r2 = rindex
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + (r2 + 49 * x3), rmask & xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tl.where(rmask & xmask, tmp3, 0)
tmp6 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp8 = tl.where(rmask & xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 49, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(rmask & xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = tmp2 - tmp12
tmp20 = 49.0
tmp21 = tmp18 / tmp20
tmp22 = 1e-05
tmp23 = tmp21 + tmp22
tmp24 = libdevice.rsqrt(tmp23)
tmp25 = tmp19 * tmp24
tl.store(in_out_ptr0 + (r2 + 49 * x3), tmp2, rmask & xmask)
tl.store(out_ptr2 + (r2 + 49 * x3), tmp25, rmask & xmask)
tl.store(out_ptr3 + x3, tmp24, xmask)
tl.store(out_ptr0 + x3, tmp12, 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=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 7, 7), (196, 49, 7, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf6 = empty_strided_cuda((1, 16, 7, 7), (784, 49, 7, 1), torch.float32
)
buf5 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_convolution_0[grid(16)](buf1,
primals_2, buf2, buf6, buf5, 16, 49, XBLOCK=1, num_warps=2,
num_stages=1)
del primals_2
return reinterpret_tensor(buf6, (4, 4, 7, 7), (196, 49, 7, 1), 0
), primals_1, primals_3, buf1, reinterpret_tensor(buf5, (16,), (1,), 0
), reinterpret_tensor(buf2, (1, 16, 1, 1), (16, 1, 1, 1), 0)
class ConvTransposeInstanceNorm2dNew(nn.Module):
def __init__(self, in_channels: 'int', out_channels: 'int', kernel_size:
'Union[int, Tuple[int]]', stride: 'Union[int, Tuple[int]]'=1,
padding: 'Union[int, Tuple[int]]'=0, output_padding:
'Union[int, Tuple[int]]'=0, dilation: 'Union[int, Tuple[int]]'=1,
groups: 'int'=1, bias: 'bool'=True, padding_mode: 'str'='zeros'):
super().__init__()
self.dconv = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size, stride, padding, output_padding, groups, bias,
dilation, padding_mode)
self.norm = nn.InstanceNorm2d(out_channels)
def forward(self, input_0):
primals_1 = self.dconv.weight
primals_2 = self.dconv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Geson-anko/ReimplementCycleGAN
|
ConvTransposeInstanceNorm2d
| false
| 2,288
|
[
"MIT"
] | 0
|
3bd40c519d53a7ebb284c718e935e3832326633f
|
https://github.com/Geson-anko/ReimplementCycleGAN/tree/3bd40c519d53a7ebb284c718e935e3832326633f
|
Quantizing
|
import torch
import torch.nn as nn
from typing import Tuple
class Quantizing(nn.Module):
"""
This is quantizing layer.
"""
__initialized: 'bool' = True
def __init__(self, num_quantizing: 'int', quantizing_dim: 'int',
_weight: 'torch.Tensor'=None, initialize_by_dataset: 'bool'=True,
mean: 'float'=0.0, std: 'float'=1.0, dtype: 'torch.dtype'=None,
device: 'torch.device'=None):
super().__init__()
assert num_quantizing > 0
assert quantizing_dim > 0
self.num_quantizing = num_quantizing
self.quantizing_dim = quantizing_dim
self.initialize_by_dataset = initialize_by_dataset
self.mean, self.std = mean, std
if _weight is None:
self.weight = nn.Parameter(torch.empty(num_quantizing,
quantizing_dim, dtype=dtype, device=device))
nn.init.normal_(self.weight, mean=mean, std=std)
if initialize_by_dataset:
self.__initialized = False
self.__initialized_length = 0
else:
assert _weight.dim() == 2
assert _weight.size(0) == num_quantizing
assert _weight.size(1) == quantizing_dim
self.weight = nn.Parameter(_weight.to(device))
def forward(self, x: 'torch.Tensor') ->Tuple[torch.Tensor]:
"""
x : shape is (*, E), and weight shape is (Q, E).
return -> ( quantized : shape is (*, E), quantized_idx : shape is (*,) )
"""
input_size = x.shape
h = x.view(-1, self.quantizing_dim)
if not self.__initialized and self.initialize_by_dataset:
getting_len = self.num_quantizing - self.__initialized_length
init_weight = h[torch.randperm(len(h))[:getting_len]]
_until = self.__initialized_length + init_weight.size(0)
self.weight.data[self.__initialized_length:_until] = init_weight
self.__initialized_length = _until
None
if _until >= self.num_quantizing:
self.__initialized = True
None
delta = self.weight.unsqueeze(0) - h.unsqueeze(1)
dist = torch.sum(delta * delta, dim=-1)
q_idx = torch.argmin(dist, dim=-1)
q_data = self.weight[q_idx]
return q_data.view(input_size), q_idx.view(input_size[:1])
def from_idx(self, idx: 'torch.Tensor') ->torch.Tensor:
"""
idx: shape is (*, ). int tensor.
return -> (*, E) float tensor
"""
input_size = idx.shape
i = idx.view(-1)
q_data = self.weight[i].view(*input_size, self.quantizing_dim)
return q_data
def load_state_dict(self, state_dict, strict: 'bool'):
self.__initialized = True
return super().load_state_dict(state_dict, strict=strict)
def __repr__(self):
s = f'Quantizing({self.num_quantizing}, {self.quantizing_dim})'
return s
def isInitialized(self) ->bool:
return self.__initialized
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'num_quantizing': 4, 'quantizing_dim': 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_poi_fused_argmin_mul_sub_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + 1)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + 2)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK])
tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr0 + 3)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK])
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp23 = tl.load(in_ptr0 + 4)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK])
tmp27 = tl.load(in_ptr0 + 5)
tmp28 = tl.broadcast_to(tmp27, [XBLOCK])
tmp32 = tl.load(in_ptr0 + 6)
tmp33 = tl.broadcast_to(tmp32, [XBLOCK])
tmp37 = tl.load(in_ptr0 + 7)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK])
tmp57 = tl.load(in_ptr0 + 8)
tmp58 = tl.broadcast_to(tmp57, [XBLOCK])
tmp61 = tl.load(in_ptr0 + 9)
tmp62 = tl.broadcast_to(tmp61, [XBLOCK])
tmp66 = tl.load(in_ptr0 + 10)
tmp67 = tl.broadcast_to(tmp66, [XBLOCK])
tmp71 = tl.load(in_ptr0 + 11)
tmp72 = tl.broadcast_to(tmp71, [XBLOCK])
tmp90 = tl.load(in_ptr0 + 12)
tmp91 = tl.broadcast_to(tmp90, [XBLOCK])
tmp94 = tl.load(in_ptr0 + 13)
tmp95 = tl.broadcast_to(tmp94, [XBLOCK])
tmp99 = tl.load(in_ptr0 + 14)
tmp100 = tl.broadcast_to(tmp99, [XBLOCK])
tmp104 = tl.load(in_ptr0 + 15)
tmp105 = tl.broadcast_to(tmp104, [XBLOCK])
tmp3 = tmp1 - tmp2
tmp4 = tmp3 * tmp3
tmp8 = tmp6 - tmp7
tmp9 = tmp8 * tmp8
tmp10 = tmp4 + tmp9
tmp14 = tmp12 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tmp10 + tmp15
tmp20 = tmp18 - tmp19
tmp21 = tmp20 * tmp20
tmp22 = tmp16 + tmp21
tmp25 = tmp24 - tmp2
tmp26 = tmp25 * tmp25
tmp29 = tmp28 - tmp7
tmp30 = tmp29 * tmp29
tmp31 = tmp26 + tmp30
tmp34 = tmp33 - tmp13
tmp35 = tmp34 * tmp34
tmp36 = tmp31 + tmp35
tmp39 = tmp38 - tmp19
tmp40 = tmp39 * tmp39
tmp41 = tmp36 + tmp40
tmp42 = tmp22 < tmp41
tmp43 = tmp22 == tmp41
tmp44 = tmp22 != tmp22
tmp45 = tmp41 != tmp41
tmp46 = tmp44 > tmp45
tmp47 = tmp42 | tmp46
tmp48 = tmp44 & tmp45
tmp49 = tmp43 | tmp48
tmp50 = tl.full([1], 0, tl.int64)
tmp51 = tl.full([1], 1, tl.int64)
tmp52 = tmp50 < tmp51
tmp53 = tmp49 & tmp52
tmp54 = tmp47 | tmp53
tmp55 = tl.where(tmp54, tmp22, tmp41)
tmp56 = tl.where(tmp54, tmp50, tmp51)
tmp59 = tmp58 - tmp2
tmp60 = tmp59 * tmp59
tmp63 = tmp62 - tmp7
tmp64 = tmp63 * tmp63
tmp65 = tmp60 + tmp64
tmp68 = tmp67 - tmp13
tmp69 = tmp68 * tmp68
tmp70 = tmp65 + tmp69
tmp73 = tmp72 - tmp19
tmp74 = tmp73 * tmp73
tmp75 = tmp70 + tmp74
tmp76 = tmp55 < tmp75
tmp77 = tmp55 == tmp75
tmp78 = tmp55 != tmp55
tmp79 = tmp75 != tmp75
tmp80 = tmp78 > tmp79
tmp81 = tmp76 | tmp80
tmp82 = tmp78 & tmp79
tmp83 = tmp77 | tmp82
tmp84 = tl.full([1], 2, tl.int64)
tmp85 = tmp56 < tmp84
tmp86 = tmp83 & tmp85
tmp87 = tmp81 | tmp86
tmp88 = tl.where(tmp87, tmp55, tmp75)
tmp89 = tl.where(tmp87, tmp56, tmp84)
tmp92 = tmp91 - tmp2
tmp93 = tmp92 * tmp92
tmp96 = tmp95 - tmp7
tmp97 = tmp96 * tmp96
tmp98 = tmp93 + tmp97
tmp101 = tmp100 - tmp13
tmp102 = tmp101 * tmp101
tmp103 = tmp98 + tmp102
tmp106 = tmp105 - tmp19
tmp107 = tmp106 * tmp106
tmp108 = tmp103 + tmp107
tmp109 = tmp88 < tmp108
tmp110 = tmp88 == tmp108
tmp111 = tmp88 != tmp88
tmp112 = tmp108 != tmp108
tmp113 = tmp111 > tmp112
tmp114 = tmp109 | tmp113
tmp115 = tmp111 & tmp112
tmp116 = tmp110 | tmp115
tmp117 = tl.full([1], 3, tl.int64)
tmp118 = tmp89 < tmp117
tmp119 = tmp116 & tmp118
tmp120 = tmp114 | tmp119
tl.where(tmp120, tmp88, tmp108)
tmp122 = tl.where(tmp120, tmp89, tmp117)
tl.store(out_ptr0 + x0, tmp122, xmask)
@triton.jit
def triton_poi_fused_index_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
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
'index out of bounds: 0 <= tmp4 < 4')
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, 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,), (1,), torch.int64)
get_raw_stream(0)
triton_poi_fused_argmin_mul_sub_sum_0[grid(4)](primals_2, primals_1,
buf0, 4, XBLOCK=4, num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_index_1[grid(16)](buf0, primals_2, buf1, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
return buf1, buf0, buf0
class QuantizingNew(nn.Module):
"""
This is quantizing layer.
"""
__initialized: 'bool' = True
def __init__(self, num_quantizing: 'int', quantizing_dim: 'int',
_weight: 'torch.Tensor'=None, initialize_by_dataset: 'bool'=True,
mean: 'float'=0.0, std: 'float'=1.0, dtype: 'torch.dtype'=None,
device: 'torch.device'=None):
super().__init__()
assert num_quantizing > 0
assert quantizing_dim > 0
self.num_quantizing = num_quantizing
self.quantizing_dim = quantizing_dim
self.initialize_by_dataset = initialize_by_dataset
self.mean, self.std = mean, std
if _weight is None:
self.weight = nn.Parameter(torch.empty(num_quantizing,
quantizing_dim, dtype=dtype, device=device))
nn.init.normal_(self.weight, mean=mean, std=std)
if initialize_by_dataset:
self.__initialized = False
self.__initialized_length = 0
else:
assert _weight.dim() == 2
assert _weight.size(0) == num_quantizing
assert _weight.size(1) == quantizing_dim
self.weight = nn.Parameter(_weight.to(device))
def from_idx(self, idx: 'torch.Tensor') ->torch.Tensor:
"""
idx: shape is (*, ). int tensor.
return -> (*, E) float tensor
"""
input_size = idx.shape
i = idx.view(-1)
q_data = self.weight[i].view(*input_size, self.quantizing_dim)
return q_data
def load_state_dict(self, state_dict, strict: 'bool'):
self.__initialized = True
return super().load_state_dict(state_dict, strict=strict)
def __repr__(self):
s = f'Quantizing({self.num_quantizing}, {self.quantizing_dim})'
return s
def isInitialized(self) ->bool:
return self.__initialized
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0], output[1]
|
Geson-anko/VQ_AutoEncoder
|
Quantizing
| false
| 2,289
|
[
"MIT"
] | 0
|
62e1694de38ea6f152891e19abc190ad4048e587
|
https://github.com/Geson-anko/VQ_AutoEncoder/tree/62e1694de38ea6f152891e19abc190ad4048e587
|
Sine
|
import torch
from torch import nn
class Sine(nn.Module):
def __init__(self, w0=30):
super().__init__()
self.w0 = w0
def forward(self, input):
return torch.sin(self.w0 * 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 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_mul_sin_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 30.0
tmp2 = tmp0 * tmp1
tmp3 = tl_math.sin(tmp2)
tl.store(out_ptr0 + x0, tmp3, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sin_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SineNew(nn.Module):
def __init__(self, w0=30):
super().__init__()
self.w0 = w0
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Fred62879/ACORN
|
Sine
| false
| 2,290
|
[
"MIT"
] | 0
|
2de0bf747d595dbdc4d67311fb8f46cf47f9b4cb
|
https://github.com/Fred62879/ACORN/tree/2de0bf747d595dbdc4d67311fb8f46cf47f9b4cb
|
BasicConv
|
import torch
import torch.nn as nn
import torch.onnx
import torch.nn.parallel
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1,
padding=0, dilation=1, groups=1, relu=True, bn=False, bias=False):
super(BasicConv, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=
kernel_size, stride=stride, padding=padding, dilation=dilation,
groups=groups, bias=bias)
self.bn = nn.BatchNorm2d(out_planes, eps=1e-05, momentum=0.01,
affine=True) if bn else None
self.relu = nn.ReLU() if relu else None
def forward(self, x):
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_planes': 4, 'out_planes': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.onnx
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = 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))
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, 4, 1, 1), (4, 1, 1, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16)](buf1, buf2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
return buf1, primals_1, primals_2, buf2
class BasicConvNew(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1,
padding=0, dilation=1, groups=1, relu=True, bn=False, bias=False):
super(BasicConvNew, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=
kernel_size, stride=stride, padding=padding, dilation=dilation,
groups=groups, bias=bias)
self.bn = nn.BatchNorm2d(out_planes, eps=1e-05, momentum=0.01,
affine=True) if bn else None
self.relu = nn.ReLU() if relu else None
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
Ganzooo/soil_segmentation
|
BasicConv
| false
| 2,291
|
[
"MIT"
] | 0
|
56f410e3e184f24e52dd4b542ea309f0d203ca00
|
https://github.com/Ganzooo/soil_segmentation/tree/56f410e3e184f24e52dd4b542ea309f0d203ca00
|
Hardswish
|
import torch
from torch.nn import functional as F
import torch.nn as nn
class Hardswish(nn.Module):
@staticmethod
def forward(x):
return x * F.hardtanh(x + 3, 0.0, 6.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=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class HardswishNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
GoalballAnalysis/GUI
|
Hardswish
| false
| 2,292
|
[
"MIT"
] | 0
|
c7f1cc27f4fd7f861c3ca09f5ca25d1a3f19a8a7
|
https://github.com/GoalballAnalysis/GUI/tree/c7f1cc27f4fd7f861c3ca09f5ca25d1a3f19a8a7
|
TransitionUp
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.onnx
import torch.nn.parallel
class TransitionUp(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
def forward(self, x, skip, concat=True):
out = F.interpolate(x, size=(skip.size(2), skip.size(3)), mode=
'bilinear', align_corners=True)
if concat:
out = torch.cat([out, skip], 1)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.onnx
import torch.nn.parallel
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 = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 4
x0 = xindex % 4
x2 = xindex // 16
x4 = xindex // 64
x7 = xindex % 64
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 + 128 * x4), tmp38, xmask)
@triton.jit
def triton_poi_fused_cat_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
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tl.store(out_ptr0 + (x0 + 128 * x1), tmp0, 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)
buf3 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
buf1 = reinterpret_tensor(buf3, (4, 4, 4, 4), (128, 16, 4, 1), 0)
get_raw_stream(0)
triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_0[grid
(256)](arg1_1, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
buf2 = reinterpret_tensor(buf3, (4, 4, 4, 4), (128, 16, 4, 1), 64)
triton_poi_fused_cat_1[grid(256)](arg0_1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf3,
class TransitionUpNew(nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Ganzooo/soil_segmentation
|
TransitionUp
| false
| 2,293
|
[
"MIT"
] | 0
|
56f410e3e184f24e52dd4b542ea309f0d203ca00
|
https://github.com/Ganzooo/soil_segmentation/tree/56f410e3e184f24e52dd4b542ea309f0d203ca00
|
AddLayer
|
import torch
from torch import nn
import torch.utils.checkpoint
class AddLayer(nn.Module):
def __init__(self, t1, t2):
super(AddLayer, self).__init__()
self.t1 = t1
self.t2 = t2
def forward(self, x, y):
return x + y
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'t1': 4, 't2': 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
import torch.utils.checkpoint
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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x0, tmp2, 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_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 AddLayerNew(nn.Module):
def __init__(self, t1, t2):
super(AddLayerNew, self).__init__()
self.t1 = t1
self.t2 = t2
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
DeepPoolML/DeepPool
|
AddLayer
| false
| 2,294
|
[
"MIT"
] | 0
|
7f823f26747c9399524e74f2d81c99a2bb677f7c
|
https://github.com/DeepPoolML/DeepPool/tree/7f823f26747c9399524e74f2d81c99a2bb677f7c
|
MyModel
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class MyModel(nn.Module):
def __init__(self, state_size, action_size):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, action_size)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def select_action(self, state):
self.eval()
x = self.forward(state)
self.train()
return x.max(0)[1]
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 64), (64, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (4, 64), (64, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1,
primals_2, buf6, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf3,
primals_5, buf5, 4096, 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, 64),
(64, 1), 0), reinterpret_tensor(primals_6, (64, 4), (1, 64), 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, 64), (64, 1), 0), reinterpret_tensor(
buf3, (64, 64), (64, 1), 0), primals_6, buf5, primals_4, buf6
class MyModelNew(nn.Module):
def __init__(self, state_size, action_size):
super(MyModelNew, self).__init__()
self.fc1 = nn.Linear(state_size, 64)
self.fc2 = nn.Linear(64, 64)
self.fc3 = nn.Linear(64, action_size)
def select_action(self, state):
self.eval()
x = self.forward(state)
self.train()
return x.max(0)[1]
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_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]
|
Ghazalmg/slimevolleygym
|
MyModel
| false
| 2,295
|
[
"Apache-2.0"
] | 0
|
d880a35625c22bbe0bc10fa0352495f0aea06364
|
https://github.com/Ghazalmg/slimevolleygym/tree/d880a35625c22bbe0bc10fa0352495f0aea06364
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.