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
|
|---|---|---|---|---|---|---|---|---|---|---|
M_VDNMixer
|
from _paritybench_helpers import _mock_config
import torch
import numpy as np
import torch.nn as nn
def to_torch(input):
return torch.from_numpy(input) if type(input) == np.ndarray else input
class M_VDNMixer(nn.Module):
"""
Computes total Q values given agent q values and global states.
:param args: (namespace) contains information about hyperparameters and algorithm configuration (unused).
:param num_agents: (int) number of agents in env
:param cent_obs_dim: (int) dimension of the centralized state (unused).
:param device: (torch.Device) torch device on which to do computations.
:param multidiscrete_list: (list) list of each action dimension if action space is multidiscrete
"""
def __init__(self, args, num_agents, cent_obs_dim, device,
multidiscrete_list=None):
"""
init mixer class
"""
super(M_VDNMixer, self).__init__()
self.device = device
self.num_agents = num_agents
if multidiscrete_list:
self.num_mixer_q_inps = sum(multidiscrete_list)
else:
self.num_mixer_q_inps = self.num_agents
def forward(self, agent_q_inps):
"""
Computes Q_tot by summing individual agent q values.
:param agent_q_inps: (torch.Tensor) individual agent q values
:return Q_tot: (torch.Tensor) computed Q_tot values
"""
agent_q_inps = to_torch(agent_q_inps)
return agent_q_inps.sum(dim=-1).view(-1, 1, 1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'args': _mock_config(), 'num_agents': 4, 'cent_obs_dim': 4,
'device': 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 numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sum_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 + 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
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sum_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (64, 1, 1), (1, 1, 1), 0),
def to_torch(input):
return torch.from_numpy(input) if type(input) == np.ndarray else input
class M_VDNMixerNew(nn.Module):
"""
Computes total Q values given agent q values and global states.
:param args: (namespace) contains information about hyperparameters and algorithm configuration (unused).
:param num_agents: (int) number of agents in env
:param cent_obs_dim: (int) dimension of the centralized state (unused).
:param device: (torch.Device) torch device on which to do computations.
:param multidiscrete_list: (list) list of each action dimension if action space is multidiscrete
"""
def __init__(self, args, num_agents, cent_obs_dim, device,
multidiscrete_list=None):
"""
init mixer class
"""
super(M_VDNMixerNew, self).__init__()
self.device = device
self.num_agents = num_agents
if multidiscrete_list:
self.num_mixer_q_inps = sum(multidiscrete_list)
else:
self.num_mixer_q_inps = self.num_agents
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Maxtoq/off-policy
|
M_VDNMixer
| false
| 16,099
|
[
"MIT"
] | 76
|
e866f13a3d144a29552c38f104bcdfb411036138
|
https://github.com/Maxtoq/off-policy/tree/e866f13a3d144a29552c38f104bcdfb411036138
|
ycbcr_to_rgb_jpeg
|
import torch
import numpy as np
import torch.nn as nn
class ycbcr_to_rgb_jpeg(nn.Module):
""" Converts YCbCr image to RGB JPEG
Input:
image(tensor): batch x height x width x 3
Outpput:
result(tensor): batch x 3 x height x width
"""
def __init__(self):
super(ycbcr_to_rgb_jpeg, self).__init__()
matrix = np.array([[1.0, 0.0, 1.402], [1, -0.344136, -0.714136], [1,
1.772, 0]], dtype=np.float32).T
self.shift = nn.Parameter(torch.tensor([0, -128.0, -128.0]))
self.matrix = nn.Parameter(torch.from_numpy(matrix))
def forward(self, image):
result = torch.tensordot(image + self.shift, self.matrix, dims=1)
result.view(image.shape)
return result.permute(0, 3, 1, 2)
def get_inputs():
return [torch.rand([4, 4, 4, 3])]
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 numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 3
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (3,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 3), (48, 12, 3, 1))
assert_size_stride(primals_3, (3, 3), (1, 3))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 3), (48, 12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(192)](primals_2, primals_1, buf0, 192,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 3), (3, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 3), (3, 1), 0),
primals_3, out=buf1)
return reinterpret_tensor(buf1, (4, 3, 4, 4), (48, 1, 12, 3), 0
), reinterpret_tensor(buf0, (64, 3), (3, 1), 0), reinterpret_tensor(
primals_3, (3, 3), (3, 1), 0)
class ycbcr_to_rgb_jpegNew(nn.Module):
""" Converts YCbCr image to RGB JPEG
Input:
image(tensor): batch x height x width x 3
Outpput:
result(tensor): batch x 3 x height x width
"""
def __init__(self):
super(ycbcr_to_rgb_jpegNew, self).__init__()
matrix = np.array([[1.0, 0.0, 1.402], [1, -0.344136, -0.714136], [1,
1.772, 0]], dtype=np.float32).T
self.shift = nn.Parameter(torch.tensor([0, -128.0, -128.0]))
self.matrix = nn.Parameter(torch.from_numpy(matrix))
def forward(self, input_0):
primals_1 = self.shift
primals_3 = self.matrix
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
mlomnitz/DifferentiableJPEG
|
ycbcr_to_rgb_jpeg
| false
| 16,100
|
[
"MIT"
] | 86
|
a5767feba955a1bcb78600135a09c36a806f6249
|
https://github.com/mlomnitz/DifferentiableJPEG/tree/a5767feba955a1bcb78600135a09c36a806f6249
|
LightHead
|
import torch
from torch import nn
class RMSNorm(nn.Module):
"""An implementation of RMS Normalization.
# https://catalyst-team.github.io/catalyst/_modules/catalyst/contrib/nn/modules/rms_norm.html#RMSNorm
"""
def __init__(self, dimension: 'int', epsilon: 'float'=1e-08, is_bias:
'bool'=False):
"""
Args:
dimension (int): the dimension of the layer output to normalize
epsilon (float): an epsilon to prevent dividing by zero
in case the layer has zero variance. (default = 1e-8)
is_bias (bool): a boolean value whether to include bias term
while normalization
"""
super().__init__()
self.dimension = dimension
self.epsilon = epsilon
self.is_bias = is_bias
self.scale = nn.Parameter(torch.ones(self.dimension))
if self.is_bias:
self.bias = nn.Parameter(torch.zeros(self.dimension))
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x_std = torch.sqrt(torch.mean(x ** 2, -1, keepdim=True))
x_norm = x / (x_std + self.epsilon)
if self.is_bias:
return self.scale * x_norm + self.bias
return self.scale * x_norm
class LightHead(nn.Module):
def __init__(self, in_features, num_classes):
super().__init__()
self.norm = RMSNorm(in_features)
self.fc = nn.Linear(in_features, num_classes)
def forward(self, x):
x = self.norm(x)
x = self.fc(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_div_mean_mul_pow_sqrt_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 % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp3 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = libdevice.sqrt(tmp14)
tmp16 = 1e-08
tmp17 = tmp15 + tmp16
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tl.store(out_ptr0 + x2, tmp19, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mean_mul_pow_sqrt_0[grid(256)](primals_2,
primals_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_4
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_1, reinterpret_tensor(buf0, (64, 4), (4, 1), 0), primals_3
class RMSNorm(nn.Module):
"""An implementation of RMS Normalization.
# https://catalyst-team.github.io/catalyst/_modules/catalyst/contrib/nn/modules/rms_norm.html#RMSNorm
"""
def __init__(self, dimension: 'int', epsilon: 'float'=1e-08, is_bias:
'bool'=False):
"""
Args:
dimension (int): the dimension of the layer output to normalize
epsilon (float): an epsilon to prevent dividing by zero
in case the layer has zero variance. (default = 1e-8)
is_bias (bool): a boolean value whether to include bias term
while normalization
"""
super().__init__()
self.dimension = dimension
self.epsilon = epsilon
self.is_bias = is_bias
self.scale = nn.Parameter(torch.ones(self.dimension))
if self.is_bias:
self.bias = nn.Parameter(torch.zeros(self.dimension))
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x_std = torch.sqrt(torch.mean(x ** 2, -1, keepdim=True))
x_norm = x / (x_std + self.epsilon)
if self.is_bias:
return self.scale * x_norm + self.bias
return self.scale * x_norm
class LightHeadNew(nn.Module):
def __init__(self, in_features, num_classes):
super().__init__()
self.norm = RMSNorm(in_features)
self.fc = nn.Linear(in_features, num_classes)
def forward(self, input_0):
primals_2 = self.norm.scale
primals_3 = self.fc.weight
primals_4 = self.fc.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
mohamedbakrey12/prpjectINDeepLearning
|
LightHead
| false
| 16,101
|
[
"MIT"
] | 122
|
b6106ee13ff9377e4a84bee4814bd54a34156930
|
https://github.com/mohamedbakrey12/prpjectINDeepLearning/tree/b6106ee13ff9377e4a84bee4814bd54a34156930
|
TVLoss
|
import torch
from torch import nn
from torch.nn import functional as F
class TVLoss(nn.Module):
def forward(self, input):
input = F.pad(input, (0, 1, 0, 1), 'replicate')
x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
diff = x_diff ** 2 + y_diff ** 2 + 1e-08
return diff.mean(dim=1).sqrt().mean()
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
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_mean_pow_sqrt_sub_0(in_out_ptr0, in_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 4
r1 = rindex // 4 % 4
r2 = rindex // 16
tmp0 = tl.load(in_ptr0 + (4 * (3 * (3 <= r1) + r1 * (r1 < 3)) + 64 * r2 +
(3 * (3 <= 1 + r0) + (1 + r0) * (1 + r0 < 3))), None)
tmp1 = tl.load(in_ptr0 + (4 * (3 * (3 <= r1) + r1 * (r1 < 3)) + 64 * r2 +
(3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp4 = tl.load(in_ptr0 + (4 * (3 * (3 <= 1 + r1) + (1 + r1) * (1 + r1 <
3)) + 64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp10 = tl.load(in_ptr0 + (16 + 4 * (3 * (3 <= r1) + r1 * (r1 < 3)) +
64 * r2 + (3 * (3 <= 1 + r0) + (1 + r0) * (1 + r0 < 3))), None)
tmp11 = tl.load(in_ptr0 + (16 + 4 * (3 * (3 <= r1) + r1 * (r1 < 3)) +
64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp14 = tl.load(in_ptr0 + (16 + 4 * (3 * (3 <= 1 + r1) + (1 + r1) * (1 +
r1 < 3)) + 64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp20 = tl.load(in_ptr0 + (32 + 4 * (3 * (3 <= r1) + r1 * (r1 < 3)) +
64 * r2 + (3 * (3 <= 1 + r0) + (1 + r0) * (1 + r0 < 3))), None)
tmp21 = tl.load(in_ptr0 + (32 + 4 * (3 * (3 <= r1) + r1 * (r1 < 3)) +
64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp24 = tl.load(in_ptr0 + (32 + 4 * (3 * (3 <= 1 + r1) + (1 + r1) * (1 +
r1 < 3)) + 64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp30 = tl.load(in_ptr0 + (48 + 4 * (3 * (3 <= r1) + r1 * (r1 < 3)) +
64 * r2 + (3 * (3 <= 1 + r0) + (1 + r0) * (1 + r0 < 3))), None)
tmp31 = tl.load(in_ptr0 + (48 + 4 * (3 * (3 <= r1) + r1 * (r1 < 3)) +
64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp34 = tl.load(in_ptr0 + (48 + 4 * (3 * (3 <= 1 + r1) + (1 + r1) * (1 +
r1 < 3)) + 64 * r2 + (3 * (3 <= r0) + r0 * (r0 < 3))), None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp5 = tmp4 - tmp1
tmp6 = tmp5 * tmp5
tmp7 = tmp3 + tmp6
tmp8 = 1e-08
tmp9 = tmp7 + tmp8
tmp12 = tmp10 - tmp11
tmp13 = tmp12 * tmp12
tmp15 = tmp14 - tmp11
tmp16 = tmp15 * tmp15
tmp17 = tmp13 + tmp16
tmp18 = tmp17 + tmp8
tmp19 = tmp9 + tmp18
tmp22 = tmp20 - tmp21
tmp23 = tmp22 * tmp22
tmp25 = tmp24 - tmp21
tmp26 = tmp25 * tmp25
tmp27 = tmp23 + tmp26
tmp28 = tmp27 + tmp8
tmp29 = tmp19 + tmp28
tmp32 = tmp30 - tmp31
tmp33 = tmp32 * tmp32
tmp35 = tmp34 - tmp31
tmp36 = tmp35 * tmp35
tmp37 = tmp33 + tmp36
tmp38 = tmp37 + tmp8
tmp39 = tmp29 + tmp38
tmp40 = 4.0
tmp41 = tmp39 / tmp40
tmp42 = libdevice.sqrt(tmp41)
tmp43 = tl.broadcast_to(tmp42, [XBLOCK, RBLOCK])
tmp45 = tl.sum(tmp43, 1)[:, None]
tmp46 = 64.0
tmp47 = tmp45 / tmp46
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp47, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_mean_pow_sqrt_sub_0[grid(1)](buf2, arg0_1, 1,
64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf2,
class TVLossNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
momo-the-monster/vqgan-clip-app
|
TVLoss
| false
| 16,102
|
[
"MIT"
] | 63
|
56cfc0a53928d6d8f90ed8c79439afb4430bc118
|
https://github.com/momo-the-monster/vqgan-clip-app/tree/56cfc0a53928d6d8f90ed8c79439afb4430bc118
|
ClassicalConv2
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.utils.prune
import torch.backends.cudnn
import torch.cuda
import torch.nn
import torch.utils.data
class ClassicalConv2(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 4, 2, 1)
self.conv2 = nn.Conv2d(4, 4, 1, 1)
self.conv3 = nn.Conv2d(4, 4, 2, 1)
self.conv4 = nn.Conv2d(4, 4, 1, 1)
self.conv5 = nn.Conv2d(4, 10, 2, 1)
self.act = lambda x: x * x
def forward(self, x):
x = F.avg_pool2d(x, 6)
x = self.conv1(x)
x = self.act(x)
x = self.conv2(x)
x = self.act(x)
x = self.conv3(x)
x = self.act(x)
x = self.conv4(x)
x = self.act(x)
x = self.conv5(x)
output = F.log_softmax(x, dim=1)
return output.squeeze()
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.utils.prune
import torch.backends.cudnn
import torch.cuda
import torch.nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_mul_0(in_out_ptr0, in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1296
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 81 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tmp2 * tmp2
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp3, xmask)
@triton.jit
def triton_poi_fused_convolution_mul_1(in_out_ptr0, in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 64 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tmp2 * tmp2
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp3, xmask)
@triton.jit
def triton_per_fused__log_softmax_convolution_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 196
rnumel = 10
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r2 = rindex
x0 = xindex % 49
x1 = xindex // 49
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 49 * r2 + 490 * x1), rmask & xmask,
other=0.0)
tmp1 = tl.load(in_ptr1 + r2, rmask, eviction_policy='evict_last', other=0.0
)
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(rmask & xmask, tmp3, float('-inf'))
tmp6 = triton_helpers.max2(tmp5, 1)[:, None]
tmp7 = tmp2 - tmp6
tmp8 = tl_math.exp(tmp7)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.where(rmask & xmask, tmp9, 0)
tmp12 = tl.sum(tmp11, 1)[:, None]
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp12, xmask)
@triton.jit
def triton_poi_fused__log_softmax__log_softmax_backward_data_convolution_squeeze_3(
in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1960
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 49 % 10
x0 = xindex % 49
x2 = xindex // 490
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 49 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr3 + (x0 + 49 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = tl_math.log(tmp5)
tmp7 = tmp4 - tmp6
tmp8 = tl_math.exp(tmp7)
tl.store(out_ptr0 + x3, tmp7, xmask)
tl.store(out_ptr1 + x3, 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) = args
args.clear()
assert_size_stride(primals_1, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_2, (4, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 2, 2), (16, 4, 2, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (10, 4, 2, 2), (16, 4, 2, 1))
assert_size_stride(primals_11, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten.avg_pool2d.default(primals_1, [6, 6], [6, 6],
[0, 0], False, True, None)
del primals_1
buf1 = buf0
del buf0
buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 9, 9), (324, 81, 9, 1))
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_mul_0[grid(1296)](buf3, primals_3,
buf4, 1296, XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf5 = extern_kernels.convolution(buf4, primals_4, 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, 9, 9), (324, 81, 9, 1))
buf6 = buf5
del buf5
buf7 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32)
triton_poi_fused_convolution_mul_0[grid(1296)](buf6, primals_5,
buf7, 1296, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf8 = extern_kernels.convolution(buf7, primals_6, 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, 8, 8), (256, 64, 8, 1))
buf9 = buf8
del buf8
buf10 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32
)
triton_poi_fused_convolution_mul_1[grid(1024)](buf9, primals_7,
buf10, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf11 = extern_kernels.convolution(buf10, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 4, 8, 8), (256, 64, 8, 1))
buf12 = buf11
del buf11
buf13 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32
)
triton_poi_fused_convolution_mul_1[grid(1024)](buf12, primals_9,
buf13, 1024, XBLOCK=256, 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, 10, 7, 7), (490, 49, 7, 1))
buf15 = empty_strided_cuda((4, 1, 7, 7), (49, 196, 7, 1), torch.float32
)
buf16 = empty_strided_cuda((4, 1, 7, 7), (49, 196, 7, 1), torch.float32
)
triton_per_fused__log_softmax_convolution_2[grid(196)](buf14,
primals_11, buf15, buf16, 196, 10, XBLOCK=1, num_warps=2,
num_stages=1)
buf17 = empty_strided_cuda((4, 10, 7, 7), (490, 49, 7, 1), torch.
float32)
buf18 = empty_strided_cuda((4, 10, 7, 7), (490, 49, 7, 1), torch.
float32)
triton_poi_fused__log_softmax__log_softmax_backward_data_convolution_squeeze_3[
grid(1960)](buf14, primals_11, buf15, buf16, buf17, buf18, 1960,
XBLOCK=128, num_warps=4, num_stages=1)
del buf14
del buf15
del buf16
del primals_11
return (buf17, primals_2, primals_4, primals_6, primals_8, primals_10,
buf1, buf3, buf4, buf6, buf7, buf9, buf10, buf12, buf13, buf18)
class ClassicalConv2New(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 4, 2, 1)
self.conv2 = nn.Conv2d(4, 4, 1, 1)
self.conv3 = nn.Conv2d(4, 4, 2, 1)
self.conv4 = nn.Conv2d(4, 4, 1, 1)
self.conv5 = nn.Conv2d(4, 10, 2, 1)
self.act = lambda x: x * x
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.conv5.weight
primals_11 = self.conv5.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
mit-han-lab/pytorch-quantum
|
ClassicalConv2
| false
| 16,103
|
[
"MIT"
] | 98
|
05cf000d689307f6b1fe02d12744ad455685935b
|
https://github.com/mit-han-lab/pytorch-quantum/tree/05cf000d689307f6b1fe02d12744ad455685935b
|
Anchor3DHead
|
import torch
import numpy as np
import torch.nn as nn
def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-06):
"""Calculate overlap between two set of bboxes.
If ``is_aligned `` is ``False``, then calculate the overlaps between each
bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned
pair of bboxes1 and bboxes2.
Args:
bboxes1 (Tensor): shape (B, m, 4) in <x1, y1, x2, y2> format or empty.
bboxes2 (Tensor): shape (B, n, 4) in <x1, y1, x2, y2> format or empty.
B indicates the batch dim, in shape (B1, B2, ..., Bn).
If ``is_aligned `` is ``True``, then m and n must be equal.
mode (str): "iou" (intersection over union) or "iof" (intersection over
foreground).
is_aligned (bool, optional): If True, then m and n must be equal.
Default False.
eps (float, optional): A value added to the denominator for numerical
stability. Default 1e-6.
Returns:
Tensor: shape (m, n) if ``is_aligned `` is False else shape (m,)
Example:
>>> bboxes1 = torch.FloatTensor([
>>> [0, 0, 10, 10],
>>> [10, 10, 20, 20],
>>> [32, 32, 38, 42],
>>> ])
>>> bboxes2 = torch.FloatTensor([
>>> [0, 0, 10, 20],
>>> [0, 10, 10, 19],
>>> [10, 10, 20, 20],
>>> ])
>>> overlaps = bbox_overlaps(bboxes1, bboxes2)
>>> assert overlaps.shape == (3, 3)
>>> overlaps = bbox_overlaps(bboxes1, bboxes2, is_aligned=True)
>>> assert overlaps.shape == (3, )
Example:
>>> empty = torch.empty(0, 4)
>>> nonempty = torch.FloatTensor([[0, 0, 10, 9]])
>>> assert tuple(bbox_overlaps(empty, nonempty).shape) == (0, 1)
>>> assert tuple(bbox_overlaps(nonempty, empty).shape) == (1, 0)
>>> assert tuple(bbox_overlaps(empty, empty).shape) == (0, 0)
"""
assert mode in ['iou', 'iof', 'giou'], f'Unsupported mode {mode}'
assert bboxes1.size(-1) == 4 or bboxes1.size(0) == 0
assert bboxes2.size(-1) == 4 or bboxes2.size(0) == 0
assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
batch_shape = bboxes1.shape[:-2]
rows = bboxes1.size(-2)
cols = bboxes2.size(-2)
if is_aligned:
assert rows == cols
if rows * cols == 0:
if is_aligned:
return bboxes1.new(batch_shape + (rows,))
else:
return bboxes1.new(batch_shape + (rows, cols))
area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] -
bboxes1[..., 1])
area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] -
bboxes2[..., 1])
if is_aligned:
lt = torch.max(bboxes1[..., :2], bboxes2[..., :2])
rb = torch.min(bboxes1[..., 2:], bboxes2[..., 2:])
wh = (rb - lt).clamp(min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1 + area2 - overlap
else:
union = area1
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :2], bboxes2[..., :2])
enclosed_rb = torch.max(bboxes1[..., 2:], bboxes2[..., 2:])
else:
lt = torch.max(bboxes1[..., :, None, :2], bboxes2[..., None, :, :2])
rb = torch.min(bboxes1[..., :, None, 2:], bboxes2[..., None, :, 2:])
wh = (rb - lt).clamp(min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1[..., None] + area2[..., None, :] - overlap
else:
union = area1[..., None]
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :, None, :2], bboxes2[...,
None, :, :2])
enclosed_rb = torch.max(bboxes1[..., :, None, 2:], bboxes2[...,
None, :, 2:])
eps = union.new_tensor([eps])
union = torch.max(union, eps)
ious = overlap / union
if mode in ['iou', 'iof']:
return ious
enclose_wh = (enclosed_rb - enclosed_lt).clamp(min=0)
enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
enclose_area = torch.max(enclose_area, eps)
gious = ious - (enclose_area - union) / enclose_area
return gious
def box3d_to_bev(boxes3d):
"""Convert rotated 3d boxes in XYZWHDR format to BEV in XYWHR format.
Args:
boxes3d (torch.Tensor): Rotated boxes in XYZWHDR format.
Returns:
torch.Tensor: Converted BEV boxes in XYWHR format.
"""
return boxes3d[:, [0, 1, 3, 4, 6]]
def limit_period(val, offset=0.5, period=np.pi):
"""Limit the value into a period for periodic function.
Args:
val (torch.Tensor): The value to be converted.
offset (float, optional): Offset to set the value range. Defaults to 0.5.
period ([type], optional): Period of the value. Defaults to np.pi.
Returns:
torch.Tensor: Value in the range of [-offset * period, (1-offset) * period]
"""
return val - torch.floor(val / period + offset) * period
def box3d_to_bev2d(boxes3d):
"""Convert rotated 3d boxes in XYZWHDR format to neareset BEV without
rotation.
Args:
boxes3d (torch.Tensor): Rotated boxes in XYZWHDR format.
Returns:
torch.Tensor: Converted BEV boxes in XYWH format.
"""
bev_rotated_boxes = box3d_to_bev(boxes3d)
rotations = bev_rotated_boxes[:, -1]
normed_rotations = torch.abs(limit_period(rotations, 0.5, np.pi))
conditions = (normed_rotations > np.pi / 4)[..., None]
bboxes_xywh = torch.where(conditions, bev_rotated_boxes[:, [0, 1, 3, 2]
], bev_rotated_boxes[:, :4])
centers = bboxes_xywh[:, :2]
dims = bboxes_xywh[:, 2:]
bev_boxes = torch.cat([centers - dims / 2, centers + dims / 2], dim=-1)
return bev_boxes
def xywhr_to_xyxyr(boxes_xywhr):
"""Convert rotated boxes in XYWHR format to XYXYR format.
Args:
boxes_xywhr (torch.Tensor): Rotated boxes in XYWHR format.
Returns:
torch.Tensor: Converted boxes in XYXYR format.
"""
boxes = torch.zeros_like(boxes_xywhr)
half_w = boxes_xywhr[:, 2] / 2
half_h = boxes_xywhr[:, 3] / 2
boxes[:, 0] = boxes_xywhr[:, 0] - half_w
boxes[:, 1] = boxes_xywhr[:, 1] - half_h
boxes[:, 2] = boxes_xywhr[:, 0] + half_w
boxes[:, 3] = boxes_xywhr[:, 1] + half_h
boxes[:, 4] = boxes_xywhr[:, 4]
return boxes
def multiclass_nms(boxes, scores, score_thr):
"""Multi-class nms for 3D boxes.
Args:
boxes (torch.Tensor): Multi-level boxes with shape (N, M).
M is the dimensions of boxes.
scores (torch.Tensor): Multi-level boxes with shape
(N, ). N is the number of boxes.
score_thr (float): Score threshold to filter boxes with low
confidence.
Returns:
list[torch.Tensor]: Return a list of indices after nms,
with an entry for each class.
"""
idxs = []
for i in range(scores.shape[1]):
cls_inds = scores[:, i] > score_thr
if not cls_inds.any():
idxs.append(torch.tensor([], dtype=torch.long, device=cls_inds.
device))
continue
orig_idx = torch.arange(cls_inds.shape[0], device=cls_inds.device,
dtype=torch.long)[cls_inds]
_scores = scores[cls_inds, i]
_boxes = boxes[cls_inds, :]
_bev = xywhr_to_xyxyr(box3d_to_bev(_boxes))
idx = nms(_bev, _scores, 0.01)
idxs.append(orig_idx[idx])
return idxs
class Anchor3DRangeGenerator(object):
"""3D Anchor Generator by range.
This anchor generator generates anchors by the given range in different
feature levels.
Args:
ranges (list[list[float]]): Ranges of different anchors.
The ranges are the same across different feature levels. But may
vary for different anchor sizes if size_per_range is True.
sizes (list[list[float]]): 3D sizes of anchors.
rotations (list[float]): Rotations of anchors in a feature grid.
"""
def __init__(self, ranges, sizes=[[1.6, 3.9, 1.56]], rotations=[0,
1.5707963]):
if len(sizes) != len(ranges):
assert len(ranges) == 1
ranges = ranges * len(sizes)
assert len(ranges) == len(sizes)
self.sizes = sizes
self.ranges = ranges
self.rotations = rotations
@property
def num_base_anchors(self):
"""list[int]: Total number of base anchors in a feature grid."""
num_rot = len(self.rotations)
num_size = torch.tensor(self.sizes).reshape(-1, 3).size(0)
return num_rot * num_size
def grid_anchors(self, featmap_size, device='cuda'):
"""Generate grid anchors of a single level feature map.
This function is usually called by method ``self.grid_anchors``.
Args:
featmap_size (tuple[int]): Size of the feature map.
device (str, optional): Device the tensor will be put on.
Defaults to 'cuda'.
Returns:
torch.Tensor: Anchors in the overall feature map.
"""
mr_anchors = []
for anchor_range, anchor_size in zip(self.ranges, self.sizes):
mr_anchors.append(self.anchors_single_range(featmap_size,
anchor_range, anchor_size, self.rotations, device=device))
mr_anchors = torch.cat(mr_anchors, dim=-3)
return mr_anchors
def anchors_single_range(self, feature_size, anchor_range, sizes=[[1.6,
3.9, 1.56]], rotations=[0, 1.5707963], device='cuda'):
"""Generate anchors in a single range.
Args:
feature_size (list[float] | tuple[float]): Feature map size. It is
either a list of a tuple of [D, H, W](in order of z, y, and x).
anchor_range (torch.Tensor | list[float]): Range of anchors with
shape [6]. The order is consistent with that of anchors, i.e.,
(x_min, y_min, z_min, x_max, y_max, z_max).
sizes (list[list] | np.ndarray | torch.Tensor): Anchor size with
shape [N, 3], in order of x, y, z.
rotations (list[float] | np.ndarray | torch.Tensor): Rotations of
anchors in a single feature grid.
device (str): Devices that the anchors will be put on.
Returns:
torch.Tensor: Anchors with shape [*feature_size, num_sizes, num_rots, 7].
"""
if len(feature_size) == 2:
feature_size = [1, feature_size[0], feature_size[1]]
anchor_range = torch.tensor(anchor_range, device=device)
z_centers = torch.linspace(anchor_range[2], anchor_range[5],
feature_size[0], device=device)
y_centers = torch.linspace(anchor_range[1], anchor_range[4],
feature_size[1], device=device)
x_centers = torch.linspace(anchor_range[0], anchor_range[3],
feature_size[2], device=device)
sizes = torch.tensor(sizes, device=device).reshape(-1, 3)
rotations = torch.tensor(rotations, device=device)
rets = torch.meshgrid(x_centers, y_centers, z_centers, rotations)
rets = list(rets)
for i in range(len(rets)):
rets[i] = rets[i].unsqueeze(-2).unsqueeze(-1)
sizes = sizes.reshape([1, 1, 1, 1, 1, 3])
tile_size_shape = list(rets[0].shape)
tile_size_shape[3] = 1
sizes = sizes.repeat(tile_size_shape)
rets.insert(3, sizes)
ret = torch.cat(rets, dim=-1).permute([2, 1, 0, 3, 4, 5])
return ret
class BBoxCoder(object):
"""Bbox Coder for 3D boxes.
Args:
code_size (int): The dimension of boxes to be encoded.
"""
def __init__(self):
super(BBoxCoder, self).__init__()
@staticmethod
def encode(src_boxes, dst_boxes):
"""Get box regression transformation deltas (dx, dy, dz, dw, dh, dl, dr,
dv*) that can be used to transform the `src_boxes` into the
`target_boxes`.
Args:
src_boxes (torch.Tensor): source boxes, e.g., object proposals.
dst_boxes (torch.Tensor): target of the transformation, e.g.,
ground-truth boxes.
Returns:
torch.Tensor: Box transformation deltas.
"""
xa, ya, za, wa, la, ha, ra = torch.split(src_boxes, 1, dim=-1)
xg, yg, zg, wg, lg, hg, rg = torch.split(dst_boxes, 1, dim=-1)
za = za + ha / 2
zg = zg + hg / 2
diagonal = torch.sqrt(la ** 2 + wa ** 2)
xt = (xg - xa) / diagonal
yt = (yg - ya) / diagonal
zt = (zg - za) / ha
lt = torch.log(lg / la)
wt = torch.log(wg / wa)
ht = torch.log(hg / ha)
rt = rg - ra
return torch.cat([xt, yt, zt, wt, lt, ht, rt], dim=-1)
@staticmethod
def decode(anchors, deltas):
"""Apply transformation `deltas` (dx, dy, dz, dw, dh, dl, dr, dv*) to
`boxes`.
Args:
anchors (torch.Tensor): Parameters of anchors with shape (N, 7).
deltas (torch.Tensor): Encoded boxes with shape
(N, 7+n) [x, y, z, w, l, h, r, velo*].
Returns:
torch.Tensor: Decoded boxes.
"""
xa, ya, za, wa, la, ha, ra = torch.split(anchors, 1, dim=-1)
xt, yt, zt, wt, lt, ht, rt = torch.split(deltas, 1, dim=-1)
za = za + ha / 2
diagonal = torch.sqrt(la ** 2 + wa ** 2)
xg = xt * diagonal + xa
yg = yt * diagonal + ya
zg = zt * ha + za
lg = torch.exp(lt) * la
wg = torch.exp(wt) * wa
hg = torch.exp(ht) * ha
rg = rt + ra
zg = zg - hg / 2
return torch.cat([xg, yg, zg, wg, lg, hg, rg], dim=-1)
class Anchor3DHead(nn.Module):
def __init__(self, num_classes=1, in_channels=384, feat_channels=384,
nms_pre=100, score_thr=0.1, dir_offset=0, ranges=[[0, -40.0, -3,
70.0, 40.0, 1]], sizes=[[0.6, 1.0, 1.5]], rotations=[0, 1.57],
iou_thr=[[0.35, 0.5]]):
super().__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.feat_channels = feat_channels
self.nms_pre = nms_pre
self.score_thr = score_thr
self.dir_offset = dir_offset
self.iou_thr = iou_thr
if len(self.iou_thr) != num_classes:
assert len(self.iou_thr) == 1
self.iou_thr = self.iou_thr * num_classes
assert len(self.iou_thr) == num_classes
self.anchor_generator = Anchor3DRangeGenerator(ranges=ranges, sizes
=sizes, rotations=rotations)
self.num_anchors = self.anchor_generator.num_base_anchors
self.bbox_coder = BBoxCoder()
self.box_code_size = 7
self.fp16_enabled = False
self.cls_out_channels = self.num_anchors * self.num_classes
self.conv_cls = nn.Conv2d(self.feat_channels, self.cls_out_channels, 1)
self.conv_reg = nn.Conv2d(self.feat_channels, self.num_anchors *
self.box_code_size, 1)
self.conv_dir_cls = nn.Conv2d(self.feat_channels, self.num_anchors *
2, 1)
self.init_weights()
@staticmethod
def bias_init_with_prob(prior_prob):
"""Initialize conv/fc bias value according to giving probablity."""
bias_init = float(-np.log((1 - prior_prob) / prior_prob))
return bias_init
@staticmethod
def normal_init(module, mean=0, std=1, bias=0):
nn.init.normal_(module.weight, mean, std)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias)
def init_weights(self):
"""Initialize the weights of head."""
bias_cls = self.bias_init_with_prob(0.01)
self.normal_init(self.conv_cls, std=0.01, bias=bias_cls)
self.normal_init(self.conv_reg, std=0.01)
def forward(self, x):
"""Forward function on a feature map.
Args:
x (torch.Tensor): Input features.
Returns:
tuple[torch.Tensor]: Contain score of each class, bbox regression and direction classification predictions.
"""
cls_score = self.conv_cls(x)
bbox_pred = self.conv_reg(x)
dir_cls_preds = None
dir_cls_preds = self.conv_dir_cls(x)
return cls_score, bbox_pred, dir_cls_preds
def assign_bboxes(self, pred_bboxes, target_bboxes):
"""Assigns target bboxes to given anchors.
Args:
pred_bboxes (torch.Tensor): Bbox predictions (anchors).
target_bboxes (torch.Tensor): Bbox targets.
Returns:
torch.Tensor: Assigned target bboxes for each given anchor.
torch.Tensor: Flat index of matched targets.
torch.Tensor: Index of positive matches.
torch.Tensor: Index of negative matches.
"""
anchors = [self.anchor_generator.grid_anchors(pred_bboxes.shape[-2:
], device=pred_bboxes.device) for _ in range(len(target_bboxes))]
anchors_cnt = torch.tensor(anchors[0].shape[:-1]).prod()
rot_angles = anchors[0].shape[-2]
assigned_bboxes, target_idxs, pos_idxs, neg_idxs = [], [], [], []
def flatten_idx(idx, j):
"""Inject class dimension in the given indices (...
z * rot_angles + x) --> (.. z * num_classes * rot_angles + j * rot_angles + x)
"""
z = idx // rot_angles
x = idx % rot_angles
return z * self.num_classes * rot_angles + j * rot_angles + x
idx_off = 0
for i in range(len(target_bboxes)):
for j, (neg_th, pos_th) in enumerate(self.iou_thr):
anchors_stride = anchors[i][..., j, :, :].reshape(-1, self.
box_code_size)
if target_bboxes[i].shape[0] == 0:
assigned_bboxes.append(torch.zeros((0, 7), device=
pred_bboxes.device))
target_idxs.append(torch.zeros((0,), dtype=torch.long,
device=pred_bboxes.device))
pos_idxs.append(torch.zeros((0,), dtype=torch.long,
device=pred_bboxes.device))
neg_idxs.append(torch.zeros((0,), dtype=torch.long,
device=pred_bboxes.device))
continue
overlaps = bbox_overlaps(box3d_to_bev2d(target_bboxes[i]),
box3d_to_bev2d(anchors_stride))
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
gt_max_overlaps, _ = overlaps.max(dim=1)
pos_idx = max_overlaps >= pos_th
neg_idx = (max_overlaps >= 0) & (max_overlaps < neg_th)
for k in range(len(target_bboxes[i])):
if gt_max_overlaps[k] >= neg_th:
pos_idx[overlaps[k, :] == gt_max_overlaps[k]] = True
assigned_bboxes.append(self.bbox_coder.encode(
anchors_stride[pos_idx], target_bboxes[i][
argmax_overlaps[pos_idx]]))
target_idxs.append(argmax_overlaps[pos_idx] + idx_off)
pos_idx = flatten_idx(pos_idx.nonzero(as_tuple=False).
squeeze(-1), j) + i * anchors_cnt
neg_idx = flatten_idx(neg_idx.nonzero(as_tuple=False).
squeeze(-1), j) + i * anchors_cnt
pos_idxs.append(pos_idx)
neg_idxs.append(neg_idx)
idx_off += len(target_bboxes[i])
return torch.cat(assigned_bboxes, axis=0), torch.cat(target_idxs,
axis=0), torch.cat(pos_idxs, axis=0), torch.cat(neg_idxs, axis=0)
def get_bboxes(self, cls_scores, bbox_preds, dir_preds):
"""Get bboxes of anchor head.
Args:
cls_scores (list[torch.Tensor]): Class scores.
bbox_preds (list[torch.Tensor]): Bbox predictions.
dir_cls_preds (list[torch.Tensor]): Direction
class predictions.
Returns:
tuple[torch.Tensor]: Prediction results of batches
(bboxes, scores, labels).
"""
bboxes, scores, labels = [], [], []
for cls_score, bbox_pred, dir_pred in zip(cls_scores, bbox_preds,
dir_preds):
b, s, l = self.get_bboxes_single(cls_score, bbox_pred, dir_pred)
bboxes.append(b)
scores.append(s)
labels.append(l)
return bboxes, scores, labels
def get_bboxes_single(self, cls_scores, bbox_preds, dir_preds):
"""Get bboxes of anchor head.
Args:
cls_scores (list[torch.Tensor]): Class scores.
bbox_preds (list[torch.Tensor]): Bbox predictions.
dir_cls_preds (list[torch.Tensor]): Direction
class predictions.
Returns:
tuple[torch.Tensor]: Prediction results of batches
(bboxes, scores, labels).
"""
assert cls_scores.size()[-2:] == bbox_preds.size()[-2:]
assert cls_scores.size()[-2:] == dir_preds.size()[-2:]
anchors = self.anchor_generator.grid_anchors(cls_scores.shape[-2:],
device=cls_scores.device)
anchors = anchors.reshape(-1, self.box_code_size)
dir_preds = dir_preds.permute(1, 2, 0).reshape(-1, 2)
dir_scores = torch.max(dir_preds, dim=-1)[1]
cls_scores = cls_scores.permute(1, 2, 0).reshape(-1, self.num_classes)
scores = cls_scores.sigmoid()
bbox_preds = bbox_preds.permute(1, 2, 0).reshape(-1, self.box_code_size
)
if scores.shape[0] > self.nms_pre:
max_scores, _ = scores.max(dim=1)
_, topk_inds = max_scores.topk(self.nms_pre)
anchors = anchors[topk_inds, :]
bbox_preds = bbox_preds[topk_inds, :]
scores = scores[topk_inds, :]
dir_scores = dir_scores[topk_inds]
bboxes = self.bbox_coder.decode(anchors, bbox_preds)
idxs = multiclass_nms(bboxes, scores, self.score_thr)
labels = [torch.full((len(idxs[i]),), i, dtype=torch.long) for i in
range(self.num_classes)]
labels = torch.cat(labels)
scores = [scores[idxs[i], i] for i in range(self.num_classes)]
scores = torch.cat(scores)
idxs = torch.cat(idxs)
bboxes = bboxes[idxs]
dir_scores = dir_scores[idxs]
if bboxes.shape[0] > 0:
dir_rot = limit_period(bboxes[..., 6] - self.dir_offset, 1, np.pi)
bboxes[..., 6] = dir_rot + self.dir_offset + np.pi * dir_scores
return bboxes, scores, labels
def get_inputs():
return [torch.rand([4, 384, 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 numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 1536
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 % 384
y1 = yindex // 384
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 384 * x2 + 1572864 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, in_ptr1, 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')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, ymask)
@triton.jit
def triton_poi_fused_convolution_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 56
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 % 14
y1 = yindex // 14
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 14 * x2 + 57344 * y1), ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, ymask)
@triton.jit
def triton_poi_fused_convolution_3(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 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]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16384 * y1), ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, 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, (2, 384, 1, 1), (384, 1, 1, 1))
assert_size_stride(primals_2, (2,), (1,))
assert_size_stride(primals_3, (4, 384, 64, 64), (1572864, 4096, 64, 1))
assert_size_stride(primals_4, (14, 384, 1, 1), (384, 1, 1, 1))
assert_size_stride(primals_5, (14,), (1,))
assert_size_stride(primals_6, (4, 384, 1, 1), (384, 1, 1, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 384, 64, 64), (1572864, 1, 24576, 384
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(1536, 4096)](primals_3, buf0, 1536, 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, 2, 64, 64), (8192, 1, 128, 2))
buf2 = empty_strided_cuda((4, 2, 64, 64), (8192, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_1[grid(8, 4096)](buf1, primals_2, buf2,
8, 4096, XBLOCK=256, YBLOCK=1, num_warps=4, num_stages=1)
del buf1
del primals_2
buf3 = extern_kernels.convolution(buf0, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 14, 64, 64), (57344, 1, 896, 14))
buf4 = empty_strided_cuda((4, 14, 64, 64), (57344, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_2[grid(56, 4096)](buf3, primals_5,
buf4, 56, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del buf3
del primals_5
buf5 = extern_kernels.convolution(buf0, primals_6, 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, 64, 64), (16384, 1, 256, 4))
buf6 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_3[grid(16, 4096)](buf5, primals_7,
buf6, 16, 4096, XBLOCK=32, YBLOCK=16, num_warps=4, num_stages=1)
del buf5
del primals_7
return buf2, buf4, buf6, primals_1, buf0, primals_4, primals_6
def bbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, eps=1e-06):
"""Calculate overlap between two set of bboxes.
If ``is_aligned `` is ``False``, then calculate the overlaps between each
bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned
pair of bboxes1 and bboxes2.
Args:
bboxes1 (Tensor): shape (B, m, 4) in <x1, y1, x2, y2> format or empty.
bboxes2 (Tensor): shape (B, n, 4) in <x1, y1, x2, y2> format or empty.
B indicates the batch dim, in shape (B1, B2, ..., Bn).
If ``is_aligned `` is ``True``, then m and n must be equal.
mode (str): "iou" (intersection over union) or "iof" (intersection over
foreground).
is_aligned (bool, optional): If True, then m and n must be equal.
Default False.
eps (float, optional): A value added to the denominator for numerical
stability. Default 1e-6.
Returns:
Tensor: shape (m, n) if ``is_aligned `` is False else shape (m,)
Example:
>>> bboxes1 = torch.FloatTensor([
>>> [0, 0, 10, 10],
>>> [10, 10, 20, 20],
>>> [32, 32, 38, 42],
>>> ])
>>> bboxes2 = torch.FloatTensor([
>>> [0, 0, 10, 20],
>>> [0, 10, 10, 19],
>>> [10, 10, 20, 20],
>>> ])
>>> overlaps = bbox_overlaps(bboxes1, bboxes2)
>>> assert overlaps.shape == (3, 3)
>>> overlaps = bbox_overlaps(bboxes1, bboxes2, is_aligned=True)
>>> assert overlaps.shape == (3, )
Example:
>>> empty = torch.empty(0, 4)
>>> nonempty = torch.FloatTensor([[0, 0, 10, 9]])
>>> assert tuple(bbox_overlaps(empty, nonempty).shape) == (0, 1)
>>> assert tuple(bbox_overlaps(nonempty, empty).shape) == (1, 0)
>>> assert tuple(bbox_overlaps(empty, empty).shape) == (0, 0)
"""
assert mode in ['iou', 'iof', 'giou'], f'Unsupported mode {mode}'
assert bboxes1.size(-1) == 4 or bboxes1.size(0) == 0
assert bboxes2.size(-1) == 4 or bboxes2.size(0) == 0
assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
batch_shape = bboxes1.shape[:-2]
rows = bboxes1.size(-2)
cols = bboxes2.size(-2)
if is_aligned:
assert rows == cols
if rows * cols == 0:
if is_aligned:
return bboxes1.new(batch_shape + (rows,))
else:
return bboxes1.new(batch_shape + (rows, cols))
area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] -
bboxes1[..., 1])
area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] -
bboxes2[..., 1])
if is_aligned:
lt = torch.max(bboxes1[..., :2], bboxes2[..., :2])
rb = torch.min(bboxes1[..., 2:], bboxes2[..., 2:])
wh = (rb - lt).clamp(min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1 + area2 - overlap
else:
union = area1
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :2], bboxes2[..., :2])
enclosed_rb = torch.max(bboxes1[..., 2:], bboxes2[..., 2:])
else:
lt = torch.max(bboxes1[..., :, None, :2], bboxes2[..., None, :, :2])
rb = torch.min(bboxes1[..., :, None, 2:], bboxes2[..., None, :, 2:])
wh = (rb - lt).clamp(min=0)
overlap = wh[..., 0] * wh[..., 1]
if mode in ['iou', 'giou']:
union = area1[..., None] + area2[..., None, :] - overlap
else:
union = area1[..., None]
if mode == 'giou':
enclosed_lt = torch.min(bboxes1[..., :, None, :2], bboxes2[...,
None, :, :2])
enclosed_rb = torch.max(bboxes1[..., :, None, 2:], bboxes2[...,
None, :, 2:])
eps = union.new_tensor([eps])
union = torch.max(union, eps)
ious = overlap / union
if mode in ['iou', 'iof']:
return ious
enclose_wh = (enclosed_rb - enclosed_lt).clamp(min=0)
enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
enclose_area = torch.max(enclose_area, eps)
gious = ious - (enclose_area - union) / enclose_area
return gious
def box3d_to_bev(boxes3d):
"""Convert rotated 3d boxes in XYZWHDR format to BEV in XYWHR format.
Args:
boxes3d (torch.Tensor): Rotated boxes in XYZWHDR format.
Returns:
torch.Tensor: Converted BEV boxes in XYWHR format.
"""
return boxes3d[:, [0, 1, 3, 4, 6]]
def limit_period(val, offset=0.5, period=np.pi):
"""Limit the value into a period for periodic function.
Args:
val (torch.Tensor): The value to be converted.
offset (float, optional): Offset to set the value range. Defaults to 0.5.
period ([type], optional): Period of the value. Defaults to np.pi.
Returns:
torch.Tensor: Value in the range of [-offset * period, (1-offset) * period]
"""
return val - torch.floor(val / period + offset) * period
def box3d_to_bev2d(boxes3d):
"""Convert rotated 3d boxes in XYZWHDR format to neareset BEV without
rotation.
Args:
boxes3d (torch.Tensor): Rotated boxes in XYZWHDR format.
Returns:
torch.Tensor: Converted BEV boxes in XYWH format.
"""
bev_rotated_boxes = box3d_to_bev(boxes3d)
rotations = bev_rotated_boxes[:, -1]
normed_rotations = torch.abs(limit_period(rotations, 0.5, np.pi))
conditions = (normed_rotations > np.pi / 4)[..., None]
bboxes_xywh = torch.where(conditions, bev_rotated_boxes[:, [0, 1, 3, 2]
], bev_rotated_boxes[:, :4])
centers = bboxes_xywh[:, :2]
dims = bboxes_xywh[:, 2:]
bev_boxes = torch.cat([centers - dims / 2, centers + dims / 2], dim=-1)
return bev_boxes
def xywhr_to_xyxyr(boxes_xywhr):
"""Convert rotated boxes in XYWHR format to XYXYR format.
Args:
boxes_xywhr (torch.Tensor): Rotated boxes in XYWHR format.
Returns:
torch.Tensor: Converted boxes in XYXYR format.
"""
boxes = torch.zeros_like(boxes_xywhr)
half_w = boxes_xywhr[:, 2] / 2
half_h = boxes_xywhr[:, 3] / 2
boxes[:, 0] = boxes_xywhr[:, 0] - half_w
boxes[:, 1] = boxes_xywhr[:, 1] - half_h
boxes[:, 2] = boxes_xywhr[:, 0] + half_w
boxes[:, 3] = boxes_xywhr[:, 1] + half_h
boxes[:, 4] = boxes_xywhr[:, 4]
return boxes
def multiclass_nms(boxes, scores, score_thr):
"""Multi-class nms for 3D boxes.
Args:
boxes (torch.Tensor): Multi-level boxes with shape (N, M).
M is the dimensions of boxes.
scores (torch.Tensor): Multi-level boxes with shape
(N, ). N is the number of boxes.
score_thr (float): Score threshold to filter boxes with low
confidence.
Returns:
list[torch.Tensor]: Return a list of indices after nms,
with an entry for each class.
"""
idxs = []
for i in range(scores.shape[1]):
cls_inds = scores[:, i] > score_thr
if not cls_inds.any():
idxs.append(torch.tensor([], dtype=torch.long, device=cls_inds.
device))
continue
orig_idx = torch.arange(cls_inds.shape[0], device=cls_inds.device,
dtype=torch.long)[cls_inds]
_scores = scores[cls_inds, i]
_boxes = boxes[cls_inds, :]
_bev = xywhr_to_xyxyr(box3d_to_bev(_boxes))
idx = nms(_bev, _scores, 0.01)
idxs.append(orig_idx[idx])
return idxs
class Anchor3DRangeGenerator(object):
"""3D Anchor Generator by range.
This anchor generator generates anchors by the given range in different
feature levels.
Args:
ranges (list[list[float]]): Ranges of different anchors.
The ranges are the same across different feature levels. But may
vary for different anchor sizes if size_per_range is True.
sizes (list[list[float]]): 3D sizes of anchors.
rotations (list[float]): Rotations of anchors in a feature grid.
"""
def __init__(self, ranges, sizes=[[1.6, 3.9, 1.56]], rotations=[0,
1.5707963]):
if len(sizes) != len(ranges):
assert len(ranges) == 1
ranges = ranges * len(sizes)
assert len(ranges) == len(sizes)
self.sizes = sizes
self.ranges = ranges
self.rotations = rotations
@property
def num_base_anchors(self):
"""list[int]: Total number of base anchors in a feature grid."""
num_rot = len(self.rotations)
num_size = torch.tensor(self.sizes).reshape(-1, 3).size(0)
return num_rot * num_size
def grid_anchors(self, featmap_size, device='cuda'):
"""Generate grid anchors of a single level feature map.
This function is usually called by method ``self.grid_anchors``.
Args:
featmap_size (tuple[int]): Size of the feature map.
device (str, optional): Device the tensor will be put on.
Defaults to 'cuda'.
Returns:
torch.Tensor: Anchors in the overall feature map.
"""
mr_anchors = []
for anchor_range, anchor_size in zip(self.ranges, self.sizes):
mr_anchors.append(self.anchors_single_range(featmap_size,
anchor_range, anchor_size, self.rotations, device=device))
mr_anchors = torch.cat(mr_anchors, dim=-3)
return mr_anchors
def anchors_single_range(self, feature_size, anchor_range, sizes=[[1.6,
3.9, 1.56]], rotations=[0, 1.5707963], device='cuda'):
"""Generate anchors in a single range.
Args:
feature_size (list[float] | tuple[float]): Feature map size. It is
either a list of a tuple of [D, H, W](in order of z, y, and x).
anchor_range (torch.Tensor | list[float]): Range of anchors with
shape [6]. The order is consistent with that of anchors, i.e.,
(x_min, y_min, z_min, x_max, y_max, z_max).
sizes (list[list] | np.ndarray | torch.Tensor): Anchor size with
shape [N, 3], in order of x, y, z.
rotations (list[float] | np.ndarray | torch.Tensor): Rotations of
anchors in a single feature grid.
device (str): Devices that the anchors will be put on.
Returns:
torch.Tensor: Anchors with shape [*feature_size, num_sizes, num_rots, 7].
"""
if len(feature_size) == 2:
feature_size = [1, feature_size[0], feature_size[1]]
anchor_range = torch.tensor(anchor_range, device=device)
z_centers = torch.linspace(anchor_range[2], anchor_range[5],
feature_size[0], device=device)
y_centers = torch.linspace(anchor_range[1], anchor_range[4],
feature_size[1], device=device)
x_centers = torch.linspace(anchor_range[0], anchor_range[3],
feature_size[2], device=device)
sizes = torch.tensor(sizes, device=device).reshape(-1, 3)
rotations = torch.tensor(rotations, device=device)
rets = torch.meshgrid(x_centers, y_centers, z_centers, rotations)
rets = list(rets)
for i in range(len(rets)):
rets[i] = rets[i].unsqueeze(-2).unsqueeze(-1)
sizes = sizes.reshape([1, 1, 1, 1, 1, 3])
tile_size_shape = list(rets[0].shape)
tile_size_shape[3] = 1
sizes = sizes.repeat(tile_size_shape)
rets.insert(3, sizes)
ret = torch.cat(rets, dim=-1).permute([2, 1, 0, 3, 4, 5])
return ret
class BBoxCoder(object):
"""Bbox Coder for 3D boxes.
Args:
code_size (int): The dimension of boxes to be encoded.
"""
def __init__(self):
super(BBoxCoder, self).__init__()
@staticmethod
def encode(src_boxes, dst_boxes):
"""Get box regression transformation deltas (dx, dy, dz, dw, dh, dl, dr,
dv*) that can be used to transform the `src_boxes` into the
`target_boxes`.
Args:
src_boxes (torch.Tensor): source boxes, e.g., object proposals.
dst_boxes (torch.Tensor): target of the transformation, e.g.,
ground-truth boxes.
Returns:
torch.Tensor: Box transformation deltas.
"""
xa, ya, za, wa, la, ha, ra = torch.split(src_boxes, 1, dim=-1)
xg, yg, zg, wg, lg, hg, rg = torch.split(dst_boxes, 1, dim=-1)
za = za + ha / 2
zg = zg + hg / 2
diagonal = torch.sqrt(la ** 2 + wa ** 2)
xt = (xg - xa) / diagonal
yt = (yg - ya) / diagonal
zt = (zg - za) / ha
lt = torch.log(lg / la)
wt = torch.log(wg / wa)
ht = torch.log(hg / ha)
rt = rg - ra
return torch.cat([xt, yt, zt, wt, lt, ht, rt], dim=-1)
@staticmethod
def decode(anchors, deltas):
"""Apply transformation `deltas` (dx, dy, dz, dw, dh, dl, dr, dv*) to
`boxes`.
Args:
anchors (torch.Tensor): Parameters of anchors with shape (N, 7).
deltas (torch.Tensor): Encoded boxes with shape
(N, 7+n) [x, y, z, w, l, h, r, velo*].
Returns:
torch.Tensor: Decoded boxes.
"""
xa, ya, za, wa, la, ha, ra = torch.split(anchors, 1, dim=-1)
xt, yt, zt, wt, lt, ht, rt = torch.split(deltas, 1, dim=-1)
za = za + ha / 2
diagonal = torch.sqrt(la ** 2 + wa ** 2)
xg = xt * diagonal + xa
yg = yt * diagonal + ya
zg = zt * ha + za
lg = torch.exp(lt) * la
wg = torch.exp(wt) * wa
hg = torch.exp(ht) * ha
rg = rt + ra
zg = zg - hg / 2
return torch.cat([xg, yg, zg, wg, lg, hg, rg], dim=-1)
class Anchor3DHeadNew(nn.Module):
def __init__(self, num_classes=1, in_channels=384, feat_channels=384,
nms_pre=100, score_thr=0.1, dir_offset=0, ranges=[[0, -40.0, -3,
70.0, 40.0, 1]], sizes=[[0.6, 1.0, 1.5]], rotations=[0, 1.57],
iou_thr=[[0.35, 0.5]]):
super().__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.feat_channels = feat_channels
self.nms_pre = nms_pre
self.score_thr = score_thr
self.dir_offset = dir_offset
self.iou_thr = iou_thr
if len(self.iou_thr) != num_classes:
assert len(self.iou_thr) == 1
self.iou_thr = self.iou_thr * num_classes
assert len(self.iou_thr) == num_classes
self.anchor_generator = Anchor3DRangeGenerator(ranges=ranges, sizes
=sizes, rotations=rotations)
self.num_anchors = self.anchor_generator.num_base_anchors
self.bbox_coder = BBoxCoder()
self.box_code_size = 7
self.fp16_enabled = False
self.cls_out_channels = self.num_anchors * self.num_classes
self.conv_cls = nn.Conv2d(self.feat_channels, self.cls_out_channels, 1)
self.conv_reg = nn.Conv2d(self.feat_channels, self.num_anchors *
self.box_code_size, 1)
self.conv_dir_cls = nn.Conv2d(self.feat_channels, self.num_anchors *
2, 1)
self.init_weights()
@staticmethod
def bias_init_with_prob(prior_prob):
"""Initialize conv/fc bias value according to giving probablity."""
bias_init = float(-np.log((1 - prior_prob) / prior_prob))
return bias_init
@staticmethod
def normal_init(module, mean=0, std=1, bias=0):
nn.init.normal_(module.weight, mean, std)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias)
def init_weights(self):
"""Initialize the weights of head."""
bias_cls = self.bias_init_with_prob(0.01)
self.normal_init(self.conv_cls, std=0.01, bias=bias_cls)
self.normal_init(self.conv_reg, std=0.01)
def assign_bboxes(self, pred_bboxes, target_bboxes):
"""Assigns target bboxes to given anchors.
Args:
pred_bboxes (torch.Tensor): Bbox predictions (anchors).
target_bboxes (torch.Tensor): Bbox targets.
Returns:
torch.Tensor: Assigned target bboxes for each given anchor.
torch.Tensor: Flat index of matched targets.
torch.Tensor: Index of positive matches.
torch.Tensor: Index of negative matches.
"""
anchors = [self.anchor_generator.grid_anchors(pred_bboxes.shape[-2:
], device=pred_bboxes.device) for _ in range(len(target_bboxes))]
anchors_cnt = torch.tensor(anchors[0].shape[:-1]).prod()
rot_angles = anchors[0].shape[-2]
assigned_bboxes, target_idxs, pos_idxs, neg_idxs = [], [], [], []
def flatten_idx(idx, j):
"""Inject class dimension in the given indices (...
z * rot_angles + x) --> (.. z * num_classes * rot_angles + j * rot_angles + x)
"""
z = idx // rot_angles
x = idx % rot_angles
return z * self.num_classes * rot_angles + j * rot_angles + x
idx_off = 0
for i in range(len(target_bboxes)):
for j, (neg_th, pos_th) in enumerate(self.iou_thr):
anchors_stride = anchors[i][..., j, :, :].reshape(-1, self.
box_code_size)
if target_bboxes[i].shape[0] == 0:
assigned_bboxes.append(torch.zeros((0, 7), device=
pred_bboxes.device))
target_idxs.append(torch.zeros((0,), dtype=torch.long,
device=pred_bboxes.device))
pos_idxs.append(torch.zeros((0,), dtype=torch.long,
device=pred_bboxes.device))
neg_idxs.append(torch.zeros((0,), dtype=torch.long,
device=pred_bboxes.device))
continue
overlaps = bbox_overlaps(box3d_to_bev2d(target_bboxes[i]),
box3d_to_bev2d(anchors_stride))
max_overlaps, argmax_overlaps = overlaps.max(dim=0)
gt_max_overlaps, _ = overlaps.max(dim=1)
pos_idx = max_overlaps >= pos_th
neg_idx = (max_overlaps >= 0) & (max_overlaps < neg_th)
for k in range(len(target_bboxes[i])):
if gt_max_overlaps[k] >= neg_th:
pos_idx[overlaps[k, :] == gt_max_overlaps[k]] = True
assigned_bboxes.append(self.bbox_coder.encode(
anchors_stride[pos_idx], target_bboxes[i][
argmax_overlaps[pos_idx]]))
target_idxs.append(argmax_overlaps[pos_idx] + idx_off)
pos_idx = flatten_idx(pos_idx.nonzero(as_tuple=False).
squeeze(-1), j) + i * anchors_cnt
neg_idx = flatten_idx(neg_idx.nonzero(as_tuple=False).
squeeze(-1), j) + i * anchors_cnt
pos_idxs.append(pos_idx)
neg_idxs.append(neg_idx)
idx_off += len(target_bboxes[i])
return torch.cat(assigned_bboxes, axis=0), torch.cat(target_idxs,
axis=0), torch.cat(pos_idxs, axis=0), torch.cat(neg_idxs, axis=0)
def get_bboxes(self, cls_scores, bbox_preds, dir_preds):
"""Get bboxes of anchor head.
Args:
cls_scores (list[torch.Tensor]): Class scores.
bbox_preds (list[torch.Tensor]): Bbox predictions.
dir_cls_preds (list[torch.Tensor]): Direction
class predictions.
Returns:
tuple[torch.Tensor]: Prediction results of batches
(bboxes, scores, labels).
"""
bboxes, scores, labels = [], [], []
for cls_score, bbox_pred, dir_pred in zip(cls_scores, bbox_preds,
dir_preds):
b, s, l = self.get_bboxes_single(cls_score, bbox_pred, dir_pred)
bboxes.append(b)
scores.append(s)
labels.append(l)
return bboxes, scores, labels
def get_bboxes_single(self, cls_scores, bbox_preds, dir_preds):
"""Get bboxes of anchor head.
Args:
cls_scores (list[torch.Tensor]): Class scores.
bbox_preds (list[torch.Tensor]): Bbox predictions.
dir_cls_preds (list[torch.Tensor]): Direction
class predictions.
Returns:
tuple[torch.Tensor]: Prediction results of batches
(bboxes, scores, labels).
"""
assert cls_scores.size()[-2:] == bbox_preds.size()[-2:]
assert cls_scores.size()[-2:] == dir_preds.size()[-2:]
anchors = self.anchor_generator.grid_anchors(cls_scores.shape[-2:],
device=cls_scores.device)
anchors = anchors.reshape(-1, self.box_code_size)
dir_preds = dir_preds.permute(1, 2, 0).reshape(-1, 2)
dir_scores = torch.max(dir_preds, dim=-1)[1]
cls_scores = cls_scores.permute(1, 2, 0).reshape(-1, self.num_classes)
scores = cls_scores.sigmoid()
bbox_preds = bbox_preds.permute(1, 2, 0).reshape(-1, self.box_code_size
)
if scores.shape[0] > self.nms_pre:
max_scores, _ = scores.max(dim=1)
_, topk_inds = max_scores.topk(self.nms_pre)
anchors = anchors[topk_inds, :]
bbox_preds = bbox_preds[topk_inds, :]
scores = scores[topk_inds, :]
dir_scores = dir_scores[topk_inds]
bboxes = self.bbox_coder.decode(anchors, bbox_preds)
idxs = multiclass_nms(bboxes, scores, self.score_thr)
labels = [torch.full((len(idxs[i]),), i, dtype=torch.long) for i in
range(self.num_classes)]
labels = torch.cat(labels)
scores = [scores[idxs[i], i] for i in range(self.num_classes)]
scores = torch.cat(scores)
idxs = torch.cat(idxs)
bboxes = bboxes[idxs]
dir_scores = dir_scores[idxs]
if bboxes.shape[0] > 0:
dir_rot = limit_period(bboxes[..., 6] - self.dir_offset, 1, np.pi)
bboxes[..., 6] = dir_rot + self.dir_offset + np.pi * dir_scores
return bboxes, scores, labels
def forward(self, input_0):
primals_1 = self.conv_cls.weight
primals_2 = self.conv_cls.bias
primals_4 = self.conv_reg.weight
primals_5 = self.conv_reg.bias
primals_6 = self.conv_dir_cls.weight
primals_7 = self.conv_dir_cls.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1], output[2]
|
mi-exwzd/Open3D-ML
|
Anchor3DHead
| false
| 16,104
|
[
"MIT"
] | 447
|
d58b24edd37de7889446360164cd5500e0bde060
|
https://github.com/mi-exwzd/Open3D-ML/tree/d58b24edd37de7889446360164cd5500e0bde060
|
CRF
|
import torch
from torch import nn
class CRF(nn.Module):
def __init__(self, num_nodes, iteration=10):
"""Initialize the CRF module
Args:
num_nodes: int, number of nodes/patches within the fully CRF
iteration: int, number of mean field iterations, e.g. 10
"""
super(CRF, self).__init__()
self.num_nodes = num_nodes
self.iteration = iteration
self.W = nn.Parameter(torch.zeros(1, num_nodes, num_nodes))
def forward(self, feats, logits):
"""Performing the CRF. Algorithm details is explained below:
Within the paper, I formulate the CRF distribution using negative
energy and cost, e.g. cosine distance, to derive pairwise potentials
following the convention in energy based models. But for implementation
simplicity, I use reward, e.g. cosine similarity to derive pairwise
potentials. So now, pairwise potentials would encourage high reward for
assigning (y_i, y_j) with the same label if (x_i, x_j) are similar, as
measured by cosine similarity, pairwise_sim. For
pairwise_potential_E = torch.sum(
probs * pairwise_potential - (1 - probs) * pairwise_potential,
dim=2, keepdim=True
)
This is taking the expectation of pairwise potentials using the current
marginal distribution of each patch being tumor, i.e. probs. There are
four cases to consider when taking the expectation between (i, j):
1. i=T,j=T; 2. i=N,j=T; 3. i=T,j=N; 4. i=N,j=N
probs is the marginal distribution of each i being tumor, therefore
logits > 0 means tumor and logits < 0 means normal. Given this, the
full expectation equation should be:
[probs * +pairwise_potential] + [(1 - probs) * +pairwise_potential] +
case 1 case 2
[probs * -pairwise_potential] + [(1 - probs) * -pairwise_potential]
case 3 case 4
positive sign rewards logits to be more tumor and negative sign rewards
logits to be more normal. But because of label compatibility, i.e. the
indicator function within equation 3 in the paper, case 2 and case 3
are dropped, which ends up being:
probs * pairwise_potential - (1 - probs) * pairwise_potential
In high level speaking, if (i, j) embedding are different, then
pairwise_potential, as computed as cosine similarity, would approach 0,
which then as no affect anyway. if (i, j) embedding are similar, then
pairwise_potential would be a positive reward. In this case,
if probs -> 1, then pairwise_potential promotes tumor probability;
if probs -> 0, then -pairwise_potential promotes normal probability.
Args:
feats: 3D tensor with the shape of
[batch_size, num_nodes, embedding_size], where num_nodes is the
number of patches within a grid, e.g. 9 for a 3x3 grid;
embedding_size is the size of extracted feature representation for
each patch from ResNet, e.g. 512
logits: 3D tensor with shape of [batch_size, num_nodes, 1], the
logit of each patch within the grid being tumor before CRF
Returns:
logits: 3D tensor with shape of [batch_size, num_nodes, 1], the
logit of each patch within the grid being tumor after CRF
"""
feats_norm = torch.norm(feats, p=2, dim=2, keepdim=True)
pairwise_norm = torch.bmm(feats_norm, torch.transpose(feats_norm, 1, 2)
)
pairwise_dot = torch.bmm(feats, torch.transpose(feats, 1, 2))
pairwise_sim = pairwise_dot / pairwise_norm
W_sym = (self.W + torch.transpose(self.W, 1, 2)) / 2
pairwise_potential = pairwise_sim * W_sym
unary_potential = logits.clone()
for i in range(self.iteration):
probs = torch.transpose(logits.sigmoid(), 1, 2)
pairwise_potential_E = torch.sum(probs * pairwise_potential - (
1 - probs) * pairwise_potential, dim=2, keepdim=True)
logits = unary_potential + pairwise_potential_E
return logits
def __repr__(self):
return 'CRF(num_nodes={}, iteration={})'.format(self.num_nodes,
self.iteration)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'num_nodes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_linalg_vector_norm_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = libdevice.sqrt(tmp10)
tl.store(out_ptr0 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused_div_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_out_ptr0 + x0, xmask)
tmp2 = tmp0 / tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_rsub_sub_sum_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp2 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp16 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp30 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp42 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp43 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp44 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp5 = tmp3 + tmp4
tmp6 = 0.5
tmp7 = tmp5 * tmp6
tmp8 = tmp2 * tmp7
tmp9 = tmp1 * tmp8
tmp10 = 1.0
tmp11 = tmp10 - tmp1
tmp12 = tmp11 * tmp8
tmp13 = tmp9 - tmp12
tmp15 = tl.sigmoid(tmp14)
tmp19 = tmp17 + tmp18
tmp20 = tmp19 * tmp6
tmp21 = tmp16 * tmp20
tmp22 = tmp15 * tmp21
tmp23 = tmp10 - tmp15
tmp24 = tmp23 * tmp21
tmp25 = tmp22 - tmp24
tmp26 = tmp13 + tmp25
tmp28 = tl.sigmoid(tmp27)
tmp32 = tmp30 + tmp31
tmp33 = tmp32 * tmp6
tmp34 = tmp29 * tmp33
tmp35 = tmp28 * tmp34
tmp36 = tmp10 - tmp28
tmp37 = tmp36 * tmp34
tmp38 = tmp35 - tmp37
tmp39 = tmp26 + tmp38
tmp41 = tl.sigmoid(tmp40)
tmp45 = tmp43 + tmp44
tmp46 = tmp45 * tmp6
tmp47 = tmp42 * tmp46
tmp48 = tmp41 * tmp47
tmp49 = tmp10 - tmp41
tmp50 = tmp49 * tmp47
tmp51 = tmp48 - tmp50
tmp52 = tmp39 + tmp51
tl.store(out_ptr0 + x2, tmp52, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_rsub_sub_sum_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + 4 * x2, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr3 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp32 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp35 = tl.load(in_ptr2 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_ptr3 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp37 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last')
tmp46 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp47 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp50 = tl.load(in_ptr2 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp51 = tl.load(in_ptr3 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp52 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp7 = tmp5 + tmp6
tmp8 = 0.5
tmp9 = tmp7 * tmp8
tmp10 = tmp4 * tmp9
tmp11 = tmp3 * tmp10
tmp12 = 1.0
tmp13 = tmp12 - tmp3
tmp14 = tmp13 * tmp10
tmp15 = tmp11 - tmp14
tmp18 = tmp16 + tmp17
tmp19 = tl.sigmoid(tmp18)
tmp23 = tmp21 + tmp22
tmp24 = tmp23 * tmp8
tmp25 = tmp20 * tmp24
tmp26 = tmp19 * tmp25
tmp27 = tmp12 - tmp19
tmp28 = tmp27 * tmp25
tmp29 = tmp26 - tmp28
tmp30 = tmp15 + tmp29
tmp33 = tmp31 + tmp32
tmp34 = tl.sigmoid(tmp33)
tmp38 = tmp36 + tmp37
tmp39 = tmp38 * tmp8
tmp40 = tmp35 * tmp39
tmp41 = tmp34 * tmp40
tmp42 = tmp12 - tmp34
tmp43 = tmp42 * tmp40
tmp44 = tmp41 - tmp43
tmp45 = tmp30 + tmp44
tmp48 = tmp46 + tmp47
tmp49 = tl.sigmoid(tmp48)
tmp53 = tmp51 + tmp52
tmp54 = tmp53 * tmp8
tmp55 = tmp50 * tmp54
tmp56 = tmp49 * tmp55
tmp57 = tmp12 - tmp49
tmp58 = tmp57 * tmp55
tmp59 = tmp56 - tmp58
tmp60 = tmp45 + tmp59
tl.store(out_ptr0 + x2, tmp60, xmask)
@triton.jit
def triton_poi_fused_add_4(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_linalg_vector_norm_0[grid(16)](primals_1, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf0, reinterpret_tensor(buf0, (4, 1, 4), (4, 16,
1), 0), out=buf1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(primals_1, reinterpret_tensor(primals_1, (4, 4,
4), (16, 1, 4), 0), out=buf2)
del primals_1
buf3 = buf1
del buf1
triton_poi_fused_div_1[grid(64)](buf3, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = buf0
del buf0
triton_poi_fused_add_div_mul_rsub_sub_sum_2[grid(16)](primals_3,
buf3, primals_2, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf4, buf3, primals_2, buf5, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf5, buf3, primals_2, buf6, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf6, buf3, primals_2, buf7, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf8 = buf6
del buf6
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf7, buf3, primals_2, buf8, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf8, buf3, primals_2, buf9, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf10 = buf8
del buf8
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf9, buf3, primals_2, buf10, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf11 = buf9
del buf9
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf10, buf3, primals_2, buf11, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf12 = buf10
del buf10
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf11, buf3, primals_2, buf12, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf13 = buf11
del buf11
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf12, buf3, primals_2, buf13, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf12
buf14 = buf2
del buf2
triton_poi_fused_add_4[grid(64)](primals_3, buf13, buf14, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf13
return buf14, primals_2, primals_3, buf3
class CRFNew(nn.Module):
def __init__(self, num_nodes, iteration=10):
"""Initialize the CRF module
Args:
num_nodes: int, number of nodes/patches within the fully CRF
iteration: int, number of mean field iterations, e.g. 10
"""
super(CRFNew, self).__init__()
self.num_nodes = num_nodes
self.iteration = iteration
self.W = nn.Parameter(torch.zeros(1, num_nodes, num_nodes))
def __repr__(self):
return 'CRF(num_nodes={}, iteration={})'.format(self.num_nodes,
self.iteration)
def forward(self, input_0, input_1):
primals_2 = self.W
primals_1 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
mingrui/NCRF
|
CRF
| false
| 16,105
|
[
"Apache-2.0"
] | 734
|
d3dcb50739a9eb8621d42ea98b7d0496afe430ca
|
https://github.com/mingrui/NCRF/tree/d3dcb50739a9eb8621d42ea98b7d0496afe430ca
|
AODnet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class AODnet(nn.Module):
def __init__(self):
super(AODnet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=1)
self.conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3,
padding=1)
self.conv3 = nn.Conv2d(in_channels=6, out_channels=3, kernel_size=5,
padding=2)
self.conv4 = nn.Conv2d(in_channels=6, out_channels=3, kernel_size=7,
padding=3)
self.conv5 = nn.Conv2d(in_channels=12, out_channels=3, kernel_size=
3, padding=1)
self.b = 1
def forward(self, x):
x1 = F.relu(self.conv1(x))
x2 = F.relu(self.conv2(x1))
cat1 = torch.cat((x1, x2), 1)
x3 = F.relu(self.conv3(cat1))
cat2 = torch.cat((x2, x3), 1)
x4 = F.relu(self.conv4(cat2))
cat3 = torch.cat((x1, x2, x3, x4), 1)
k = F.relu(self.conv5(cat3))
if k.size() != x.size():
raise Exception('k, haze image are different size!')
output = k * x - k + self.b
return F.relu(output)
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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 6
x0 = xindex % 4096
x2 = xindex // 24576
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 3, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 12288 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 6, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 4096 * (-3 + x1) + 12288 * x2), tmp6,
other=0.0)
tmp10 = tl.load(in_ptr2 + (-3 + x1), tmp6, eviction_policy='evict_last',
other=0.0)
tmp11 = tmp9 + tmp10
tmp12 = tl.full([1], 0, tl.int32)
tmp13 = triton_helpers.maximum(tmp12, tmp11)
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp6, tmp13, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_cat_2(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 % 6
x0 = xindex % 4096
x2 = xindex // 24576
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 3, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 12288 * x2), tmp4, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tl.full([1], 6, tl.int64)
tmp15 = tl.load(in_ptr2 + (x0 + 4096 * (-3 + x1) + 12288 * x2), tmp12,
other=0.0)
tmp16 = tl.load(in_ptr3 + (-3 + x1), tmp12, eviction_policy=
'evict_last', other=0.0)
tmp17 = tmp15 + tmp16
tmp18 = triton_helpers.maximum(tmp8, tmp17)
tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype)
tmp20 = tl.where(tmp12, tmp18, tmp19)
tmp21 = tl.where(tmp4, tmp11, tmp20)
tl.store(out_ptr0 + x3, tmp21, None)
@triton.jit
def triton_poi_fused_cat_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, in_ptr6, 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 % 12
x0 = xindex % 4096
x2 = xindex // 49152
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 3, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 12288 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 6, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (x0 + 4096 * (-3 + x1) + 12288 * x2), tmp9,
other=0.0)
tmp11 = tl.load(in_ptr2 + (-3 + x1), tmp9, eviction_policy='evict_last',
other=0.0)
tmp12 = tmp10 + tmp11
tmp13 = tl.full([1], 0, tl.int32)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp9, tmp14, tmp15)
tmp17 = tmp0 >= tmp7
tmp18 = tl.full([1], 9, tl.int64)
tmp19 = tmp0 < tmp18
tmp20 = tmp17 & tmp19
tmp21 = tl.load(in_ptr3 + (x0 + 4096 * (-6 + x1) + 12288 * x2), tmp20,
other=0.0)
tmp22 = tl.load(in_ptr4 + (-6 + x1), tmp20, eviction_policy=
'evict_last', other=0.0)
tmp23 = tmp21 + tmp22
tmp24 = triton_helpers.maximum(tmp13, tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp20, tmp24, tmp25)
tmp27 = tmp0 >= tmp18
tl.full([1], 12, tl.int64)
tmp30 = tl.load(in_ptr5 + (x0 + 4096 * (-9 + x1) + 12288 * x2), tmp27,
other=0.0)
tmp31 = tl.load(in_ptr6 + (-9 + x1), tmp27, eviction_policy=
'evict_last', other=0.0)
tmp32 = tmp30 + tmp31
tmp33 = triton_helpers.maximum(tmp13, tmp32)
tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype)
tmp35 = tl.where(tmp27, tmp33, tmp34)
tmp36 = tl.where(tmp20, tmp26, tmp35)
tmp37 = tl.where(tmp9, tmp16, tmp36)
tmp38 = tl.where(tmp4, tmp5, tmp37)
tl.store(out_ptr0 + x3, tmp38, None)
@triton.jit
def triton_poi_fused_add_convolution_mul_relu_sub_threshold_backward_4(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + x3, None)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = tmp4 * tmp5
tmp7 = tmp6 - tmp4
tmp8 = 1.0
tmp9 = tmp7 + tmp8
tmp10 = triton_helpers.maximum(tmp3, tmp9)
tmp11 = 0.0
tmp12 = tmp4 <= tmp11
tmp13 = tmp10 <= tmp11
tl.store(out_ptr0 + x3, tmp10, None)
tl.store(out_ptr1 + x3, tmp12, None)
tl.store(out_ptr2 + x3, tmp13, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_5(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, 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(out_ptr0 + x3, tmp6, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (3, 3, 1, 1), (3, 1, 1, 1))
assert_size_stride(primals_2, (3,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (3, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_5, (3,), (1,))
assert_size_stride(primals_6, (3, 6, 5, 5), (150, 25, 5, 1))
assert_size_stride(primals_7, (3,), (1,))
assert_size_stride(primals_8, (3, 6, 7, 7), (294, 49, 7, 1))
assert_size_stride(primals_9, (3,), (1,))
assert_size_stride(primals_10, (3, 12, 3, 3), (108, 9, 3, 1))
assert_size_stride(primals_11, (3,), (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, 3, 64, 64), (12288, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(49152)](buf1, primals_2,
49152, XBLOCK=512, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf3 = empty_strided_cuda((4, 6, 64, 64), (24576, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_1[grid(98304)](buf1, buf2, primals_5, buf3,
98304, XBLOCK=512, num_warps=8, num_stages=1)
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf5 = empty_strided_cuda((4, 6, 64, 64), (24576, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_2[grid(98304)](buf2, primals_5, buf4,
primals_7, buf5, 98304, XBLOCK=512, num_warps=8, num_stages=1)
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1),
padding=(3, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf7 = empty_strided_cuda((4, 12, 64, 64), (49152, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_3[grid(196608)](buf1, buf2, primals_5, buf4,
primals_7, buf6, primals_9, buf7, 196608, XBLOCK=512, num_warps
=8, num_stages=1)
buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf9 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.float32)
buf11 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
buf10 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_add_convolution_mul_relu_sub_threshold_backward_4[grid
(49152)](buf8, primals_11, primals_3, buf9, buf11, buf10, 49152,
XBLOCK=512, num_warps=4, num_stages=1)
del buf8
del primals_11
buf12 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_5[grid(49152)](
buf6, primals_9, buf12, 49152, XBLOCK=512, num_warps=4,
num_stages=1)
del buf6
del primals_9
buf13 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_5[grid(49152)](
buf4, primals_7, buf13, 49152, XBLOCK=512, num_warps=4,
num_stages=1)
del buf4
del primals_7
buf14 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_5[grid(49152)](
buf2, primals_5, buf14, 49152, XBLOCK=512, num_warps=4,
num_stages=1)
del buf2
del primals_5
return (buf9, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, buf1, buf3, buf5, buf7, buf10, buf11, buf12, buf13, buf14)
class AODnetNew(nn.Module):
def __init__(self):
super(AODnetNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=1)
self.conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3,
padding=1)
self.conv3 = nn.Conv2d(in_channels=6, out_channels=3, kernel_size=5,
padding=2)
self.conv4 = nn.Conv2d(in_channels=6, out_channels=3, kernel_size=7,
padding=3)
self.conv5 = nn.Conv2d(in_channels=12, out_channels=3, kernel_size=
3, padding=1)
self.b = 1
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.conv5.weight
primals_11 = self.conv5.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
misads/cv_template
|
AODnet
| false
| 16,106
|
[
"MIT"
] | 69
|
9976ee0ada449a494d26f896c598610f233edc10
|
https://github.com/misads/cv_template/tree/9976ee0ada449a494d26f896c598610f233edc10
|
ClassicalConv5
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.utils.prune
import torch.backends.cudnn
import torch.cuda
import torch.nn
import torch.utils.data
class ClassicalConv5(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, 1, padding=1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(64, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = F.avg_pool2d(x, 4)
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = x.view(x.shape[0], x.shape[1], -1)
x = x.mean(-1).squeeze()
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
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
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.utils.prune
import torch.backends.cudnn
import torch.cuda
import torch.nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_avg_pool2d_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
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 * x0 + 256 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (64 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (65 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (66 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp13 = tl.load(in_ptr0 + (67 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (128 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp17 = tl.load(in_ptr0 + (129 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp19 = tl.load(in_ptr0 + (130 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp21 = tl.load(in_ptr0 + (131 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp23 = tl.load(in_ptr0 + (192 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp25 = tl.load(in_ptr0 + (193 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp27 = tl.load(in_ptr0 + (194 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp29 = tl.load(in_ptr0 + (195 + 4 * x0 + 256 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp8 = tmp7 + tmp6
tmp10 = tmp9 + tmp8
tmp12 = tmp11 + tmp10
tmp14 = tmp13 + tmp12
tmp16 = tmp15 + tmp14
tmp18 = tmp17 + tmp16
tmp20 = tmp19 + tmp18
tmp22 = tmp21 + tmp20
tmp24 = tmp23 + tmp22
tmp26 = tmp25 + tmp24
tmp28 = tmp27 + tmp26
tmp30 = tmp29 + tmp28
tmp31 = 0.0625
tmp32 = tmp30 * tmp31
tl.store(out_ptr0 + x2, tmp32, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_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 % 8
x1 = xindex // 8
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 32 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 32 * x1), None, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (16 + 2 * x0 + 32 * x1), None, eviction_policy
='evict_last')
tmp12 = tl.load(in_ptr0 + (17 + 2 * x0 + 32 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, None)
@triton.jit
def triton_per_fused_mean_squeeze_4(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 256
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 + (2 * (r1 % 8) + 32 * (r1 // 8) + 256 * x0),
xmask, eviction_policy='evict_last', other=0.0)
tmp1 = tl.load(in_ptr0 + (1 + 2 * (r1 % 8) + 32 * (r1 // 8) + 256 * x0),
xmask, eviction_policy='evict_last', other=0.0)
tmp3 = tl.load(in_ptr0 + (16 + 2 * (r1 % 8) + 32 * (r1 // 8) + 256 * x0
), xmask, eviction_policy='evict_last', other=0.0)
tmp5 = tl.load(in_ptr0 + (17 + 2 * (r1 % 8) + 32 * (r1 // 8) + 256 * x0
), xmask, eviction_policy='evict_last', other=0.0)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = 64.0
tmp12 = tmp10 / tmp11
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused__log_softmax_6(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 10
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 10 * x0), rmask & xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask & xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask & xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 - tmp11
tl.store(out_ptr2 + (r1 + 10 * x0), tmp12, rmask & xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_2, (32, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_3, (32,), (1,))
assert_size_stride(primals_4, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (64, 64), (64, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (10, 64), (64, 1))
assert_size_stride(primals_9, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 16, 16), (256, 256, 16, 1), torch.
float32)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_0[grid(1024)](primals_1, buf0, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 32, 16, 16), (8192, 256, 16, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_relu_1[grid(32768)](buf2, primals_3,
32768, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 64, 16, 16), (16384, 256, 16, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_relu_2[grid(65536)](buf4, primals_5,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((4, 64, 8, 8), (4096, 64, 8, 1), torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(16384)](buf4, buf5,
16384, XBLOCK=128, num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
buf7 = buf6
del buf6
triton_per_fused_mean_squeeze_4[grid(256)](buf7, buf4, 256, 64,
XBLOCK=32, num_warps=8, num_stages=1)
buf8 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
extern_kernels.mm(buf7, reinterpret_tensor(primals_6, (64, 64), (1,
64), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_5[grid(256)](buf9, primals_7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_9, buf9, reinterpret_tensor(primals_8,
(64, 10), (1, 64), 0), alpha=1, beta=1, out=buf10)
del primals_9
buf13 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
triton_per_fused__log_softmax_6[grid(4)](buf10, buf13, 4, 10,
XBLOCK=1, num_warps=2, num_stages=1)
del buf10
return (buf13, primals_2, primals_4, buf0, buf2, buf4, buf5, buf7, buf9,
buf13, primals_8, primals_6)
class ClassicalConv5New(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, 1, padding=1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(64, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
mit-han-lab/pytorch-quantum
|
ClassicalConv5
| false
| 16,107
|
[
"MIT"
] | 98
|
05cf000d689307f6b1fe02d12744ad455685935b
|
https://github.com/mit-han-lab/pytorch-quantum/tree/05cf000d689307f6b1fe02d12744ad455685935b
|
Generator
|
import torch
from torch import nn
def gumbel_softmax(logits, tau=1.0, hard=False, log_mode=True, dim=-1):
while True:
gumbels = -torch.empty_like(logits).exponential_().log()
gumbels = (logits + gumbels) / tau
if log_mode:
y_soft = gumbels.log_softmax(dim)
else:
y_soft = gumbels.softmax(dim)
if torch.sum(torch.isnan(y_soft)).item() < 0.01:
break
if hard:
index = y_soft.max(dim, keepdim=True)[1]
y_hard = torch.zeros_like(logits).scatter_(dim, index, 1.0)
ret = y_hard - y_soft.detach() + y_soft
else:
ret = y_soft
return ret
class Generator(nn.Module):
def __init__(self, vocab_size, dec_hidden_size, pad_idx):
super(Generator, self).__init__()
self.linear = nn.Linear(dec_hidden_size, vocab_size)
self.softmax = nn.LogSoftmax(dim=-1)
self.pad_idx = pad_idx
def forward(self, x, use_gumbel_softmax=False):
output = self.linear(x)
output[:, self.pad_idx] = -float('inf')
if use_gumbel_softmax:
output = gumbel_softmax(output, log_mode=True, dim=-1)
else:
output = self.softmax(output)
return output
def get_inputs():
return [torch.rand([4, 5, 4, 4])]
def get_init_inputs():
return [[], {'vocab_size': 4, 'dec_hidden_size': 4, 'pad_idx': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 320
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16 % 5
x5 = xindex
x6 = xindex // 4
tmp3 = tl.load(in_ptr0 + x5, xmask)
tmp6 = tl.load(in_ptr0 + 4 * x6, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x6), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (2 + 4 * x6), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr0 + (3 + 4 * x6), xmask, eviction_policy='evict_last'
)
tmp0 = x2
tmp1 = tl.full([1], 4, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = float('-inf')
tmp5 = tl.where(tmp2, tmp4, tmp3)
tmp7 = tl.where(tmp2, tmp4, tmp6)
tmp9 = tl.where(tmp2, tmp4, tmp8)
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tl.where(tmp2, tmp4, tmp11)
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp15 = tl.where(tmp2, tmp4, tmp14)
tmp16 = triton_helpers.maximum(tmp13, tmp15)
tmp17 = tmp5 - tmp16
tl.store(out_ptr0 + x5, tmp17, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 320
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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, 5, 4, 4), (80, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((80, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (80,
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, 5, 4, 4), (80, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(320)](buf0, buf1, 320, XBLOCK=
256, num_warps=4, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 5, 4, 4), (80, 16, 4, 1), 0)
del buf0
triton_poi_fused__log_softmax_1[grid(320)](buf1, buf2, 320, XBLOCK=
256, num_warps=4, num_stages=1)
del buf1
return buf2, reinterpret_tensor(primals_3, (80, 4), (4, 1), 0), buf2
def gumbel_softmax(logits, tau=1.0, hard=False, log_mode=True, dim=-1):
while True:
gumbels = -torch.empty_like(logits).exponential_().log()
gumbels = (logits + gumbels) / tau
if log_mode:
y_soft = gumbels.log_softmax(dim)
else:
y_soft = gumbels.softmax(dim)
if torch.sum(torch.isnan(y_soft)).item() < 0.01:
break
if hard:
index = y_soft.max(dim, keepdim=True)[1]
y_hard = torch.zeros_like(logits).scatter_(dim, index, 1.0)
ret = y_hard - y_soft.detach() + y_soft
else:
ret = y_soft
return ret
class GeneratorNew(nn.Module):
def __init__(self, vocab_size, dec_hidden_size, pad_idx):
super(GeneratorNew, self).__init__()
self.linear = nn.Linear(dec_hidden_size, vocab_size)
self.softmax = nn.LogSoftmax(dim=-1)
self.pad_idx = pad_idx
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]
|
mosespv96/SCAPT-ABSA
|
Generator
| false
| 16,108
|
[
"MIT"
] | 49
|
6f7f89a131127f262a8d1fd2774e5a96b58e7193
|
https://github.com/mosespv96/SCAPT-ABSA/tree/6f7f89a131127f262a8d1fd2774e5a96b58e7193
|
ShiftSoftplus
|
import torch
import numpy as np
from torch.nn import Softplus
class ShiftSoftplus(Softplus):
"""
Shiftsoft plus activation function:
1/beta * (log(1 + exp**(beta * x)) - log(shift))
"""
def __init__(self, beta=1, shift=2, threshold=20):
super().__init__(beta, threshold)
self.shift = shift
self.softplus = Softplus(beta, threshold)
def forward(self, input):
return self.softplus(input) - np.log(float(self.shift))
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, math as tl_math
from torch.nn import Softplus
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_softplus_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 20.0
tmp2 = tmp0 > tmp1
tmp3 = tl_math.exp(tmp0)
tmp4 = libdevice.log1p(tmp3)
tmp5 = tl.where(tmp2, tmp0, tmp4)
tmp6 = 0.6931471805599453
tmp7 = tmp5 - tmp6
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_log_softplus_sub_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ShiftSoftplusNew(Softplus):
"""
Shiftsoft plus activation function:
1/beta * (log(1 + exp**(beta * x)) - log(shift))
"""
def __init__(self, beta=1, shift=2, threshold=20):
super().__init__(beta, threshold)
self.shift = shift
self.softplus = Softplus(beta, threshold)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
mufeili/Alchemy
|
ShiftSoftplus
| false
| 16,109
|
[
"MIT"
] | 116
|
659c59fbbe93d406f8b3e0711e5a048e58c9c43c
|
https://github.com/mufeili/Alchemy/tree/659c59fbbe93d406f8b3e0711e5a048e58c9c43c
|
Sinh
|
import torch
import torch.onnx
import torch.nn as nn
class Sinh(nn.Module):
def forward(self, x):
return torch.sinh(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.onnx
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_sinh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.sinh(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_sinh_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SinhNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
mil-tokyo/webdnn
|
Sinh
| false
| 16,110
|
[
"MIT"
] | 1,967
|
38a60fd3e1a4e72bc01108189a3aa51e0752aecd
|
https://github.com/mil-tokyo/webdnn/tree/38a60fd3e1a4e72bc01108189a3aa51e0752aecd
|
VAE
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class VAE(nn.Module):
def __init__(self):
super(VAE, self).__init__()
self.fc1 = nn.Linear(784, 400)
self.fc21 = nn.Linear(400, 20)
self.fc22 = nn.Linear(400, 20)
self.fc3 = nn.Linear(20, 400)
self.fc4 = nn.Linear(400, 784)
def encode(self, x):
h1 = F.relu(self.fc1(x))
return self.fc21(h1), self.fc22(h1)
def reparameterize(self, mu, logvar):
if self.training:
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return eps.mul(std).add_(mu)
else:
return mu
def decode(self, z):
h3 = F.relu(self.fc3(z))
return torch.sigmoid(self.fc4(h3))
def forward(self, x):
mu, logvar = self.encode(x.view(-1, 784))
z = self.reparameterize(mu, logvar)
return self.decode(z), mu, logvar
def get_inputs():
return [torch.rand([4, 784])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 400
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 3136
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 784
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 784), (784, 1))
assert_size_stride(primals_2, (400, 784), (784, 1))
assert_size_stride(primals_3, (400,), (1,))
assert_size_stride(primals_4, (20, 400), (400, 1))
assert_size_stride(primals_5, (20,), (1,))
assert_size_stride(primals_6, (20, 400), (400, 1))
assert_size_stride(primals_7, (20,), (1,))
assert_size_stride(primals_8, (400, 20), (20, 1))
assert_size_stride(primals_9, (400,), (1,))
assert_size_stride(primals_10, (784, 400), (400, 1))
assert_size_stride(primals_11, (784,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 400), (400, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (784,
400), (1, 784), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(1600)](buf1, primals_3, 1600, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 20), (20, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(400, 20), (1, 400), 0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 20), (20, 1), torch.float32)
extern_kernels.addmm(primals_7, buf1, reinterpret_tensor(primals_6,
(400, 20), (1, 400), 0), alpha=1, beta=1, out=buf3)
del primals_7
buf4 = empty_strided_cuda((4, 400), (400, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_8, (20, 400), (1,
20), 0), out=buf4)
buf5 = buf4
del buf4
triton_poi_fused_relu_0[grid(1600)](buf5, primals_9, 1600, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_9
buf6 = empty_strided_cuda((4, 784), (784, 1), torch.float32)
extern_kernels.mm(buf5, reinterpret_tensor(primals_10, (400, 784),
(1, 400), 0), out=buf6)
buf7 = buf6
del buf6
triton_poi_fused_sigmoid_1[grid(3136)](buf7, primals_11, 3136,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
return (buf7, buf2, buf3, primals_1, buf1, buf2, buf5, buf7, primals_10,
primals_8, primals_6, primals_4)
class VAENew(nn.Module):
def __init__(self):
super(VAENew, self).__init__()
self.fc1 = nn.Linear(784, 400)
self.fc21 = nn.Linear(400, 20)
self.fc22 = nn.Linear(400, 20)
self.fc3 = nn.Linear(20, 400)
self.fc4 = nn.Linear(400, 784)
def encode(self, x):
h1 = F.relu(self.fc1(x))
return self.fc21(h1), self.fc22(h1)
def reparameterize(self, mu, logvar):
if self.training:
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return eps.mul(std).add_(mu)
else:
return mu
def decode(self, z):
h3 = F.relu(self.fc3(z))
return torch.sigmoid(self.fc4(h3))
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc21.weight
primals_5 = self.fc21.bias
primals_6 = self.fc22.weight
primals_7 = self.fc22.bias
primals_8 = self.fc3.weight
primals_9 = self.fc3.bias
primals_10 = self.fc4.weight
primals_11 = self.fc4.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1], output[2]
|
momohatt/chainer-compiler
|
VAE
| false
| 16,111
|
[
"MIT"
] | 116
|
26782cd29a5becf8e2badf268b47d98b3a6aea1d
|
https://github.com/momohatt/chainer-compiler/tree/26782cd29a5becf8e2badf268b47d98b3a6aea1d
|
idct_8x8
|
import itertools
import torch
import numpy as np
import torch.nn as nn
class idct_8x8(nn.Module):
""" Inverse discrete Cosine Transformation
Input:
dcp(tensor): batch x height x width
Output:
image(tensor): batch x height x width
"""
def __init__(self):
super(idct_8x8, self).__init__()
alpha = np.array([1.0 / np.sqrt(2)] + [1] * 7)
self.alpha = nn.Parameter(torch.from_numpy(np.outer(alpha, alpha)).
float())
tensor = np.zeros((8, 8, 8, 8), dtype=np.float32)
for x, y, u, v in itertools.product(range(8), repeat=4):
tensor[x, y, u, v] = np.cos((2 * u + 1) * x * np.pi / 16) * np.cos(
(2 * v + 1) * y * np.pi / 16)
self.tensor = nn.Parameter(torch.from_numpy(tensor).float())
def forward(self, image):
image = image * self.alpha
result = 0.25 * torch.tensordot(image, self.tensor, dims=2) + 128
result.view(image.shape)
return result
def get_inputs():
return [torch.rand([4, 4, 8, 8])]
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 itertools
import numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_mul_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 0.25
tmp2 = tmp0 * tmp1
tmp3 = 128.0
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (8, 8), (8, 1))
assert_size_stride(primals_2, (4, 4, 8, 8), (256, 64, 8, 1))
assert_size_stride(primals_3, (8, 8, 8, 8), (512, 64, 8, 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_mul_0[grid(1024)](primals_2, primals_1, buf0, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 64), (64, 1), 0),
reinterpret_tensor(primals_3, (64, 64), (64, 1), 0), out=buf1)
buf2 = reinterpret_tensor(buf1, (4, 4, 8, 8), (256, 64, 8, 1), 0)
del buf1
triton_poi_fused_add_mul_1[grid(1024)](buf2, 1024, XBLOCK=256,
num_warps=4, num_stages=1)
return buf2, primals_2, reinterpret_tensor(buf0, (64, 16), (1, 64), 0
), reinterpret_tensor(primals_3, (64, 64), (1, 64), 0)
class idct_8x8New(nn.Module):
""" Inverse discrete Cosine Transformation
Input:
dcp(tensor): batch x height x width
Output:
image(tensor): batch x height x width
"""
def __init__(self):
super(idct_8x8New, self).__init__()
alpha = np.array([1.0 / np.sqrt(2)] + [1] * 7)
self.alpha = nn.Parameter(torch.from_numpy(np.outer(alpha, alpha)).
float())
tensor = np.zeros((8, 8, 8, 8), dtype=np.float32)
for x, y, u, v in itertools.product(range(8), repeat=4):
tensor[x, y, u, v] = np.cos((2 * u + 1) * x * np.pi / 16) * np.cos(
(2 * v + 1) * y * np.pi / 16)
self.tensor = nn.Parameter(torch.from_numpy(tensor).float())
def forward(self, input_0):
primals_1 = self.alpha
primals_3 = self.tensor
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
mlomnitz/DifferentiableJPEG
|
idct_8x8
| false
| 16,112
|
[
"MIT"
] | 86
|
a5767feba955a1bcb78600135a09c36a806f6249
|
https://github.com/mlomnitz/DifferentiableJPEG/tree/a5767feba955a1bcb78600135a09c36a806f6249
|
NextSentencePrediction
|
import torch
import torch.nn as nn
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
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]
|
mortonjt/BERT-pytorch
|
NextSentencePrediction
| false
| 16,113
|
[
"Apache-2.0"
] | 5,013
|
d10dc4f9d5a6f2ca74380f62039526eb7277c671
|
https://github.com/mortonjt/BERT-pytorch/tree/d10dc4f9d5a6f2ca74380f62039526eb7277c671
|
ClassicalConv6
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.utils.prune
import torch.backends.cudnn
import torch.cuda
import torch.nn
import torch.utils.data
class ClassicalConv6(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, 1, padding=1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(64, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = x.view(x.shape[0], x.shape[1], -1)
x = x.mean(-1).squeeze()
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
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
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.utils.prune
import torch.backends.cudnn
import torch.cuda
import torch.nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_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)
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')
tmp7 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, None)
@triton.jit
def triton_red_fused_mean_3(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr, RBLOCK: tl.constexpr):
rnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
_tmp8 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (2 * (r1 % 32) + 128 * (r1 // 32) + 512 *
x0), rmask, eviction_policy='evict_last', other=0.0)
tmp1 = tl.load(in_ptr0 + (1 + 2 * (r1 % 32) + 128 * (r1 // 32) +
512 * x0), rmask, eviction_policy='evict_last', other=0.0)
tmp3 = tl.load(in_ptr0 + (64 + 2 * (r1 % 32) + 128 * (r1 // 32) +
512 * x0), rmask, eviction_policy='evict_last', other=0.0)
tmp5 = tl.load(in_ptr0 + (65 + 2 * (r1 % 32) + 128 * (r1 // 32) +
512 * x0), rmask, eviction_policy='evict_last', other=0.0)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = _tmp8 + tmp7
_tmp8 = tl.where(rmask, tmp9, _tmp8)
tmp8 = tl.sum(_tmp8, 1)[:, None]
tl.store(out_ptr0 + x0, tmp8, None)
@triton.jit
def triton_per_fused_mean_squeeze_4(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 256
RBLOCK: tl.constexpr = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 8 * 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 = 1024.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused__log_softmax_6(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 10
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 10 * x0), rmask & xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask & xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask & xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 - tmp11
tl.store(out_ptr2 + (r1 + 10 * x0), tmp12, rmask & xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (32, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (64, 64), (64, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (10, 64), (64, 1))
assert_size_stride(primals_9, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(524288)](buf1, primals_2,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(1048576)](buf3, primals_5,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_2[grid(262144)](buf3, buf4,
262144, XBLOCK=512, num_warps=8, num_stages=1)
buf5 = empty_strided_cuda((4, 64, 8), (512, 8, 1), torch.float32)
triton_red_fused_mean_3[grid(2048)](buf3, buf5, 2048, 128, XBLOCK=
64, RBLOCK=8, num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
buf7 = buf6
del buf6
triton_per_fused_mean_squeeze_4[grid(256)](buf7, buf5, 256, 8,
XBLOCK=32, num_warps=2, num_stages=1)
del buf5
buf8 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
extern_kernels.mm(buf7, reinterpret_tensor(primals_6, (64, 64), (1,
64), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_5[grid(256)](buf9, primals_7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_9, buf9, reinterpret_tensor(primals_8,
(64, 10), (1, 64), 0), alpha=1, beta=1, out=buf10)
del primals_9
buf13 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
triton_per_fused__log_softmax_6[grid(4)](buf10, buf13, 4, 10,
XBLOCK=1, num_warps=2, num_stages=1)
del buf10
return (buf13, primals_1, primals_3, primals_4, buf1, buf3, buf4, buf7,
buf9, buf13, primals_8, primals_6)
class ClassicalConv6New(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, 1, padding=1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(64, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
mit-han-lab/pytorch-quantum
|
ClassicalConv6
| false
| 16,114
|
[
"MIT"
] | 98
|
05cf000d689307f6b1fe02d12744ad455685935b
|
https://github.com/mit-han-lab/pytorch-quantum/tree/05cf000d689307f6b1fe02d12744ad455685935b
|
ComplexDropout
|
import torch
from torch import nn
import torch.utils
class ComplexDropout(nn.Module):
def __init__(self, p=0.5, inplace=False):
super(ComplexDropout, self).__init__()
self.p = p
self.inplace = inplace
self.dropout_r = nn.Dropout(p, inplace)
self.dropout_i = nn.Dropout(p, inplace)
def forward(self, input_r, input_i):
return self.dropout_r(input_r), self.dropout_i(input_i)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.utils
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tl.store(out_ptr0 + x0, 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)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(256)](arg1_1, buf1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg1_1
return buf0, buf1
class ComplexDropoutNew(nn.Module):
def __init__(self, p=0.5, inplace=False):
super(ComplexDropoutNew, self).__init__()
self.p = p
self.inplace = inplace
self.dropout_r = nn.Dropout(p, inplace)
self.dropout_i = nn.Dropout(p, inplace)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
muqiaoy/dl_signal
|
ComplexDropout
| false
| 16,115
|
[
"MIT"
] | 54
|
3a30d14982016644bfc96a7d1ca0109b441f17fd
|
https://github.com/muqiaoy/dl_signal/tree/3a30d14982016644bfc96a7d1ca0109b441f17fd
|
SeparableBlock
|
from torch.nn import Module
import torch
from torch.nn import Linear
class SeparableBlock(Module):
def __init__(self, input_size, kernel_channels_in, kernel_channels_out,
kernel_size):
super(SeparableBlock, self).__init__()
self.input_size = input_size
self.kernel_size = kernel_size
self.kernel_channels_in = kernel_channels_in
self.kernel_channels_out = kernel_channels_out
self.make_kernel_in = Linear(input_size, kernel_size * kernel_size *
kernel_channels_in)
self.make_kernel_out = Linear(input_size, kernel_size * kernel_size *
kernel_channels_out)
self.kernel_linear_in = Linear(kernel_channels_in, kernel_channels_in)
self.kernel_linear_out = Linear(kernel_channels_out,
kernel_channels_out)
def forward(self, features):
features = features.view(-1, self.input_size)
kernel_in = self.make_kernel_in(features).view(-1, self.kernel_size,
self.kernel_size, 1, self.kernel_channels_in)
kernel_out = self.make_kernel_out(features).view(-1, self.
kernel_size, self.kernel_size, self.kernel_channels_out, 1)
kernel = torch.matmul(kernel_out, kernel_in)
kernel = self.kernel_linear_in(kernel).permute(0, 1, 2, 4, 3)
kernel = self.kernel_linear_out(kernel)
kernel = kernel.permute(0, 4, 3, 1, 2)
return kernel
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'kernel_channels_in': 4,
'kernel_channels_out': 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.nn import Module
from torch.nn import Linear
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask)
@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (64, 4), (4, 1))
assert_size_stride(primals_3, (64,), (1,))
assert_size_stride(primals_4, (64, 4), (4, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 64), (1, 4),
0), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 64), (1, 4),
0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((1024, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (1024, 4, 1), (4, 1, 1),
0), reinterpret_tensor(buf0, (1024, 1, 4), (4, 4, 1), 0), out=buf2)
buf3 = empty_strided_cuda((4096, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (4096, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((64, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4096, 4)](buf3, primals_7, buf4, 4096,
4, XBLOCK=4, YBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf5 = buf3
del buf3
extern_kernels.mm(reinterpret_tensor(buf4, (4096, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (64, 4, 4, 4, 4), (256, 64, 16, 4,
1), 0)
del buf5
triton_poi_fused_add_1[grid(16384)](buf6, primals_9, 16384, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
return reinterpret_tensor(buf6, (64, 4, 4, 4, 4), (256, 1, 4, 64, 16), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4096, 4), (4, 1), 0), reinterpret_tensor(
buf4, (4096, 4), (4, 1), 0), primals_8, primals_6, reinterpret_tensor(
buf1, (1024, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf0, (1024,
4, 1), (4, 1, 4), 0)
class SeparableBlockNew(Module):
def __init__(self, input_size, kernel_channels_in, kernel_channels_out,
kernel_size):
super(SeparableBlockNew, self).__init__()
self.input_size = input_size
self.kernel_size = kernel_size
self.kernel_channels_in = kernel_channels_in
self.kernel_channels_out = kernel_channels_out
self.make_kernel_in = Linear(input_size, kernel_size * kernel_size *
kernel_channels_in)
self.make_kernel_out = Linear(input_size, kernel_size * kernel_size *
kernel_channels_out)
self.kernel_linear_in = Linear(kernel_channels_in, kernel_channels_in)
self.kernel_linear_out = Linear(kernel_channels_out,
kernel_channels_out)
def forward(self, input_0):
primals_2 = self.make_kernel_in.weight
primals_3 = self.make_kernel_in.bias
primals_4 = self.make_kernel_out.weight
primals_5 = self.make_kernel_out.bias
primals_6 = self.kernel_linear_in.weight
primals_7 = self.kernel_linear_in.bias
primals_8 = self.kernel_linear_out.weight
primals_9 = self.kernel_linear_out.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
morzh/hyperstyle
|
SeparableBlock
| false
| 16,116
|
[
"MIT"
] | 692
|
ed87f620143d045f374aa42712a43abd751a90e6
|
https://github.com/morzh/hyperstyle/tree/ed87f620143d045f374aa42712a43abd751a90e6
|
ComplexReLU
|
import torch
from torch import nn
import torch.utils
class ComplexReLU(nn.Module):
def __init__(self):
super(ComplexReLU, self).__init__()
self.relu_r = nn.ReLU()
self.relu_i = nn.ReLU()
def forward(self, input_r, input_i):
return self.relu_r(input_r), self.relu_i(input_i)
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 import nn
import torch.utils
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_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.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
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_relu_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_relu_0[grid(256)](arg1_1, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg1_1
return buf0, buf1
class ComplexReLUNew(nn.Module):
def __init__(self):
super(ComplexReLUNew, self).__init__()
self.relu_r = nn.ReLU()
self.relu_i = nn.ReLU()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
muqiaoy/dl_signal
|
ComplexReLU
| false
| 16,117
|
[
"MIT"
] | 54
|
3a30d14982016644bfc96a7d1ca0109b441f17fd
|
https://github.com/muqiaoy/dl_signal/tree/3a30d14982016644bfc96a7d1ca0109b441f17fd
|
LabelSmoothing
|
import torch
import torch.nn as nn
class LabelSmoothing(nn.Module):
"""
NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.0, n_cls=2):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
"""
super(LabelSmoothing, self).__init__()
self.confidence = 1.0 - smoothing + smoothing / n_cls
self.smoothing = smoothing / n_cls
def forward(self, x, target):
probs = torch.nn.functional.sigmoid(x)
target1 = self.confidence * target + (1 - target) * self.smoothing
loss = -(torch.log(probs + 1e-15) * target1 + (1 - target1) * torch
.log(1 - probs + 1e-15))
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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_log_mean_mul_neg_rsub_sigmoid_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp5 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.sigmoid(tmp0)
tmp2 = 1e-15
tmp3 = tmp1 + tmp2
tmp4 = tl_math.log(tmp3)
tmp6 = 1.0
tmp7 = tmp5 * tmp6
tmp8 = tmp6 - tmp5
tmp9 = 0.0
tmp10 = tmp8 * tmp9
tmp11 = tmp7 + tmp10
tmp12 = tmp4 * tmp11
tmp13 = tmp6 - tmp11
tmp14 = tmp6 - tmp1
tmp15 = tmp14 + tmp2
tmp16 = tl_math.log(tmp15)
tmp17 = tmp13 * tmp16
tmp18 = tmp12 + tmp17
tmp19 = -tmp18
tmp20 = tl.broadcast_to(tmp19, [RBLOCK])
tmp22 = triton_helpers.promote_to_tensor(tl.sum(tmp20, 0))
tmp23 = 256.0
tmp24 = tmp22 / tmp23
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp24, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_log_mean_mul_neg_rsub_sigmoid_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 LabelSmoothingNew(nn.Module):
"""
NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.0, n_cls=2):
"""
Constructor for the LabelSmoothing module.
:param smoothing: label smoothing factor
"""
super(LabelSmoothingNew, self).__init__()
self.confidence = 1.0 - smoothing + smoothing / n_cls
self.smoothing = smoothing / n_cls
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
mrblasco/kaggle_moa_winner_hungry_for_gold
|
LabelSmoothing
| false
| 16,118
|
[
"Apache-2.0"
] | 89
|
00df6d0aa4a48e526cee3e36f6e723a1534bfa08
|
https://github.com/mrblasco/kaggle_moa_winner_hungry_for_gold/tree/00df6d0aa4a48e526cee3e36f6e723a1534bfa08
|
ComplexConv1d
|
import torch
from torch import nn
import torch.utils
class ComplexConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=0, dilation=1, groups=1, bias=True):
super(ComplexConv1d, self).__init__()
self.conv_r = nn.Conv1d(in_channels, out_channels, kernel_size,
stride, padding, dilation, groups, bias)
self.conv_i = nn.Conv1d(in_channels, out_channels, kernel_size,
stride, padding, dilation, groups, bias)
def forward(self, input_r, input_i):
return self.conv_r(input_r) - self.conv_i(input_i), self.conv_r(input_i
) + self.conv_i(input_r)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([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 import nn
import torch.utils
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_sub_0(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 2
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_out_ptr1 + x2, xmask)
tmp9 = tl.load(in_ptr3 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 - tmp5
tmp8 = tmp7 + tmp1
tmp10 = tmp9 + tmp4
tmp11 = tmp8 + tmp10
tl.store(in_out_ptr0 + x2, tmp6, xmask)
tl.store(in_out_ptr1 + x2, tmp11, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3), (12, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 3), (12, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4), (16, 4, 1), 0), primals_1, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (1, 4, 2), (8, 2, 1))
buf1 = extern_kernels.convolution(reinterpret_tensor(primals_6, (1,
4, 4), (16, 4, 1), 0), primals_4, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf1, (1, 4, 2), (8, 2, 1))
buf3 = extern_kernels.convolution(reinterpret_tensor(primals_6, (1,
4, 4), (16, 4, 1), 0), primals_1, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf3, (1, 4, 2), (8, 2, 1))
buf4 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4), (16, 4, 1), 0), primals_4, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf4, (1, 4, 2), (8, 2, 1))
buf2 = reinterpret_tensor(buf0, (4, 2), (2, 1), 0)
del buf0
buf5 = reinterpret_tensor(buf3, (4, 2), (2, 1), 0)
del buf3
get_raw_stream(0)
triton_poi_fused_add_sub_0[grid(8)](buf2, buf5, primals_2, buf1,
primals_5, buf4, 8, XBLOCK=8, num_warps=1, num_stages=1)
del buf1
del buf4
del primals_2
del primals_5
return buf2, buf5, primals_1, primals_4, reinterpret_tensor(primals_3,
(1, 4, 4), (16, 4, 1), 0), reinterpret_tensor(primals_6, (1, 4, 4),
(16, 4, 1), 0)
class ComplexConv1dNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=0, dilation=1, groups=1, bias=True):
super(ComplexConv1dNew, self).__init__()
self.conv_r = nn.Conv1d(in_channels, out_channels, kernel_size,
stride, padding, dilation, groups, bias)
self.conv_i = nn.Conv1d(in_channels, out_channels, kernel_size,
stride, padding, dilation, groups, bias)
def forward(self, input_0, input_1):
primals_1 = self.conv_r.weight
primals_2 = self.conv_r.bias
primals_4 = self.conv_i.weight
primals_5 = self.conv_i.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0], output[1]
|
muqiaoy/dl_signal
|
ComplexConv1d
| false
| 16,119
|
[
"MIT"
] | 54
|
3a30d14982016644bfc96a7d1ca0109b441f17fd
|
https://github.com/muqiaoy/dl_signal/tree/3a30d14982016644bfc96a7d1ca0109b441f17fd
|
ComplexMaxPool1d
|
import torch
from torch import nn
import torch.utils
class ComplexMaxPool1d(nn.Module):
def __init__(self, kernel_size, stride=None, padding=0, dilation=1,
return_indices=False, ceil_mode=False):
super(ComplexMaxPool1d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.ceil_mode = ceil_mode
self.return_indices = return_indices
self.maxpool_r = nn.MaxPool1d(kernel_size=self.kernel_size, stride=
self.stride, padding=self.padding, dilation=self.dilation,
ceil_mode=self.ceil_mode, return_indices=self.return_indices)
self.maxpool_i = nn.MaxPool1d(kernel_size=self.kernel_size, stride=
self.stride, padding=self.padding, dilation=self.dilation,
ceil_mode=self.ceil_mode, return_indices=self.return_indices)
def forward(self, input_r, input_i):
return self.maxpool_r(input_r), self.maxpool_i(input_i)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([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
from torch import nn
import torch.utils
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(4)](arg0_1, buf0, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
triton_poi_fused_max_pool2d_with_indices_0[grid(4)](arg1_1, buf1, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del arg1_1
return reinterpret_tensor(buf0, (4, 1), (1, 1), 0), reinterpret_tensor(buf1
, (4, 1), (1, 1), 0)
class ComplexMaxPool1dNew(nn.Module):
def __init__(self, kernel_size, stride=None, padding=0, dilation=1,
return_indices=False, ceil_mode=False):
super(ComplexMaxPool1dNew, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.ceil_mode = ceil_mode
self.return_indices = return_indices
self.maxpool_r = nn.MaxPool1d(kernel_size=self.kernel_size, stride=
self.stride, padding=self.padding, dilation=self.dilation,
ceil_mode=self.ceil_mode, return_indices=self.return_indices)
self.maxpool_i = nn.MaxPool1d(kernel_size=self.kernel_size, stride=
self.stride, padding=self.padding, dilation=self.dilation,
ceil_mode=self.ceil_mode, return_indices=self.return_indices)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
muqiaoy/dl_signal
|
ComplexMaxPool1d
| false
| 16,120
|
[
"MIT"
] | 54
|
3a30d14982016644bfc96a7d1ca0109b441f17fd
|
https://github.com/muqiaoy/dl_signal/tree/3a30d14982016644bfc96a7d1ca0109b441f17fd
|
LinearWithGroupNorm
|
import torch
import torch.utils.data
from torch import nn
from math import gcd
import torch.cuda
class LinearWithGroupNorm(nn.Module):
"""Linear layer with group normalization activation used in LaneGCN."""
def __init__(self, n_in: 'int', n_out: 'int', num_groups: 'int'=32,
activation: 'bool'=True) ->None:
"""
Initialize layer.
:param n_in: Number of input channels.
:param n_out: Number of output channels.
:param num_groups: Number of groups for GroupNorm.
:param activation: Boolean indicating whether to apply ReLU activation.
"""
super().__init__()
self.linear = nn.Linear(n_in, n_out, bias=False)
self.norm = nn.GroupNorm(gcd(num_groups, n_out), n_out)
self.relu = nn.ReLU(inplace=True)
self.activation = activation
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
"""
Apply linear layer to input tensor.
:param x: Input tensor.
:return: Output of linear layer.
"""
out = self.linear(x)
out = self.norm(out)
if self.activation:
out = self.relu(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_in': 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 libdevice
import torch.utils.data
from torch import nn
from math import gcd
import torch.cuda
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_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 = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + x2, xmask, 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], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp0 - tmp10
tmp18 = 16.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
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 + 16 * x0), tmp29, xmask)
tl.store(out_ptr3 + (r1 + 16 * 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), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), 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, 4, 1, 1), (4, 1, 16, 16), torch.float32)
get_raw_stream(0)
triton_per_fused_native_group_norm_relu_threshold_backward_0[grid(16)](
buf0, primals_3, primals_4, buf1, buf5, buf6, buf4, 16, 16,
XBLOCK=1, num_warps=2, num_stages=1)
del primals_4
return buf5, primals_3, reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf1, (4, 4), (4, 1), 0
), reinterpret_tensor(buf4, (4, 4), (4, 1), 0), buf6
class LinearWithGroupNormNew(nn.Module):
"""Linear layer with group normalization activation used in LaneGCN."""
def __init__(self, n_in: 'int', n_out: 'int', num_groups: 'int'=32,
activation: 'bool'=True) ->None:
"""
Initialize layer.
:param n_in: Number of input channels.
:param n_out: Number of output channels.
:param num_groups: Number of groups for GroupNorm.
:param activation: Boolean indicating whether to apply ReLU activation.
"""
super().__init__()
self.linear = nn.Linear(n_in, n_out, bias=False)
self.norm = nn.GroupNorm(gcd(num_groups, n_out), n_out)
self.relu = nn.ReLU(inplace=True)
self.activation = activation
def forward(self, input_0):
primals_1 = self.linear.weight
primals_3 = self.norm.weight
primals_4 = self.norm.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
motional/nuplan-devkit
|
LinearWithGroupNorm
| false
| 16,121
|
[
"Apache-2.0"
] | 128
|
e39029e788b17f47f2fcadb774098ef8fbdd0d67
|
https://github.com/motional/nuplan-devkit/tree/e39029e788b17f47f2fcadb774098ef8fbdd0d67
|
CRNNcell
|
import torch
import torch.nn as nn
class CRNNcell(nn.Module):
"""
Convolutional RNN cell that evolves over both time and iterations
Parameters
-----------------
input: 4d tensor, shape (batch_size, channel, width, height)
hidden: hidden states in temporal dimension, 4d tensor, shape (batch_size, hidden_size, width, height)
hidden_iteration: hidden states in iteration dimension, 4d tensor, shape (batch_size, hidden_size, width, height)
Returns
-----------------
output: 4d tensor, shape (batch_size, hidden_size, width, height)
"""
def __init__(self, input_size, hidden_size, kernel_size):
super(CRNNcell, self).__init__()
self.kernel_size = kernel_size
self.i2h = nn.Conv2d(input_size, hidden_size, kernel_size, padding=
self.kernel_size // 2)
self.h2h = nn.Conv2d(hidden_size, hidden_size, kernel_size, padding
=self.kernel_size // 2)
self.ih2ih = nn.Conv2d(hidden_size, hidden_size, kernel_size,
padding=self.kernel_size // 2)
self.relu = nn.ReLU(inplace=True)
def forward(self, input, hidden_iteration, hidden):
in_to_hid = self.i2h(input)
hid_to_hid = self.h2h(hidden)
ih_to_ih = self.ih2ih(hidden_iteration)
hidden = self.relu(in_to_hid + hid_to_hid + ih_to_ih)
return hidden
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 [[], {'input_size': 4, 'hidden_size': 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
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_convolution_relu_threshold_backward_0(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 25 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask)
tmp4 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr3 + x3, xmask)
tmp8 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp11 = tl.full([1], 0, tl.int32)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp13 = 0.0
tmp14 = tmp12 <= tmp13
tl.store(in_out_ptr0 + x3, tmp12, xmask)
tl.store(out_ptr0 + x3, 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, 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))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (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=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 5, 5), (100, 25, 5, 1))
buf1 = extern_kernels.convolution(primals_6, primals_4, stride=(1,
1), padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 5, 5), (100, 25, 5, 1))
buf2 = extern_kernels.convolution(primals_9, primals_7, stride=(1,
1), padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 5, 5), (100, 25, 5, 1))
buf3 = buf0
del buf0
buf4 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_convolution_relu_threshold_backward_0[grid(400)](
buf3, primals_2, buf1, primals_5, buf2, primals_8, buf4, 400,
XBLOCK=256, num_warps=4, num_stages=1)
del buf1
del buf2
del primals_2
del primals_5
del primals_8
return (buf3, primals_1, primals_3, primals_4, primals_6, primals_7,
primals_9, buf4)
class CRNNcellNew(nn.Module):
"""
Convolutional RNN cell that evolves over both time and iterations
Parameters
-----------------
input: 4d tensor, shape (batch_size, channel, width, height)
hidden: hidden states in temporal dimension, 4d tensor, shape (batch_size, hidden_size, width, height)
hidden_iteration: hidden states in iteration dimension, 4d tensor, shape (batch_size, hidden_size, width, height)
Returns
-----------------
output: 4d tensor, shape (batch_size, hidden_size, width, height)
"""
def __init__(self, input_size, hidden_size, kernel_size):
super(CRNNcellNew, self).__init__()
self.kernel_size = kernel_size
self.i2h = nn.Conv2d(input_size, hidden_size, kernel_size, padding=
self.kernel_size // 2)
self.h2h = nn.Conv2d(hidden_size, hidden_size, kernel_size, padding
=self.kernel_size // 2)
self.ih2ih = nn.Conv2d(hidden_size, hidden_size, kernel_size,
padding=self.kernel_size // 2)
self.relu = nn.ReLU(inplace=True)
def forward(self, input_0, input_1, input_2):
primals_1 = self.i2h.weight
primals_2 = self.i2h.bias
primals_3 = self.h2h.weight
primals_5 = self.h2h.bias
primals_4 = self.ih2ih.weight
primals_8 = self.ih2ih.bias
primals_6 = input_0
primals_7 = input_1
primals_9 = 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]
|
myyaqubpython/https-github.com-cq615-Deep-MRI-Reconstruction
|
CRNNcell
| false
| 16,122
|
[
"Apache-2.0"
] | 260
|
4484cff9f1e19ff9874c279c5c5d6cf2a317ddbf
|
https://github.com/myyaqubpython/https-github.com-cq615-Deep-MRI-Reconstruction/tree/4484cff9f1e19ff9874c279c5c5d6cf2a317ddbf
|
ComplexLinear
|
import torch
from torch import nn
import torch.utils
class ComplexLinear(nn.Module):
def __init__(self, in_features, out_features):
super(ComplexLinear, self).__init__()
self.fc_r = nn.Linear(in_features, out_features)
self.fc_i = nn.Linear(in_features, out_features)
def forward(self, input_r, input_i):
return self.fc_r(input_r) - self.fc_i(input_i), self.fc_r(input_i
) + self.fc_i(input_r)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.utils
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_sub_0(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_out_ptr1 + x2, xmask)
tmp9 = tl.load(in_ptr3 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 - tmp5
tmp8 = tmp7 + tmp1
tmp10 = tmp9 + tmp4
tmp11 = tmp8 + tmp10
tl.store(in_out_ptr0 + x2, tmp6, xmask)
tl.store(in_out_ptr1 + x2, tmp11, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf3)
del primals_1
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf4)
del primals_4
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
get_raw_stream(0)
triton_poi_fused_add_sub_0[grid(256)](buf2, buf5, primals_2, buf1,
primals_5, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf1
del buf4
del primals_2
del primals_5
return buf2, buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0)
class ComplexLinearNew(nn.Module):
def __init__(self, in_features, out_features):
super(ComplexLinearNew, self).__init__()
self.fc_r = nn.Linear(in_features, out_features)
self.fc_i = nn.Linear(in_features, out_features)
def forward(self, input_0, input_1):
primals_1 = self.fc_r.weight
primals_2 = self.fc_r.bias
primals_4 = self.fc_i.weight
primals_5 = self.fc_i.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0], output[1]
|
muqiaoy/dl_signal
|
ComplexLinear
| false
| 16,123
|
[
"MIT"
] | 54
|
3a30d14982016644bfc96a7d1ca0109b441f17fd
|
https://github.com/muqiaoy/dl_signal/tree/3a30d14982016644bfc96a7d1ca0109b441f17fd
|
LovaszLoss
|
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from itertools import filterfalse
def jaccard(outputs, targets, per_image=False, non_empty=False, min_pixels=5):
batch_size = outputs.size()[0]
eps = 0.001
if not per_image:
batch_size = 1
dice_target = targets.contiguous().view(batch_size, -1).float()
dice_output = outputs.contiguous().view(batch_size, -1)
target_sum = torch.sum(dice_target, dim=1)
intersection = torch.sum(dice_output * dice_target, dim=1)
losses = 1.0 - (intersection + eps) / (torch.sum(dice_output +
dice_target, dim=1) - intersection + eps)
if non_empty:
assert per_image
non_empty_images = 0
sum_loss = 0
for i in range(batch_size):
if target_sum[i] > min_pixels:
sum_loss += losses[i]
non_empty_images += 1
if non_empty_images == 0:
return 0
else:
return sum_loss / non_empty_images
return losses.mean()
def flatten_binary_scores(scores, labels, ignore=None):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = labels != ignore
vscores = scores[valid]
vlabels = labels[valid]
return vscores, vlabels
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts.float() - gt_sorted.float().cumsum(0)
union = gts.float() + (1 - gt_sorted).float().cumsum(0)
jaccard = 1.0 - intersection / union
if p > 1:
jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
return jaccard
def lovasz_hinge_flat(logits, labels):
if len(labels) == 0:
return logits.sum() * 0.0
signs = 2.0 * labels.float() - 1.0
errors = 1.0 - logits * signs
errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_sorted)
loss = torch.dot(F.relu(errors_sorted), grad)
return loss
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
ll = iter(l)
if ignore_nan:
ll = filterfalse(np.isnan, ll)
try:
n = 1
acc = next(ll)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for n, v in enumerate(ll, 2):
acc += v
if n == 1:
return acc
return acc / n
def lovasz_hinge(logits, labels, per_image=True, ignore=None):
if per_image:
loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(
0), lab.unsqueeze(0), ignore)) for log, lab in zip(logits, labels))
else:
loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)
)
return loss
def symmetric_lovasz(outputs, targets):
return (lovasz_hinge(outputs, targets) + lovasz_hinge(-outputs, 1 -
targets)) / 2
class LovaszLoss(nn.Module):
def __init__(self, ignore_index=255, per_image=True):
super().__init__()
self.ignore_index = ignore_index
self.per_image = per_image
def forward(self, outputs, targets):
outputs = outputs.contiguous()
targets = targets.contiguous()
return symmetric_lovasz(outputs, targets)
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
import numpy as np
from torch import nn
import torch.nn.functional as F
from itertools import filterfalse
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_0(in_ptr0, in_ptr1,
out_ptr0, out_ptr2, out_ptr4, out_ptr5, out_ptr6, out_ptr7, out_ptr8,
out_ptr9, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tmp0 * tmp5
tmp7 = tmp4 - tmp6
tmp8 = r0
tmp9 = tmp8.to(tl.int16)
tmp10 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp11 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12, tmp13 = triton_helpers.sort_with_index(tmp10, tmp11, None, 1,
stable=False, descending=True)
tmp14 = -tmp0
tmp15 = tmp4 - tmp1
tmp16 = tmp15 * tmp2
tmp17 = tmp16 - tmp4
tmp18 = tmp14 * tmp17
tmp19 = tmp4 - tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp21, tmp22 = triton_helpers.sort_with_index(tmp20, tmp11, None, 1,
stable=False, descending=True)
tmp23 = tmp13.to(tl.int64)
tmp24 = tl.full([XBLOCK, RBLOCK], 64, tl.int32)
tmp25 = tmp23 + tmp24
tmp26 = tmp23 < 0
tmp27 = tl.where(tmp26, tmp25, tmp23)
tl.device_assert((0 <= tmp27) & (tmp27 < 64),
'index out of bounds: 0 <= tmp27 < 64')
tmp29 = tl.load(in_ptr1 + tmp27, None, eviction_policy='evict_last')
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tmp33 = tmp29.to(tl.float32)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK])
tmp35, = tl.associative_scan((tmp34,), 1, _triton_helper_fn_add0)
tmp36 = tmp4 - tmp29
tmp37 = tmp36.to(tl.float32)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp39, = tl.associative_scan((tmp38,), 1, _triton_helper_fn_add0)
tmp40 = tmp22.to(tl.int64)
tmp41 = tmp40 + tmp24
tmp42 = tmp40 < 0
tmp43 = tl.where(tmp42, tmp41, tmp40)
tl.device_assert((0 <= tmp43) & (tmp43 < 64),
'index out of bounds: 0 <= tmp43 < 64')
tmp45 = tl.load(in_ptr1 + tmp43 % 64, None, eviction_policy='evict_last')
tmp46 = tmp4 - tmp45
tmp47 = tl.broadcast_to(tmp46, [XBLOCK, RBLOCK])
tmp49 = tl.sum(tmp47, 1)[:, None]
tmp50 = tmp46.to(tl.float32)
tmp51 = tl.broadcast_to(tmp50, [XBLOCK, RBLOCK])
tmp52, = tl.associative_scan((tmp51,), 1, _triton_helper_fn_add0)
tmp53 = tmp4 - tmp46
tmp54 = tmp53.to(tl.float32)
tmp55 = tl.broadcast_to(tmp54, [XBLOCK, RBLOCK])
tmp56, = tl.associative_scan((tmp55,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp12, None)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp21, None)
tl.store(out_ptr5 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp35, None)
tl.store(out_ptr6 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp39, None)
tl.store(out_ptr8 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp52, None)
tl.store(out_ptr9 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp56, None)
tl.store(out_ptr4 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)
tl.store(out_ptr7 + tl.full([XBLOCK, 1], 0, tl.int32), tmp49, None)
@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_1(in_ptr0, in_ptr1,
out_ptr0, out_ptr2, out_ptr4, out_ptr5, out_ptr6, out_ptr7, out_ptr8,
out_ptr9, 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 + (64 + r0), None)
tmp1 = tl.load(in_ptr1 + (64 + r0), None)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tmp0 * tmp5
tmp7 = tmp4 - tmp6
tmp8 = r0
tmp9 = tmp8.to(tl.int16)
tmp10 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp11 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12, tmp13 = triton_helpers.sort_with_index(tmp10, tmp11, None, 1,
stable=False, descending=True)
tmp14 = -tmp0
tmp15 = tmp4 - tmp1
tmp16 = tmp15 * tmp2
tmp17 = tmp16 - tmp4
tmp18 = tmp14 * tmp17
tmp19 = tmp4 - tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp21, tmp22 = triton_helpers.sort_with_index(tmp20, tmp11, None, 1,
stable=False, descending=True)
tmp23 = tmp13.to(tl.int64)
tmp24 = tl.full([XBLOCK, RBLOCK], 64, tl.int32)
tmp25 = tmp23 + tmp24
tmp26 = tmp23 < 0
tmp27 = tl.where(tmp26, tmp25, tmp23)
tl.device_assert((0 <= tmp27) & (tmp27 < 64),
'index out of bounds: 0 <= tmp27 < 64')
tmp29 = tl.load(in_ptr1 + (64 + tmp27), None, eviction_policy='evict_last')
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tmp33 = tmp29.to(tl.float32)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK])
tmp35, = tl.associative_scan((tmp34,), 1, _triton_helper_fn_add0)
tmp36 = tmp4 - tmp29
tmp37 = tmp36.to(tl.float32)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp39, = tl.associative_scan((tmp38,), 1, _triton_helper_fn_add0)
tmp40 = tmp22.to(tl.int64)
tmp41 = tmp40 + tmp24
tmp42 = tmp40 < 0
tmp43 = tl.where(tmp42, tmp41, tmp40)
tl.device_assert((0 <= tmp43) & (tmp43 < 64),
'index out of bounds: 0 <= tmp43 < 64')
tmp45 = tl.load(in_ptr1 + (64 + tmp43 % 64), None, eviction_policy=
'evict_last')
tmp46 = tmp4 - tmp45
tmp47 = tl.broadcast_to(tmp46, [XBLOCK, RBLOCK])
tmp49 = tl.sum(tmp47, 1)[:, None]
tmp50 = tmp46.to(tl.float32)
tmp51 = tl.broadcast_to(tmp50, [XBLOCK, RBLOCK])
tmp52, = tl.associative_scan((tmp51,), 1, _triton_helper_fn_add0)
tmp53 = tmp4 - tmp46
tmp54 = tmp53.to(tl.float32)
tmp55 = tl.broadcast_to(tmp54, [XBLOCK, RBLOCK])
tmp56, = tl.associative_scan((tmp55,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp12, None)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp21, None)
tl.store(out_ptr5 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp35, None)
tl.store(out_ptr6 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp39, None)
tl.store(out_ptr8 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp52, None)
tl.store(out_ptr9 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp56, None)
tl.store(out_ptr4 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)
tl.store(out_ptr7 + tl.full([XBLOCK, 1], 0, tl.int32), tmp49, None)
@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_2(in_ptr0, in_ptr1,
out_ptr0, out_ptr2, out_ptr4, out_ptr5, out_ptr6, out_ptr7, out_ptr8,
out_ptr9, 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 + (128 + r0), None)
tmp1 = tl.load(in_ptr1 + (128 + r0), None)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tmp0 * tmp5
tmp7 = tmp4 - tmp6
tmp8 = r0
tmp9 = tmp8.to(tl.int16)
tmp10 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp11 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12, tmp13 = triton_helpers.sort_with_index(tmp10, tmp11, None, 1,
stable=False, descending=True)
tmp14 = -tmp0
tmp15 = tmp4 - tmp1
tmp16 = tmp15 * tmp2
tmp17 = tmp16 - tmp4
tmp18 = tmp14 * tmp17
tmp19 = tmp4 - tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp21, tmp22 = triton_helpers.sort_with_index(tmp20, tmp11, None, 1,
stable=False, descending=True)
tmp23 = tmp13.to(tl.int64)
tmp24 = tl.full([XBLOCK, RBLOCK], 64, tl.int32)
tmp25 = tmp23 + tmp24
tmp26 = tmp23 < 0
tmp27 = tl.where(tmp26, tmp25, tmp23)
tl.device_assert((0 <= tmp27) & (tmp27 < 64),
'index out of bounds: 0 <= tmp27 < 64')
tmp29 = tl.load(in_ptr1 + (128 + tmp27), None, eviction_policy='evict_last'
)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tmp33 = tmp29.to(tl.float32)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK])
tmp35, = tl.associative_scan((tmp34,), 1, _triton_helper_fn_add0)
tmp36 = tmp4 - tmp29
tmp37 = tmp36.to(tl.float32)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp39, = tl.associative_scan((tmp38,), 1, _triton_helper_fn_add0)
tmp40 = tmp22.to(tl.int64)
tmp41 = tmp40 + tmp24
tmp42 = tmp40 < 0
tmp43 = tl.where(tmp42, tmp41, tmp40)
tl.device_assert((0 <= tmp43) & (tmp43 < 64),
'index out of bounds: 0 <= tmp43 < 64')
tmp45 = tl.load(in_ptr1 + (128 + tmp43 % 64), None, eviction_policy=
'evict_last')
tmp46 = tmp4 - tmp45
tmp47 = tl.broadcast_to(tmp46, [XBLOCK, RBLOCK])
tmp49 = tl.sum(tmp47, 1)[:, None]
tmp50 = tmp46.to(tl.float32)
tmp51 = tl.broadcast_to(tmp50, [XBLOCK, RBLOCK])
tmp52, = tl.associative_scan((tmp51,), 1, _triton_helper_fn_add0)
tmp53 = tmp4 - tmp46
tmp54 = tmp53.to(tl.float32)
tmp55 = tl.broadcast_to(tmp54, [XBLOCK, RBLOCK])
tmp56, = tl.associative_scan((tmp55,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp12, None)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp21, None)
tl.store(out_ptr5 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp35, None)
tl.store(out_ptr6 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp39, None)
tl.store(out_ptr8 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp52, None)
tl.store(out_ptr9 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp56, None)
tl.store(out_ptr4 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)
tl.store(out_ptr7 + tl.full([XBLOCK, 1], 0, tl.int32), tmp49, None)
@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_3(in_ptr0, in_ptr1,
out_ptr0, out_ptr2, out_ptr4, out_ptr5, out_ptr6, out_ptr7, out_ptr8,
out_ptr9, 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 + (192 + r0), None)
tmp1 = tl.load(in_ptr1 + (192 + r0), None)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tmp0 * tmp5
tmp7 = tmp4 - tmp6
tmp8 = r0
tmp9 = tmp8.to(tl.int16)
tmp10 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp11 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12, tmp13 = triton_helpers.sort_with_index(tmp10, tmp11, None, 1,
stable=False, descending=True)
tmp14 = -tmp0
tmp15 = tmp4 - tmp1
tmp16 = tmp15 * tmp2
tmp17 = tmp16 - tmp4
tmp18 = tmp14 * tmp17
tmp19 = tmp4 - tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp21, tmp22 = triton_helpers.sort_with_index(tmp20, tmp11, None, 1,
stable=False, descending=True)
tmp23 = tmp13.to(tl.int64)
tmp24 = tl.full([XBLOCK, RBLOCK], 64, tl.int32)
tmp25 = tmp23 + tmp24
tmp26 = tmp23 < 0
tmp27 = tl.where(tmp26, tmp25, tmp23)
tl.device_assert((0 <= tmp27) & (tmp27 < 64),
'index out of bounds: 0 <= tmp27 < 64')
tmp29 = tl.load(in_ptr1 + (192 + tmp27), None, eviction_policy='evict_last'
)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tmp33 = tmp29.to(tl.float32)
tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK])
tmp35, = tl.associative_scan((tmp34,), 1, _triton_helper_fn_add0)
tmp36 = tmp4 - tmp29
tmp37 = tmp36.to(tl.float32)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp39, = tl.associative_scan((tmp38,), 1, _triton_helper_fn_add0)
tmp40 = tmp22.to(tl.int64)
tmp41 = tmp40 + tmp24
tmp42 = tmp40 < 0
tmp43 = tl.where(tmp42, tmp41, tmp40)
tl.device_assert((0 <= tmp43) & (tmp43 < 64),
'index out of bounds: 0 <= tmp43 < 64')
tmp45 = tl.load(in_ptr1 + (192 + tmp43 % 64), None, eviction_policy=
'evict_last')
tmp46 = tmp4 - tmp45
tmp47 = tl.broadcast_to(tmp46, [XBLOCK, RBLOCK])
tmp49 = tl.sum(tmp47, 1)[:, None]
tmp50 = tmp46.to(tl.float32)
tmp51 = tl.broadcast_to(tmp50, [XBLOCK, RBLOCK])
tmp52, = tl.associative_scan((tmp51,), 1, _triton_helper_fn_add0)
tmp53 = tmp4 - tmp46
tmp54 = tmp53.to(tl.float32)
tmp55 = tl.broadcast_to(tmp54, [XBLOCK, RBLOCK])
tmp56, = tl.associative_scan((tmp55,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp12, None)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp21, None)
tl.store(out_ptr5 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp35, None)
tl.store(out_ptr6 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp39, None)
tl.store(out_ptr8 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp52, None)
tl.store(out_ptr9 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp56, None)
tl.store(out_ptr4 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)
tl.store(out_ptr7 + tl.full([XBLOCK, 1], 0, tl.int32), tmp49, None)
@triton.jit
def triton_per_fused_add_div_dot_relu_rsub_sub_4(in_out_ptr0, in_out_ptr1,
in_out_ptr2, in_out_ptr3, in_out_ptr4, in_out_ptr5, in_out_ptr6,
in_out_ptr7, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10, in_ptr11, in_ptr12,
in_ptr13, in_ptr14, in_ptr15, in_ptr16, in_ptr17, in_ptr18, in_ptr19,
in_ptr20, in_ptr21, in_ptr22, in_ptr23, xnumel, rnumel, XBLOCK: tl.
constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp6 = tl.load(in_out_ptr0 + 0)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp24 = tl.load(in_ptr1 + r0, None)
tmp26 = tl.load(in_ptr2 + r0, None)
tmp35 = tl.load(in_ptr3 + r0, None)
tmp37 = tl.load(in_out_ptr1 + 0)
tmp38 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
tmp54 = tl.load(in_ptr4 + r0, None)
tmp56 = tl.load(in_ptr5 + r0, None)
tmp65 = tl.load(in_ptr6 + r0, None)
tmp67 = tl.load(in_out_ptr2 + 0)
tmp68 = tl.broadcast_to(tmp67, [XBLOCK, RBLOCK])
tmp84 = tl.load(in_ptr7 + r0, None)
tmp86 = tl.load(in_ptr8 + r0, None)
tmp95 = tl.load(in_ptr9 + r0, None)
tmp97 = tl.load(in_out_ptr3 + 0)
tmp98 = tl.broadcast_to(tmp97, [XBLOCK, RBLOCK])
tmp114 = tl.load(in_ptr10 + r0, None)
tmp116 = tl.load(in_ptr11 + r0, None)
tmp125 = tl.load(in_ptr12 + r0, None)
tmp127 = tl.load(in_out_ptr4 + 0)
tmp128 = tl.broadcast_to(tmp127, [XBLOCK, RBLOCK])
tmp144 = tl.load(in_ptr13 + r0, None)
tmp146 = tl.load(in_ptr14 + r0, None)
tmp155 = tl.load(in_ptr15 + r0, None)
tmp157 = tl.load(in_out_ptr5 + 0)
tmp158 = tl.broadcast_to(tmp157, [XBLOCK, RBLOCK])
tmp174 = tl.load(in_ptr16 + r0, None)
tmp176 = tl.load(in_ptr17 + r0, None)
tmp185 = tl.load(in_ptr18 + r0, None)
tmp187 = tl.load(in_out_ptr6 + 0)
tmp188 = tl.broadcast_to(tmp187, [XBLOCK, RBLOCK])
tmp204 = tl.load(in_ptr19 + r0, None)
tmp206 = tl.load(in_ptr20 + r0, None)
tmp215 = tl.load(in_ptr21 + r0, None)
tmp217 = tl.load(in_out_ptr7 + 0)
tmp218 = tl.broadcast_to(tmp217, [XBLOCK, RBLOCK])
tmp234 = tl.load(in_ptr22 + r0, None)
tmp236 = tl.load(in_ptr23 + r0, None)
tmp1 = tl.full([1, 1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = r0
tmp4 = tl.full([1, 1], 1, tl.int64)
tmp5 = tmp3 >= tmp4
tmp8 = tl.load(in_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp9 = tmp7 - tmp8
tmp10 = tl.load(in_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp11 = tmp7 + tmp10
tmp12 = tmp9 / tmp11
tmp13 = 1.0
tmp14 = tmp13 - tmp12
tmp15 = tl.load(in_ptr1 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp16 = tmp7 - tmp15
tmp17 = tl.load(in_ptr2 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp18 = tmp7 + tmp17
tmp19 = tmp16 / tmp18
tmp20 = tmp13 - tmp19
tmp21 = tmp14 - tmp20
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp5, tmp21, tmp22)
tmp25 = tmp7 - tmp24
tmp27 = tmp7 + tmp26
tmp28 = tmp25 / tmp27
tmp29 = tmp13 - tmp28
tmp30 = tl.where(tmp5, tmp23, tmp29)
tmp31 = tmp2 * tmp30
tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
tmp34 = tl.sum(tmp32, 1)[:, None]
tmp36 = triton_helpers.maximum(tmp1, tmp35)
tmp39 = tl.load(in_ptr4 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp40 = tmp38 - tmp39
tmp41 = tl.load(in_ptr5 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp42 = tmp38 + tmp41
tmp43 = tmp40 / tmp42
tmp44 = tmp13 - tmp43
tmp45 = tl.load(in_ptr4 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp46 = tmp38 - tmp45
tmp47 = tl.load(in_ptr5 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp48 = tmp38 + tmp47
tmp49 = tmp46 / tmp48
tmp50 = tmp13 - tmp49
tmp51 = tmp44 - tmp50
tmp52 = tl.full(tmp51.shape, 0.0, tmp51.dtype)
tmp53 = tl.where(tmp5, tmp51, tmp52)
tmp55 = tmp38 - tmp54
tmp57 = tmp38 + tmp56
tmp58 = tmp55 / tmp57
tmp59 = tmp13 - tmp58
tmp60 = tl.where(tmp5, tmp53, tmp59)
tmp61 = tmp36 * tmp60
tmp62 = tl.broadcast_to(tmp61, [XBLOCK, RBLOCK])
tmp64 = tl.sum(tmp62, 1)[:, None]
tmp66 = triton_helpers.maximum(tmp1, tmp65)
tmp69 = tl.load(in_ptr7 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp70 = tmp68 - tmp69
tmp71 = tl.load(in_ptr8 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp72 = tmp68 + tmp71
tmp73 = tmp70 / tmp72
tmp74 = tmp13 - tmp73
tmp75 = tl.load(in_ptr7 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp76 = tmp68 - tmp75
tmp77 = tl.load(in_ptr8 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp78 = tmp68 + tmp77
tmp79 = tmp76 / tmp78
tmp80 = tmp13 - tmp79
tmp81 = tmp74 - tmp80
tmp82 = tl.full(tmp81.shape, 0.0, tmp81.dtype)
tmp83 = tl.where(tmp5, tmp81, tmp82)
tmp85 = tmp68 - tmp84
tmp87 = tmp68 + tmp86
tmp88 = tmp85 / tmp87
tmp89 = tmp13 - tmp88
tmp90 = tl.where(tmp5, tmp83, tmp89)
tmp91 = tmp66 * tmp90
tmp92 = tl.broadcast_to(tmp91, [XBLOCK, RBLOCK])
tmp94 = tl.sum(tmp92, 1)[:, None]
tmp96 = triton_helpers.maximum(tmp1, tmp95)
tmp99 = tl.load(in_ptr10 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp100 = tmp98 - tmp99
tmp101 = tl.load(in_ptr11 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp102 = tmp98 + tmp101
tmp103 = tmp100 / tmp102
tmp104 = tmp13 - tmp103
tmp105 = tl.load(in_ptr10 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp106 = tmp98 - tmp105
tmp107 = tl.load(in_ptr11 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp108 = tmp98 + tmp107
tmp109 = tmp106 / tmp108
tmp110 = tmp13 - tmp109
tmp111 = tmp104 - tmp110
tmp112 = tl.full(tmp111.shape, 0.0, tmp111.dtype)
tmp113 = tl.where(tmp5, tmp111, tmp112)
tmp115 = tmp98 - tmp114
tmp117 = tmp98 + tmp116
tmp118 = tmp115 / tmp117
tmp119 = tmp13 - tmp118
tmp120 = tl.where(tmp5, tmp113, tmp119)
tmp121 = tmp96 * tmp120
tmp122 = tl.broadcast_to(tmp121, [XBLOCK, RBLOCK])
tmp124 = tl.sum(tmp122, 1)[:, None]
tmp126 = triton_helpers.maximum(tmp1, tmp125)
tmp129 = tl.load(in_ptr13 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp130 = tmp128 - tmp129
tmp131 = tl.load(in_ptr14 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp132 = tmp128 + tmp131
tmp133 = tmp130 / tmp132
tmp134 = tmp13 - tmp133
tmp135 = tl.load(in_ptr13 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp136 = tmp128 - tmp135
tmp137 = tl.load(in_ptr14 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp138 = tmp128 + tmp137
tmp139 = tmp136 / tmp138
tmp140 = tmp13 - tmp139
tmp141 = tmp134 - tmp140
tmp142 = tl.full(tmp141.shape, 0.0, tmp141.dtype)
tmp143 = tl.where(tmp5, tmp141, tmp142)
tmp145 = tmp128 - tmp144
tmp147 = tmp128 + tmp146
tmp148 = tmp145 / tmp147
tmp149 = tmp13 - tmp148
tmp150 = tl.where(tmp5, tmp143, tmp149)
tmp151 = tmp126 * tmp150
tmp152 = tl.broadcast_to(tmp151, [XBLOCK, RBLOCK])
tmp154 = tl.sum(tmp152, 1)[:, None]
tmp156 = triton_helpers.maximum(tmp1, tmp155)
tmp159 = tl.load(in_ptr16 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp160 = tmp158 - tmp159
tmp161 = tl.load(in_ptr17 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp162 = tmp158 + tmp161
tmp163 = tmp160 / tmp162
tmp164 = tmp13 - tmp163
tmp165 = tl.load(in_ptr16 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp166 = tmp158 - tmp165
tmp167 = tl.load(in_ptr17 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp168 = tmp158 + tmp167
tmp169 = tmp166 / tmp168
tmp170 = tmp13 - tmp169
tmp171 = tmp164 - tmp170
tmp172 = tl.full(tmp171.shape, 0.0, tmp171.dtype)
tmp173 = tl.where(tmp5, tmp171, tmp172)
tmp175 = tmp158 - tmp174
tmp177 = tmp158 + tmp176
tmp178 = tmp175 / tmp177
tmp179 = tmp13 - tmp178
tmp180 = tl.where(tmp5, tmp173, tmp179)
tmp181 = tmp156 * tmp180
tmp182 = tl.broadcast_to(tmp181, [XBLOCK, RBLOCK])
tmp184 = tl.sum(tmp182, 1)[:, None]
tmp186 = triton_helpers.maximum(tmp1, tmp185)
tmp189 = tl.load(in_ptr19 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp190 = tmp188 - tmp189
tmp191 = tl.load(in_ptr20 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp192 = tmp188 + tmp191
tmp193 = tmp190 / tmp192
tmp194 = tmp13 - tmp193
tmp195 = tl.load(in_ptr19 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp196 = tmp188 - tmp195
tmp197 = tl.load(in_ptr20 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp198 = tmp188 + tmp197
tmp199 = tmp196 / tmp198
tmp200 = tmp13 - tmp199
tmp201 = tmp194 - tmp200
tmp202 = tl.full(tmp201.shape, 0.0, tmp201.dtype)
tmp203 = tl.where(tmp5, tmp201, tmp202)
tmp205 = tmp188 - tmp204
tmp207 = tmp188 + tmp206
tmp208 = tmp205 / tmp207
tmp209 = tmp13 - tmp208
tmp210 = tl.where(tmp5, tmp203, tmp209)
tmp211 = tmp186 * tmp210
tmp212 = tl.broadcast_to(tmp211, [XBLOCK, RBLOCK])
tmp214 = tl.sum(tmp212, 1)[:, None]
tmp216 = triton_helpers.maximum(tmp1, tmp215)
tmp219 = tl.load(in_ptr22 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp220 = tmp218 - tmp219
tmp221 = tl.load(in_ptr23 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5,
other=0.0)
tmp222 = tmp218 + tmp221
tmp223 = tmp220 / tmp222
tmp224 = tmp13 - tmp223
tmp225 = tl.load(in_ptr22 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp226 = tmp218 - tmp225
tmp227 = tl.load(in_ptr23 + tl.broadcast_to(-1 + r0, [XBLOCK, RBLOCK]),
tmp5, other=0.0)
tmp228 = tmp218 + tmp227
tmp229 = tmp226 / tmp228
tmp230 = tmp13 - tmp229
tmp231 = tmp224 - tmp230
tmp232 = tl.full(tmp231.shape, 0.0, tmp231.dtype)
tmp233 = tl.where(tmp5, tmp231, tmp232)
tmp235 = tmp218 - tmp234
tmp237 = tmp218 + tmp236
tmp238 = tmp235 / tmp237
tmp239 = tmp13 - tmp238
tmp240 = tl.where(tmp5, tmp233, tmp239)
tmp241 = tmp216 * tmp240
tmp242 = tl.broadcast_to(tmp241, [XBLOCK, RBLOCK])
tmp244 = tl.sum(tmp242, 1)[:, None]
tmp245 = tmp34 + tmp64
tmp246 = tmp245 + tmp94
tmp247 = tmp246 + tmp124
tmp248 = 0.25
tmp249 = tmp247 * tmp248
tmp250 = tmp154 + tmp184
tmp251 = tmp250 + tmp214
tmp252 = tmp251 + tmp244
tmp253 = tmp252 * tmp248
tmp254 = tmp249 + tmp253
tmp255 = 0.5
tmp256 = tmp254 * tmp255
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp256, 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((64,), (1,), torch.float32)
buf20 = empty_strided_cuda((64,), (1,), torch.float32)
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = empty_strided_cuda((64,), (1,), torch.float32)
buf4 = empty_strided_cuda((64,), (1,), torch.float32)
buf22 = empty_strided_cuda((), (), torch.float32)
buf23 = empty_strided_cuda((64,), (1,), torch.float32)
buf24 = empty_strided_cuda((64,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_0[grid(1)](arg0_1,
arg1_1, buf0, buf20, buf2, buf3, buf4, buf22, buf23, buf24, 1,
64, XBLOCK=1, num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((64,), (1,), torch.float32)
buf25 = empty_strided_cuda((64,), (1,), torch.float32)
buf7 = empty_strided_cuda((), (), torch.float32)
buf8 = empty_strided_cuda((64,), (1,), torch.float32)
buf9 = empty_strided_cuda((64,), (1,), torch.float32)
buf27 = empty_strided_cuda((), (), torch.float32)
buf28 = empty_strided_cuda((64,), (1,), torch.float32)
buf29 = empty_strided_cuda((64,), (1,), torch.float32)
triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_1[grid(1)](arg0_1,
arg1_1, buf5, buf25, buf7, buf8, buf9, buf27, buf28, buf29, 1,
64, XBLOCK=1, num_warps=2, num_stages=1)
buf10 = empty_strided_cuda((64,), (1,), torch.float32)
buf30 = empty_strided_cuda((64,), (1,), torch.float32)
buf12 = empty_strided_cuda((), (), torch.float32)
buf13 = empty_strided_cuda((64,), (1,), torch.float32)
buf14 = empty_strided_cuda((64,), (1,), torch.float32)
buf32 = empty_strided_cuda((), (), torch.float32)
buf33 = empty_strided_cuda((64,), (1,), torch.float32)
buf34 = empty_strided_cuda((64,), (1,), torch.float32)
triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_2[grid(1)](arg0_1,
arg1_1, buf10, buf30, buf12, buf13, buf14, buf32, buf33, buf34,
1, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf15 = empty_strided_cuda((64,), (1,), torch.float32)
buf35 = empty_strided_cuda((64,), (1,), torch.float32)
buf17 = empty_strided_cuda((), (), torch.float32)
buf18 = empty_strided_cuda((64,), (1,), torch.float32)
buf19 = empty_strided_cuda((64,), (1,), torch.float32)
buf37 = empty_strided_cuda((), (), torch.float32)
buf38 = empty_strided_cuda((64,), (1,), torch.float32)
buf39 = empty_strided_cuda((64,), (1,), torch.float32)
triton_per_fused_cumsum_index_mul_rsub_sort_sub_sum_3[grid(1)](arg0_1,
arg1_1, buf15, buf35, buf17, buf18, buf19, buf37, buf38, buf39,
1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf40 = buf2
del buf2
buf41 = buf7
del buf7
buf42 = buf12
del buf12
buf43 = buf17
del buf17
buf44 = buf22
del buf22
buf45 = buf27
del buf27
buf46 = buf32
del buf32
buf47 = buf37
del buf37
buf48 = buf40
del buf40
triton_per_fused_add_div_dot_relu_rsub_sub_4[grid(1)](buf48, buf41,
buf42, buf43, buf44, buf45, buf46, buf47, buf0, buf3, buf4,
buf5, buf8, buf9, buf10, buf13, buf14, buf15, buf18, buf19,
buf20, buf23, buf24, buf25, buf28, buf29, buf30, buf33, buf34,
buf35, buf38, buf39, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf10
del buf13
del buf14
del buf15
del buf18
del buf19
del buf20
del buf23
del buf24
del buf25
del buf28
del buf29
del buf3
del buf30
del buf33
del buf34
del buf35
del buf38
del buf39
del buf4
del buf41
del buf42
del buf43
del buf44
del buf45
del buf46
del buf47
del buf5
del buf8
del buf9
return buf48,
def jaccard(outputs, targets, per_image=False, non_empty=False, min_pixels=5):
batch_size = outputs.size()[0]
eps = 0.001
if not per_image:
batch_size = 1
dice_target = targets.contiguous().view(batch_size, -1).float()
dice_output = outputs.contiguous().view(batch_size, -1)
target_sum = torch.sum(dice_target, dim=1)
intersection = torch.sum(dice_output * dice_target, dim=1)
losses = 1.0 - (intersection + eps) / (torch.sum(dice_output +
dice_target, dim=1) - intersection + eps)
if non_empty:
assert per_image
non_empty_images = 0
sum_loss = 0
for i in range(batch_size):
if target_sum[i] > min_pixels:
sum_loss += losses[i]
non_empty_images += 1
if non_empty_images == 0:
return 0
else:
return sum_loss / non_empty_images
return losses.mean()
def flatten_binary_scores(scores, labels, ignore=None):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = labels != ignore
vscores = scores[valid]
vlabels = labels[valid]
return vscores, vlabels
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts.float() - gt_sorted.float().cumsum(0)
union = gts.float() + (1 - gt_sorted).float().cumsum(0)
jaccard = 1.0 - intersection / union
if p > 1:
jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
return jaccard
def lovasz_hinge_flat(logits, labels):
if len(labels) == 0:
return logits.sum() * 0.0
signs = 2.0 * labels.float() - 1.0
errors = 1.0 - logits * signs
errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_sorted)
loss = torch.dot(F.relu(errors_sorted), grad)
return loss
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
ll = iter(l)
if ignore_nan:
ll = filterfalse(np.isnan, ll)
try:
n = 1
acc = next(ll)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for n, v in enumerate(ll, 2):
acc += v
if n == 1:
return acc
return acc / n
def lovasz_hinge(logits, labels, per_image=True, ignore=None):
if per_image:
loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(
0), lab.unsqueeze(0), ignore)) for log, lab in zip(logits, labels))
else:
loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)
)
return loss
def symmetric_lovasz(outputs, targets):
return (lovasz_hinge(outputs, targets) + lovasz_hinge(-outputs, 1 -
targets)) / 2
class LovaszLossNew(nn.Module):
def __init__(self, ignore_index=255, per_image=True):
super().__init__()
self.ignore_index = ignore_index
self.per_image = per_image
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
kevinkwshin/kaggle-pneumothorax
|
LovaszLoss
| false
| 16,124
|
[
"MIT"
] | 74
|
24b91a9425097023f0cc7781a9380cb247babe22
|
https://github.com/kevinkwshin/kaggle-pneumothorax/tree/24b91a9425097023f0cc7781a9380cb247babe22
|
RZTXDecoderLayer
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class RZTXDecoderLayer(nn.Module):
"""RZTXDecoderLayer is made up of self-attn and feedforward network with
residual weights for faster convergece.
This encoder layer is based on the paper "ReZero is All You Need:
Fast Convergence at Large Depth".
Thomas Bachlechner∗, Bodhisattwa Prasad Majumder∗, Huanru Henry Mao∗,
Garrison W. Cottrell, Julian McAuley. 2020.
Args:
d_model: the number of expected features in the input (required).
nhead: the number of heads in the multiheadattention models (required).
dim_feedforward: the dimension of the feedforward network model (default=2048).
dropout: the dropout value (default=0.1).
activation: the activation function of intermediate layer, relu or gelu (default=relu).
use_res_init: Use residual initialization
Examples::
>>> decoder_layer = RZTXDecoderLayer(d_model=512, nhead=8)
>>> src = torch.rand(10, 32, 512)
>>> out = decoder_layer(src)
"""
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu'):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout
=dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.resweight = nn.Parameter(torch.Tensor([0]))
if activation == 'relu':
self.activation = F.relu
elif activation == 'gelu':
self.activation = F.gelu
def forward(self, tgt, memory, tgt_mask=None, memory_mask=None,
tgt_key_padding_mask=None, memory_key_padding_mask=None):
"""Pass the inputs (and mask) through the decoder layer.
Args:
tgt: the sequence to the decoder layer (required).
memory: the sequnce from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the mask for the memory sequence (optional).
tgt_key_padding_mask: the mask for the tgt keys per batch (optional).
memory_key_padding_mask: the mask for the memory keys per batch (optional).
Shape:
see the docs in PyTroch Transformer class.
"""
tgt2 = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout1(tgt2) * self.resweight
tgt2 = self.multihead_attn(tgt, memory, memory, attn_mask=
memory_mask, key_padding_mask=memory_key_padding_mask)[0]
tgt = tgt + self.dropout2(tgt2) * self.resweight
if hasattr(self, 'activation'):
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(
tgt))))
else:
tgt2 = self.linear2(self.dropout(F.relu(self.linear1(tgt))))
tgt = tgt + self.dropout3(tgt2) * self.resweight
return tgt
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'nhead': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mul_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 * tmp3
tmp5 = tmp0 + tmp4
tl.store(out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_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 % 2048
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (12, 4), (4, 1))
assert_size_stride(primals_3, (12,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (12, 4), (4, 1))
assert_size_stride(primals_9, (12,), (1,))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (2048, 4), (4, 1))
assert_size_stride(primals_13, (2048,), (1,))
assert_size_stride(primals_14, (4, 2048), (2048, 1))
assert_size_stride(primals_15, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4),
(1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 4),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 16),
alpha=1, beta=1, out=buf1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 8),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf2)
del primals_2
buf3 = reinterpret_tensor(buf0, (4, 4, 1), (1, 4, 16), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](buf3, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf1, (4, 1, 4), (1, 1,
4), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 1), (1, 4,
1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_5, reinterpret_tensor(buf8, (4, 4), (4,
1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf9)
del primals_5
buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_4[grid(16)](primals_1, buf9, primals_6,
buf10, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf10, reinterpret_tensor(primals_8, (4, 4), (1,
4), 0), out=buf11)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_9, (4,), (1,), 4),
primals_7, reinterpret_tensor(primals_8, (4, 4), (1, 4), 16),
alpha=1, beta=1, out=buf12)
buf13 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_9, (4,), (1,), 8),
primals_7, reinterpret_tensor(primals_8, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf13)
buf14 = reinterpret_tensor(buf11, (4, 4, 1), (1, 4, 16), 0)
del buf11
triton_poi_fused_mul_0[grid(16)](buf14, primals_9, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_9
buf15 = buf5
del buf5
extern_kernels.bmm(buf14, reinterpret_tensor(buf12, (4, 1, 4), (1,
1, 4), 0), out=buf15)
buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf15, buf16, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf17 = buf15
del buf15
triton_poi_fused__softmax_2[grid(64)](buf16, buf17, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf16
buf18 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf17, reinterpret_tensor(buf13, (4, 4, 1), (1,
4, 1), 0), out=buf18)
buf19 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf18, buf19, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf20 = reinterpret_tensor(buf18, (4, 4), (4, 1), 0)
del buf18
extern_kernels.addmm(primals_11, reinterpret_tensor(buf19, (4, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf20)
del primals_11
buf21 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_4[grid(16)](buf10, buf20, primals_6, buf21,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf22 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32)
extern_kernels.mm(buf21, reinterpret_tensor(primals_12, (4, 2048),
(1, 4), 0), out=buf22)
buf23 = buf22
del buf22
triton_poi_fused_relu_5[grid(8192)](buf23, primals_13, 8192, XBLOCK
=128, num_warps=4, num_stages=1)
del primals_13
buf24 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_15, buf23, reinterpret_tensor(
primals_14, (2048, 4), (1, 2048), 0), alpha=1, beta=1, out=buf24)
del primals_15
buf25 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_4[grid(16)](buf21, buf24, primals_6, buf25,
16, XBLOCK=16, num_warps=1, num_stages=1)
return (buf25, primals_6, primals_1, buf6, reinterpret_tensor(buf8, (4,
4), (4, 1), 0), buf9, buf10, primals_7, buf17, reinterpret_tensor(
buf19, (4, 4), (4, 1), 0), buf20, buf21, buf23, buf24, primals_14,
primals_12, primals_10, reinterpret_tensor(buf13, (4, 1, 4), (1, 1,
4), 0), reinterpret_tensor(buf14, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf12, (4, 4, 1), (1, 4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (4, 1), 0), primals_4,
reinterpret_tensor(buf2, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf3, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf1, (4, 4, 1), (1, 4, 1), 0))
class RZTXDecoderLayerNew(nn.Module):
"""RZTXDecoderLayer is made up of self-attn and feedforward network with
residual weights for faster convergece.
This encoder layer is based on the paper "ReZero is All You Need:
Fast Convergence at Large Depth".
Thomas Bachlechner∗, Bodhisattwa Prasad Majumder∗, Huanru Henry Mao∗,
Garrison W. Cottrell, Julian McAuley. 2020.
Args:
d_model: the number of expected features in the input (required).
nhead: the number of heads in the multiheadattention models (required).
dim_feedforward: the dimension of the feedforward network model (default=2048).
dropout: the dropout value (default=0.1).
activation: the activation function of intermediate layer, relu or gelu (default=relu).
use_res_init: Use residual initialization
Examples::
>>> decoder_layer = RZTXDecoderLayer(d_model=512, nhead=8)
>>> src = torch.rand(10, 32, 512)
>>> out = decoder_layer(src)
"""
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu'):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout
=dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.resweight = nn.Parameter(torch.Tensor([0]))
if activation == 'relu':
self.activation = F.relu
elif activation == 'gelu':
self.activation = F.gelu
def forward(self, input_0, input_1):
primals_6 = self.resweight
primals_2 = self.self_attn.in_proj_weight
primals_3 = self.self_attn.in_proj_bias
primals_1 = self.self_attn.out_proj.weight
primals_5 = self.self_attn.out_proj.bias
primals_8 = self.multihead_attn.in_proj_weight
primals_9 = self.multihead_attn.in_proj_bias
primals_4 = self.multihead_attn.out_proj.weight
primals_11 = self.multihead_attn.out_proj.bias
primals_12 = self.linear1.weight
primals_13 = self.linear1.bias
primals_14 = self.linear2.weight
primals_15 = self.linear2.bias
primals_7 = input_0
primals_10 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15])
return output[0]
|
mpariente/rezero
|
RZTXDecoderLayer
| false
| 16,125
|
[
"MIT"
] | 376
|
6bcf1df00bc9a3560b093a2bbe12dade92f86eba
|
https://github.com/mpariente/rezero/tree/6bcf1df00bc9a3560b093a2bbe12dade92f86eba
|
LearnableClsToken
|
import torch
import torch as th
from torch import nn
class LearnableClsToken(nn.Module):
"""
Layer that adds learnable CLS tokens to sequence input.
"""
def __init__(self, d_model: 'int'):
super().__init__()
cls_token = th.zeros(d_model)
self.cls_param = nn.Parameter(cls_token, requires_grad=True)
self.fixed_ones = nn.Parameter(th.ones(1), requires_grad=False)
def forward(self, features, mask, lengths):
"""
CLS Token forward.
"""
batch, _seq_len, _d_model = features.shape
features = th.cat([self.cls_param.unsqueeze(0).unsqueeze(0).repeat(
batch, 1, 1), features], dim=1)
assert th.all(features[0, 0, :] == self.cls_param)
zeros = (self.fixed_ones.unsqueeze(0).repeat(batch, 1) * 0).bool()
mask = th.cat([zeros, mask], dim=1)
lengths = lengths + 1
return features, mask, lengths
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4]), torch.rand([4, 4, 4, 4])
]
def get_init_inputs():
return [[], {'d_model': 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 as th
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 5
x0 = xindex % 4
x2 = xindex // 20
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 5, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 4 * (-1 + x1) + 16 * x2), tmp6 & xmask,
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 20
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp5 = tl.load(in_ptr0 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp7 = 0.0
tmp8 = tmp6 * tmp7
tmp9 = tmp8 != 0
tmp10 = tmp9.to(tl.float32)
tmp11 = tl.full(tmp10.shape, 0.0, tmp10.dtype)
tmp12 = tl.where(tmp4, tmp10, tmp11)
tmp13 = tmp0 >= tmp3
tl.full([1], 5, tl.int64)
tmp16 = tl.load(in_ptr1 + (4 * x1 + (-1 + x0)), tmp13 & xmask,
eviction_policy='evict_last', other=0.0)
tmp17 = tl.where(tmp4, tmp12, tmp16)
tl.store(out_ptr0 + x2, tmp17, xmask)
@triton.jit
def triton_poi_fused_add_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 5, 4), (20, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(80)](primals_2, primals_1, buf0, 80,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 5), (5, 1), torch.float32)
triton_poi_fused_cat_1[grid(20)](primals_3, primals_4, buf1, 20,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_3
del primals_4
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_2[grid(256)](primals_5, buf2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_5
return buf0, buf1, buf2
class LearnableClsTokenNew(nn.Module):
"""
Layer that adds learnable CLS tokens to sequence input.
"""
def __init__(self, d_model: 'int'):
super().__init__()
cls_token = th.zeros(d_model)
self.cls_param = nn.Parameter(cls_token, requires_grad=True)
self.fixed_ones = nn.Parameter(th.ones(1), requires_grad=False)
def forward(self, input_0, input_1, input_2):
primals_2 = self.cls_param
primals_3 = self.fixed_ones
primals_1 = input_0
primals_4 = input_1
primals_5 = input_2
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1], output[2]
|
mzolfaghari/coot-videotext
|
LearnableClsToken
| false
| 16,126
|
[
"Apache-2.0"
] | 213
|
ee09c56c2600f56581167773d7f7dc5d036cc5e6
|
https://github.com/mzolfaghari/coot-videotext/tree/ee09c56c2600f56581167773d7f7dc5d036cc5e6
|
RZTXEncoderLayer
|
from torch.nn import Module
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.module import Module
from torch.nn.modules.activation import MultiheadAttention
from torch.nn.modules.dropout import Dropout
from torch.nn.modules.linear import Linear
class RZTXEncoderLayer(Module):
"""RZTXEncoderLayer is made up of self-attn and feedforward network with
residual weights for faster convergece.
This encoder layer is based on the paper "ReZero is All You Need:
Fast Convergence at Large Depth".
Thomas Bachlechner∗, Bodhisattwa Prasad Majumder∗, Huanru Henry Mao∗,
Garrison W. Cottrell, Julian McAuley. 2020.
Args:
d_model: the number of expected features in the input (required).
nhead: the number of heads in the multiheadattention models (required).
dim_feedforward: the dimension of the feedforward network model (default=2048).
dropout: the dropout value (default=0.1).
activation: the activation function of intermediate layer, relu or gelu (default=relu).
use_res_init: Use residual initialization
Examples::
>>> encoder_layer = RZTXEncoderLayer(d_model=512, nhead=8)
>>> src = torch.rand(10, 32, 512)
>>> out = encoder_layer(src)
"""
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu'):
super().__init__()
self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = Linear(d_model, dim_feedforward)
self.dropout = Dropout(dropout)
self.linear2 = Linear(dim_feedforward, d_model)
self.dropout1 = Dropout(dropout)
self.dropout2 = Dropout(dropout)
self.resweight = nn.Parameter(torch.Tensor([0]))
if activation == 'relu':
self.activation = F.relu
elif activation == 'gelu':
self.activation = F.gelu
def __setstate__(self, state):
if 'activation' not in state:
state['activation'] = F.relu
super().__setstate__(state)
def forward(self, src, src_mask=None, src_key_padding_mask=None):
"""Pass the input through the encoder layer.
Args:
src: the sequence to the encoder layer (required).
src_mask: the mask for the src sequence (optional).
src_key_padding_mask: the mask for the src keys per batch (optional).
Shape:
see the docs in PyTroch Transformer class.
"""
src2 = src
src2 = self.self_attn(src2, src2, src2, attn_mask=src_mask,
key_padding_mask=src_key_padding_mask)
src2 = src2[0]
src2 = src2 * self.resweight
src = src + self.dropout1(src2)
src2 = src
src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
src2 = src2 * self.resweight
src = src + self.dropout2(src2)
return src
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'nhead': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.module import Module
from torch.nn.modules.activation import MultiheadAttention
from torch.nn.modules.dropout import Dropout
from torch.nn.modules.linear import Linear
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mul_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp4 = tmp1 * tmp3
tmp5 = tmp0 + tmp4
tl.store(out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_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 % 2048
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
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, (12, 4), (4, 1))
assert_size_stride(primals_3, (12,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1,), (1,))
assert_size_stride(primals_7, (2048, 4), (4, 1))
assert_size_stride(primals_8, (2048,), (1,))
assert_size_stride(primals_9, (4, 2048), (2048, 1))
assert_size_stride(primals_10, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4),
(1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 4),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 16),
alpha=1, beta=1, out=buf1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 8),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf2)
del primals_2
buf3 = reinterpret_tensor(buf0, (4, 4, 1), (1, 4, 16), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](buf3, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf1, (4, 1, 4), (1, 1,
4), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf5
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 1), (1, 4,
1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_5, reinterpret_tensor(buf8, (4, 4), (4,
1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf9)
del primals_5
buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_4[grid(16)](primals_1, buf9, primals_6,
buf10, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32)
extern_kernels.mm(buf10, reinterpret_tensor(primals_7, (4, 2048), (
1, 4), 0), out=buf11)
buf12 = buf11
del buf11
triton_poi_fused_relu_5[grid(8192)](buf12, primals_8, 8192, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_8
buf13 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_10, buf12, reinterpret_tensor(
primals_9, (2048, 4), (1, 2048), 0), alpha=1, beta=1, out=buf13)
del primals_10
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_4[grid(16)](buf10, buf13, primals_6, buf14,
16, XBLOCK=16, num_warps=1, num_stages=1)
return (buf14, primals_6, primals_1, buf6, reinterpret_tensor(buf8, (4,
4), (4, 1), 0), buf9, buf10, buf12, buf13, primals_9, primals_7,
primals_4, reinterpret_tensor(buf2, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf3, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf1, (4, 4, 1), (1, 4, 1), 0))
class RZTXEncoderLayerNew(Module):
"""RZTXEncoderLayer is made up of self-attn and feedforward network with
residual weights for faster convergece.
This encoder layer is based on the paper "ReZero is All You Need:
Fast Convergence at Large Depth".
Thomas Bachlechner∗, Bodhisattwa Prasad Majumder∗, Huanru Henry Mao∗,
Garrison W. Cottrell, Julian McAuley. 2020.
Args:
d_model: the number of expected features in the input (required).
nhead: the number of heads in the multiheadattention models (required).
dim_feedforward: the dimension of the feedforward network model (default=2048).
dropout: the dropout value (default=0.1).
activation: the activation function of intermediate layer, relu or gelu (default=relu).
use_res_init: Use residual initialization
Examples::
>>> encoder_layer = RZTXEncoderLayer(d_model=512, nhead=8)
>>> src = torch.rand(10, 32, 512)
>>> out = encoder_layer(src)
"""
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu'):
super().__init__()
self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = Linear(d_model, dim_feedforward)
self.dropout = Dropout(dropout)
self.linear2 = Linear(dim_feedforward, d_model)
self.dropout1 = Dropout(dropout)
self.dropout2 = Dropout(dropout)
self.resweight = nn.Parameter(torch.Tensor([0]))
if activation == 'relu':
self.activation = F.relu
elif activation == 'gelu':
self.activation = F.gelu
def __setstate__(self, state):
if 'activation' not in state:
state['activation'] = F.relu
super().__setstate__(state)
def forward(self, input_0):
primals_6 = self.resweight
primals_2 = self.self_attn.in_proj_weight
primals_3 = self.self_attn.in_proj_bias
primals_1 = self.self_attn.out_proj.weight
primals_5 = self.self_attn.out_proj.bias
primals_7 = self.linear1.weight
primals_8 = self.linear1.bias
primals_9 = self.linear2.weight
primals_10 = self.linear2.bias
primals_4 = input_0
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]
|
mpariente/rezero
|
RZTXEncoderLayer
| false
| 16,127
|
[
"MIT"
] | 376
|
6bcf1df00bc9a3560b093a2bbe12dade92f86eba
|
https://github.com/mpariente/rezero/tree/6bcf1df00bc9a3560b093a2bbe12dade92f86eba
|
AddCoords
|
import torch
import torch.nn as nn
class AddCoords(nn.Module):
"""
Add Coords to a tensor
"""
def __init__(self, with_r=False):
super(AddCoords, self).__init__()
self.with_r = with_r
def forward(self, x):
"""
:param x: shape (batch, channel, x_dim, y_dim)
:return: shape (batch, channel+2, x_dim, y_dim)
"""
B, _, x_dim, y_dim = x.size()
xx_channel = torch.arange(x_dim).repeat(B, 1, y_dim, 1).type_as(x)
yy_cahnnel = torch.arange(y_dim).repeat(B, 1, x_dim, 1).permute(0,
1, 3, 2).type_as(x)
xx_channel = xx_channel.float() / (x_dim - 1)
yy_cahnnel = yy_cahnnel.float() / (y_dim - 1)
xx_channel = xx_channel * 2 - 1
yy_cahnnel = yy_cahnnel * 2 - 1
ret = torch.cat([x, xx_channel, yy_cahnnel], dim=1)
if self.with_r:
rr = torch.sqrt(xx_channel ** 2 + yy_cahnnel ** 2)
ret = torch.cat([ret, rr], dim=1)
return ret
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_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16 % 6
x3 = xindex // 96
x4 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x4 + 16 * x2 + 64 * x3), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 5, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = x0
tmp11 = tmp10.to(tl.float32)
tmp12 = 0.3333333333333333
tmp13 = tmp11 * tmp12
tmp14 = 2.0
tmp15 = tmp13 * tmp14
tmp16 = 1.0
tmp17 = tmp15 - tmp16
tmp18 = tl.full(tmp17.shape, 0.0, tmp17.dtype)
tmp19 = tl.where(tmp9, tmp17, tmp18)
tmp20 = tmp0 >= tmp7
tl.full([1], 6, tl.int64)
tmp23 = x1
tmp24 = tmp23.to(tl.float32)
tmp25 = tmp24 * tmp12
tmp26 = tmp25 * tmp14
tmp27 = tmp26 - tmp16
tmp28 = tl.full(tmp27.shape, 0.0, tmp27.dtype)
tmp29 = tl.where(tmp20, tmp27, tmp28)
tmp30 = tl.where(tmp9, tmp19, tmp29)
tmp31 = tl.where(tmp4, tmp5, tmp30)
tl.store(out_ptr0 + x5, tmp31, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 6, 4, 4), (96, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(384)](arg0_1, buf0, 384, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class AddCoordsNew(nn.Module):
"""
Add Coords to a tensor
"""
def __init__(self, with_r=False):
super(AddCoordsNew, self).__init__()
self.with_r = with_r
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nandbhat/dressing-in-order
|
AddCoords
| false
| 16,128
|
[
"BSD-3-Clause"
] | 172
|
93ed967f588de9f3f80dcc40c51d5790569fbcab
|
https://github.com/nandbhat/dressing-in-order/tree/93ed967f588de9f3f80dcc40c51d5790569fbcab
|
CoordConv
|
import torch
import torch.nn as nn
from torch.nn.utils.spectral_norm import spectral_norm as SpectralNorm
def spectral_norm(module, use_spect=True):
"""use spectral normal layer to stable the training process"""
if use_spect:
return SpectralNorm(module)
else:
return module
class AddCoords(nn.Module):
"""
Add Coords to a tensor
"""
def __init__(self, with_r=False):
super(AddCoords, self).__init__()
self.with_r = with_r
def forward(self, x):
"""
:param x: shape (batch, channel, x_dim, y_dim)
:return: shape (batch, channel+2, x_dim, y_dim)
"""
B, _, x_dim, y_dim = x.size()
xx_channel = torch.arange(x_dim).repeat(B, 1, y_dim, 1).type_as(x)
yy_cahnnel = torch.arange(y_dim).repeat(B, 1, x_dim, 1).permute(0,
1, 3, 2).type_as(x)
xx_channel = xx_channel.float() / (x_dim - 1)
yy_cahnnel = yy_cahnnel.float() / (y_dim - 1)
xx_channel = xx_channel * 2 - 1
yy_cahnnel = yy_cahnnel * 2 - 1
ret = torch.cat([x, xx_channel, yy_cahnnel], dim=1)
if self.with_r:
rr = torch.sqrt(xx_channel ** 2 + yy_cahnnel ** 2)
ret = torch.cat([ret, rr], dim=1)
return ret
class CoordConv(nn.Module):
"""
CoordConv operation
"""
def __init__(self, input_nc, output_nc, with_r=False, use_spect=False,
**kwargs):
super(CoordConv, self).__init__()
self.addcoords = AddCoords(with_r=with_r)
input_nc = input_nc + 2
if with_r:
input_nc = input_nc + 1
self.conv = spectral_norm(nn.Conv2d(input_nc, output_nc, **kwargs),
use_spect)
def forward(self, x):
ret = self.addcoords(x)
ret = self.conv(ret)
return ret
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_nc': 4, 'output_nc': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from torch.nn.utils.spectral_norm import spectral_norm as SpectralNorm
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 = 384
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16 % 6
x3 = xindex // 96
x4 = xindex % 16
x0 = xindex % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x4 + 16 * x2 + 64 * x3), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 5, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = x0
tmp11 = tmp10.to(tl.float32)
tmp12 = 0.3333333333333333
tmp13 = tmp11 * tmp12
tmp14 = 2.0
tmp15 = tmp13 * tmp14
tmp16 = 1.0
tmp17 = tmp15 - tmp16
tmp18 = tl.full(tmp17.shape, 0.0, tmp17.dtype)
tmp19 = tl.where(tmp9, tmp17, tmp18)
tmp20 = tmp0 >= tmp7
tl.full([1], 6, tl.int64)
tmp23 = x1
tmp24 = tmp23.to(tl.float32)
tmp25 = tmp24 * tmp12
tmp26 = tmp25 * tmp14
tmp27 = tmp26 - tmp16
tmp28 = tl.full(tmp27.shape, 0.0, tmp27.dtype)
tmp29 = tl.where(tmp20, tmp27, tmp28)
tmp30 = tl.where(tmp9, tmp19, tmp29)
tmp31 = tl.where(tmp4, tmp5, tmp30)
tl.store(out_ptr0 + x5, tmp31, 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, 6, 4, 4), (96, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 6, 4, 4), (96, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(384)](primals_1, buf0, 384, 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, 1, 1), (4, 1, 1, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(16)](buf2, primals_3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return buf2, primals_2, buf0
def spectral_norm(module, use_spect=True):
"""use spectral normal layer to stable the training process"""
if use_spect:
return SpectralNorm(module)
else:
return module
class AddCoords(nn.Module):
"""
Add Coords to a tensor
"""
def __init__(self, with_r=False):
super(AddCoords, self).__init__()
self.with_r = with_r
def forward(self, x):
"""
:param x: shape (batch, channel, x_dim, y_dim)
:return: shape (batch, channel+2, x_dim, y_dim)
"""
B, _, x_dim, y_dim = x.size()
xx_channel = torch.arange(x_dim).repeat(B, 1, y_dim, 1).type_as(x)
yy_cahnnel = torch.arange(y_dim).repeat(B, 1, x_dim, 1).permute(0,
1, 3, 2).type_as(x)
xx_channel = xx_channel.float() / (x_dim - 1)
yy_cahnnel = yy_cahnnel.float() / (y_dim - 1)
xx_channel = xx_channel * 2 - 1
yy_cahnnel = yy_cahnnel * 2 - 1
ret = torch.cat([x, xx_channel, yy_cahnnel], dim=1)
if self.with_r:
rr = torch.sqrt(xx_channel ** 2 + yy_cahnnel ** 2)
ret = torch.cat([ret, rr], dim=1)
return ret
class CoordConvNew(nn.Module):
"""
CoordConv operation
"""
def __init__(self, input_nc, output_nc, with_r=False, use_spect=False,
**kwargs):
super(CoordConvNew, self).__init__()
self.addcoords = AddCoords(with_r=with_r)
input_nc = input_nc + 2
if with_r:
input_nc = input_nc + 1
self.conv = spectral_norm(nn.Conv2d(input_nc, output_nc, **kwargs),
use_spect)
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]
|
nandbhat/dressing-in-order
|
CoordConv
| false
| 16,129
|
[
"BSD-3-Clause"
] | 172
|
93ed967f588de9f3f80dcc40c51d5790569fbcab
|
https://github.com/nandbhat/dressing-in-order/tree/93ed967f588de9f3f80dcc40c51d5790569fbcab
|
SLN
|
import torch
import torch.nn as nn
class SLN(nn.Module):
"""
Self-modulated LayerNorm
"""
def __init__(self, num_features):
super(SLN, self).__init__()
self.ln = nn.LayerNorm(num_features)
self.gamma = nn.Parameter(torch.randn(1, 1, 1))
self.beta = nn.Parameter(torch.randn(1, 1, 1))
def forward(self, hl, w):
return self.gamma * w * self.ln(hl) + self.beta * w
def get_inputs():
return [torch.rand([4, 4, 4, 4]), 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
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_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 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_add_mul_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, 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 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x2, xmask)
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr7 + 0)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp3 = tmp1 * tmp2
tmp6 = tmp4 - tmp5
tmp8 = tmp6 * tmp7
tmp10 = tmp8 * tmp9
tmp12 = tmp10 + tmp11
tmp13 = tmp3 * tmp12
tmp16 = tmp15 * tmp2
tmp17 = tmp13 + tmp16
tl.store(out_ptr0 + x2, tmp17, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 1), (1, 1, 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, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_6, (1, 1, 1), (1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(64)](primals_5, buf0,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_native_layer_norm_1[grid(256)](primals_1,
primals_2, primals_5, buf0, buf1, primals_3, primals_4,
primals_6, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del buf1
del primals_6
return buf2, primals_1, primals_2, primals_3, primals_4, primals_5
class SLNNew(nn.Module):
"""
Self-modulated LayerNorm
"""
def __init__(self, num_features):
super(SLNNew, self).__init__()
self.ln = nn.LayerNorm(num_features)
self.gamma = nn.Parameter(torch.randn(1, 1, 1))
self.beta = nn.Parameter(torch.randn(1, 1, 1))
def forward(self, input_0, input_1):
primals_1 = self.gamma
primals_6 = self.beta
primals_3 = self.ln.weight
primals_4 = self.ln.bias
primals_2 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
nandkishore1/TransformersInVision
|
SLN
| false
| 16,130
|
[
"MIT"
] | 94
|
134ef26b63916d2b9ae384124de7365a97102b06
|
https://github.com/nandkishore1/TransformersInVision/tree/134ef26b63916d2b9ae384124de7365a97102b06
|
ToLongTensor
|
import torch
from torch import Tensor
from typing import List
import torch.nn as nn
class ToLongTensor(nn.Module):
"""Convert a list of integers to long tensor
"""
def __init__(self):
super(ToLongTensor, self).__init__()
def forward(self, tokens: 'List[List[int]]') ->Tensor:
return torch.tensor(tokens)
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__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)
tl.store(out_ptr0 + x0, tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__to_copy_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ToLongTensorNew(nn.Module):
"""Convert a list of integers to long tensor
"""
def __init__(self):
super(ToLongTensorNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nateanl/text
|
ToLongTensor
| false
| 16,131
|
[
"BSD-3-Clause"
] | 3,172
|
b26e9350ad387a84aefe131443bbbf1c51a8a618
|
https://github.com/nateanl/text/tree/b26e9350ad387a84aefe131443bbbf1c51a8a618
|
BucketingEmbedding
|
import torch
import torch.nn as nn
class BucketingEmbedding(nn.Module):
def __init__(self, min_val, max_val, count, dim, use_log_scale=False):
super().__init__()
self.min_val = min_val
self.max_val = max_val
self.count = count
self.dim = dim
self.use_log_scale = use_log_scale
if self.use_log_scale:
self.min_val = torch.log2(torch.Tensor([self.min_val])).item()
self.max_val = torch.log2(torch.Tensor([self.max_val])).item()
self.main = nn.Embedding(count, dim)
def forward(self, x):
"""
x - (bs, ) values
"""
if self.use_log_scale:
x = torch.log2(x)
x = self.count * (x - self.min_val) / (self.max_val - self.min_val)
x = torch.clamp(x, 0, self.count - 1).long()
return self.main(x)
def get_class(self, x):
"""
x - (bs, ) values
"""
if self.use_log_scale:
x = torch.log2(x)
x = self.count * (x - self.min_val) / (self.max_val - self.min_val)
x = torch.clamp(x, 0, self.count - 1).long()
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'min_val': 4, 'max_val': 4, 'count': 4, '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
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__to_copy_clamp_div_mul_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 4.0
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp1
tmp4 = float('inf')
tmp5 = tmp3 * tmp4
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = 3.0
tmp9 = triton_helpers.minimum(tmp7, tmp8)
tmp10 = tmp9.to(tl.int64)
tl.store(out_ptr0 + x0, tmp10, xmask)
@triton.jit
def triton_poi_fused_embedding_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int64)
get_raw_stream(0)
triton_poi_fused__to_copy_clamp_div_mul_sub_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, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_embedding_1[grid(1024)](buf0, primals_2, buf1,
1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf1, buf0
class BucketingEmbeddingNew(nn.Module):
def __init__(self, min_val, max_val, count, dim, use_log_scale=False):
super().__init__()
self.min_val = min_val
self.max_val = max_val
self.count = count
self.dim = dim
self.use_log_scale = use_log_scale
if self.use_log_scale:
self.min_val = torch.log2(torch.Tensor([self.min_val])).item()
self.max_val = torch.log2(torch.Tensor([self.max_val])).item()
self.main = nn.Embedding(count, dim)
def get_class(self, x):
"""
x - (bs, ) values
"""
if self.use_log_scale:
x = torch.log2(x)
x = self.count * (x - self.min_val) / (self.max_val - self.min_val)
x = torch.clamp(x, 0, self.count - 1).long()
return x
def forward(self, input_0):
primals_2 = self.main.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
narekvslife/OccupancyAnticipation
|
BucketingEmbedding
| false
| 16,132
|
[
"MIT"
] | 53
|
19b9f4d72b114339d07bd225a1c3feed73e982c2
|
https://github.com/narekvslife/OccupancyAnticipation/tree/19b9f4d72b114339d07bd225a1c3feed73e982c2
|
conv_head_pooling
|
import torch
from torch import nn
class conv_head_pooling(nn.Module):
def __init__(self, in_feature, out_feature, stride, padding_mode='zeros'):
super(conv_head_pooling, self).__init__()
self.conv = nn.Conv2d(in_feature, out_feature, kernel_size=stride +
1, padding=stride // 2, stride=stride, padding_mode=
padding_mode, groups=in_feature)
def forward(self, x):
x = self.conv(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_feature': 4, 'out_feature': 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 import 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 = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 9 % 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, 1, 2, 2), (4, 4, 2, 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=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf0, (4, 4, 3, 3), (36, 9, 3, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(144)](buf1, primals_2, 144,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class conv_head_poolingNew(nn.Module):
def __init__(self, in_feature, out_feature, stride, padding_mode='zeros'):
super(conv_head_poolingNew, self).__init__()
self.conv = nn.Conv2d(in_feature, out_feature, kernel_size=stride +
1, padding=stride // 2, stride=stride, padding_mode=
padding_mode, groups=in_feature)
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]
|
naver-ai/PfLayer
|
conv_head_pooling
| false
| 16,133
|
[
"Apache-2.0"
] | 59
|
da8f80b2ea3b6bd7fbee3beee8b1516c89bc0441
|
https://github.com/naver-ai/PfLayer/tree/da8f80b2ea3b6bd7fbee3beee8b1516c89bc0441
|
Dec
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class Dec(nn.Module):
def __init__(self, opt):
super(Dec, self).__init__()
self.fc1 = nn.Linear(opt.resSize, opt.ngh)
self.fc2 = nn.Linear(opt.ngh, opt.ngh)
self.fc3 = nn.Linear(opt.ngh, opt.attSize)
self.lrelu = nn.LeakyReLU(0.2, True)
self.relu = nn.ReLU(True)
self.apply(weights_init)
def forward(self, feat):
h = self.lrelu(self.fc1(feat))
h = self.lrelu(self.fc2(h))
h = self.fc3(h)
return h
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'opt': _mock_config(resSize=4, ngh=4, attSize=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_leaky_relu_leaky_relu_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp8 = tmp7 > tmp3
tl.store(in_out_ptr0 + x4, tmp7, xmask)
tl.store(out_ptr0 + x4, tmp8, xmask)
@triton.jit
def triton_poi_fused_view_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * (x1 % 4 // 4) + 64 * ((4 *
(x1 // 4 % 4) + x1 % 4) // 16)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_leaky_relu_leaky_relu_backward_0[grid(256)](buf1,
primals_2, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
triton_poi_fused_view_1[grid(256)](buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (64, 4), (4, 1), 0)
del buf1
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_leaky_relu_leaky_relu_backward_0[grid(256)](buf4,
primals_5, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
triton_poi_fused_view_1[grid(256)](buf4, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (64, 4), (4, 1), 0)
del buf4
extern_kernels.addmm(primals_7, buf5, reinterpret_tensor(primals_6,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf6)
del primals_7
return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2, buf5, primals_6, buf7, primals_4, buf8
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class DecNew(nn.Module):
def __init__(self, opt):
super(DecNew, self).__init__()
self.fc1 = nn.Linear(opt.resSize, opt.ngh)
self.fc2 = nn.Linear(opt.ngh, opt.ngh)
self.fc3 = nn.Linear(opt.ngh, opt.attSize)
self.lrelu = nn.LeakyReLU(0.2, True)
self.relu = nn.ReLU(True)
self.apply(weights_init)
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]
|
naraysa/gzsl-od
|
Dec
| false
| 16,134
|
[
"MIT"
] | 50
|
be771e12e17a4c02386c70697c4b26e3170a7557
|
https://github.com/naraysa/gzsl-od/tree/be771e12e17a4c02386c70697c4b26e3170a7557
|
MultiheadAttention
|
import torch
from torch import nn
import torch.utils
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn import Parameter
class MultiheadAttention(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(self, embed_dim, num_heads, attn_dropout=0.0, bias=True,
add_bias_kv=False, add_zero_attn=False):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.attn_dropout = attn_dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
self.scaling = self.head_dim ** -0.5
self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim))
if bias:
self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.in_proj_weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
nn.init.xavier_normal_(self.bias_k)
if self.bias_v is not None:
nn.init.xavier_normal_(self.bias_v)
def forward(self, query, key, value, attn_mask=None):
"""Input shape: Time x Batch x Channel
Self-attention can be implemented by passing in the same arguments for
query, key and value. Timesteps can be masked by supplying a T x T mask in the
`attn_mask` argument. Padding elements can be excluded from
the key by passing a binary ByteTensor (`key_padding_mask`) with shape:
batch x src_len, where padding elements are indicated by 1s.
"""
qkv_same = query.data_ptr() == key.data_ptr() == value.data_ptr()
kv_same = key.data_ptr() == value.data_ptr()
tgt_len, bsz, embed_dim = query.size()
assert embed_dim == self.embed_dim
assert list(query.size()) == [tgt_len, bsz, embed_dim]
assert key.size() == value.size()
if qkv_same:
q, k, v = self.in_proj_qkv(query)
elif kv_same:
q = self.in_proj_q(query)
if key is None:
assert value is None
k = v = None
else:
k, v = self.in_proj_kv(key)
else:
q = self.in_proj_q(query)
k = self.in_proj_k(key)
v = self.in_proj_v(value)
q *= self.scaling
if self.bias_k is not None:
assert self.bias_v is not None
k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
if attn_mask is not None:
attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(
attn_mask.size(0), 1)], dim=1)
q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
if k is not None:
k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
if v is not None:
v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
src_len = k.size(1)
if self.add_zero_attn:
src_len += 1
k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])],
dim=1)
v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])],
dim=1)
if attn_mask is not None:
attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(
attn_mask.size(0), 1)], dim=1)
attn_weights = torch.bmm(q, k.transpose(1, 2))
assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len,
src_len]
if attn_mask is not None:
try:
attn_weights *= attn_mask.unsqueeze(0)
except:
None
None
assert False
attn_weights = (attn_weights - torch.min(attn_weights)) / (torch.
max(attn_weights) - torch.min(attn_weights))
attn_weights = F.dropout(attn_weights, p=self.attn_dropout,
training=self.training)
attn = torch.bmm(attn_weights, v)
assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.
head_dim]
attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
attn = self.out_proj(attn)
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights.sum(dim=1) / self.num_heads
return attn, attn_weights
def in_proj_qkv(self, query):
return self._in_proj(query).chunk(3, dim=-1)
def in_proj_kv(self, key):
return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
def in_proj_q(self, query):
return self._in_proj(query, end=self.embed_dim)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=0, end=None):
weight = self.in_proj_weight
bias = self.in_proj_bias
weight = weight[start:end, :]
if bias is not None:
bias = bias[start:end]
return F.linear(input, weight, bias)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4,
4, 4, 4])]
def get_init_inputs():
return [[], {'embed_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
from torch import nn
import torch.utils
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused_div_eq_isnan_logical_and_logical_or_max_min_sub_1(in_ptr0,
out_ptr2, out_ptr3, out_ptr4, out_ptr5, 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 + r0, None)
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = triton_helpers.promote_to_tensor(triton_helpers.min2(tmp1, 0))
tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp1, 0))
tmp6 = tmp5 - tmp3
tmp7 = tmp0 - tmp3
tmp8 = tmp7 / tmp6
tmp9 = tmp0 == tmp3
tmp10 = libdevice.isnan(tmp0).to(tl.int1)
tmp11 = libdevice.isnan(tmp3).to(tl.int1)
tmp12 = tmp10 & tmp11
tmp13 = tmp9 | tmp12
tmp14 = tmp0 == tmp5
tmp15 = libdevice.isnan(tmp5).to(tl.int1)
tmp16 = tmp10 & tmp15
tmp17 = tmp14 | tmp16
tl.store(out_ptr2 + tl.full([1], 0, tl.int32), tmp6, None)
tl.store(out_ptr3 + tl.broadcast_to(r0, [RBLOCK]), tmp8, None)
tl.store(out_ptr4 + tl.broadcast_to(r0, [RBLOCK]), tmp13, None)
tl.store(out_ptr5 + tl.broadcast_to(r0, [RBLOCK]), tmp17, None)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_div_sum_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x1 = xindex // 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 256 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (128 + x0 + 256 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (192 + x0 + 256 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.25
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) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (12,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 4),
reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 16), alpha=1,
beta=1, out=buf1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8),
reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha=1,
beta=1, out=buf2)
del primals_4
buf3 = reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(64)](buf3, primals_5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((16, 4, 16), (64, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (1, 16, 0),
0), reinterpret_tensor(buf1, (16, 1, 16), (1, 1, 16), 0), out=buf4)
buf7 = empty_strided_cuda((), (), torch.float32)
buf8 = empty_strided_cuda((16, 4, 16), (64, 16, 1), torch.float32)
buf13 = empty_strided_cuda((16, 4, 16), (64, 16, 1), torch.bool)
buf14 = empty_strided_cuda((16, 4, 16), (64, 16, 1), torch.bool)
triton_per_fused_div_eq_isnan_logical_and_logical_or_max_min_sub_1[grid
(1)](buf4, buf7, buf8, buf13, buf14, 1, 1024, num_warps=8,
num_stages=1)
del buf4
buf9 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf8, reinterpret_tensor(buf2, (16, 16, 1), (1,
16, 1), 0), out=buf9)
buf10 = empty_strided_cuda((4, 16, 1), (16, 1, 1), torch.float32)
triton_poi_fused_clone_2[grid(4, 16)](buf9, buf10, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_7, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_7
buf12 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_div_sum_3[grid(256)](buf8, buf12, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), buf12, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf7, buf8, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), primals_6, reinterpret_tensor(buf2, (16, 1, 16), (1, 1, 16), 0
), buf13, buf14, reinterpret_tensor(buf3, (16, 1, 4), (1, 1, 16), 0
), reinterpret_tensor(buf1, (16, 16, 1), (1, 16, 1), 0)
class MultiheadAttentionNew(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(self, embed_dim, num_heads, attn_dropout=0.0, bias=True,
add_bias_kv=False, add_zero_attn=False):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.attn_dropout = attn_dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
self.scaling = self.head_dim ** -0.5
self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim))
if bias:
self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.in_proj_weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
nn.init.xavier_normal_(self.bias_k)
if self.bias_v is not None:
nn.init.xavier_normal_(self.bias_v)
def in_proj_qkv(self, query):
return self._in_proj(query).chunk(3, dim=-1)
def in_proj_kv(self, key):
return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
def in_proj_q(self, query):
return self._in_proj(query, end=self.embed_dim)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=0, end=None):
weight = self.in_proj_weight
bias = self.in_proj_bias
weight = weight[start:end, :]
if bias is not None:
bias = bias[start:end]
return F.linear(input, weight, bias)
def forward(self, input_0, input_1, input_2):
primals_4 = self.in_proj_weight
primals_5 = self.in_proj_bias
primals_6 = self.out_proj.weight
primals_7 = self.out_proj.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
muqiaoy/dl_signal
|
MultiheadAttention
| false
| 16,135
|
[
"MIT"
] | 54
|
3a30d14982016644bfc96a7d1ca0109b441f17fd
|
https://github.com/muqiaoy/dl_signal/tree/3a30d14982016644bfc96a7d1ca0109b441f17fd
|
AdaptiveFeatureNorm
|
import torch
import torch.nn as nn
import torch.utils.data
class AdaptiveFeatureNorm(nn.Module):
"""
The `Stepwise Adaptive Feature Norm loss (ICCV 2019) <https://arxiv.org/pdf/1811.07456v2.pdf>`_
Instead of using restrictive scalar R to match the corresponding feature norm, Stepwise Adaptive Feature Norm
is used in order to learn task-specific features with large norms in a progressive manner.
We denote parameters of backbone :math:`G` as :math:`\\theta_g`, parameters of bottleneck :math:`F_f` as :math:`\\theta_f`
, parameters of classifier head :math:`F_y` as :math:`\\theta_y`, and features extracted from sample :math:`x_i` as
:math:`h(x_i;\\theta)`. Full loss is calculated as follows
.. math::
L(\\theta_g,\\theta_f,\\theta_y)=\\frac{1}{n_s}\\sum_{(x_i,y_i)\\in D_s}L_y(x_i,y_i)+\\frac{\\lambda}{n_s+n_t}
\\sum_{x_i\\in D_s\\cup D_t}L_d(h(x_i;\\theta_0)+\\Delta_r,h(x_i;\\theta))\\\\
where :math:`L_y` denotes classification loss, :math:`L_d` denotes norm loss, :math:`\\theta_0` and :math:`\\theta`
represent the updated and updating model parameters in the last and current iterations respectively.
Args:
delta (float): positive residual scalar to control the feature norm enlargement.
Inputs:
- f (tensor): feature representations on source or target domain.
Shape:
- f: :math:`(N, F)` where F means the dimension of input features.
- Outputs: scalar.
Examples::
>>> adaptive_feature_norm = AdaptiveFeatureNorm(delta=1)
>>> f_s = torch.randn(32, 1000)
>>> f_t = torch.randn(32, 1000)
>>> norm_loss = adaptive_feature_norm(f_s) + adaptive_feature_norm(f_t)
"""
def __init__(self, delta):
super(AdaptiveFeatureNorm, self).__init__()
self.delta = delta
def forward(self, f: 'torch.Tensor') ->torch.Tensor:
radius = f.norm(p=2, dim=1).detach()
assert radius.requires_grad is False
radius = radius + self.delta
loss = ((f.norm(p=2, dim=1) - radius) ** 2).mean()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'delta': 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.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_linalg_vector_norm_mean_pow_sub_0(in_out_ptr0,
in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
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)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = libdevice.sqrt(tmp10)
tmp12 = 4.0
tmp13 = tmp11 + tmp12
tmp14 = tmp11 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.sum(tmp16, 1)[:, None]
tmp19 = 64.0
tmp20 = tmp18 / 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, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_linalg_vector_norm_mean_pow_sub_0[grid(1)](buf1,
arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class AdaptiveFeatureNormNew(nn.Module):
"""
The `Stepwise Adaptive Feature Norm loss (ICCV 2019) <https://arxiv.org/pdf/1811.07456v2.pdf>`_
Instead of using restrictive scalar R to match the corresponding feature norm, Stepwise Adaptive Feature Norm
is used in order to learn task-specific features with large norms in a progressive manner.
We denote parameters of backbone :math:`G` as :math:`\\theta_g`, parameters of bottleneck :math:`F_f` as :math:`\\theta_f`
, parameters of classifier head :math:`F_y` as :math:`\\theta_y`, and features extracted from sample :math:`x_i` as
:math:`h(x_i;\\theta)`. Full loss is calculated as follows
.. math::
L(\\theta_g,\\theta_f,\\theta_y)=\\frac{1}{n_s}\\sum_{(x_i,y_i)\\in D_s}L_y(x_i,y_i)+\\frac{\\lambda}{n_s+n_t}
\\sum_{x_i\\in D_s\\cup D_t}L_d(h(x_i;\\theta_0)+\\Delta_r,h(x_i;\\theta))\\\\
where :math:`L_y` denotes classification loss, :math:`L_d` denotes norm loss, :math:`\\theta_0` and :math:`\\theta`
represent the updated and updating model parameters in the last and current iterations respectively.
Args:
delta (float): positive residual scalar to control the feature norm enlargement.
Inputs:
- f (tensor): feature representations on source or target domain.
Shape:
- f: :math:`(N, F)` where F means the dimension of input features.
- Outputs: scalar.
Examples::
>>> adaptive_feature_norm = AdaptiveFeatureNorm(delta=1)
>>> f_s = torch.randn(32, 1000)
>>> f_t = torch.randn(32, 1000)
>>> norm_loss = adaptive_feature_norm(f_s) + adaptive_feature_norm(f_t)
"""
def __init__(self, delta):
super(AdaptiveFeatureNormNew, self).__init__()
self.delta = delta
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
AdaptiveFeatureNorm
| false
| 16,136
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
BatchSpectralPenalizationLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class BatchSpectralPenalizationLoss(nn.Module):
"""Batch spectral penalization loss from `Transferability vs. Discriminability: Batch
Spectral Penalization for Adversarial Domain Adaptation (ICML 2019)
<http://ise.thss.tsinghua.edu.cn/~mlong/doc/batch-spectral-penalization-icml19.pdf>`_.
Given source features :math:`f_s` and target features :math:`f_t` in current mini batch, singular value
decomposition is first performed
.. math::
f_s = U_s\\Sigma_sV_s^T
.. math::
f_t = U_t\\Sigma_tV_t^T
Then batch spectral penalization loss is calculated as
.. math::
loss=\\sum_{i=1}^k(\\sigma_{s,i}^2+\\sigma_{t,i}^2)
where :math:`\\sigma_{s,i},\\sigma_{t,i}` refer to the :math:`i-th` largest singular value of source features
and target features respectively. We empirically set :math:`k=1`.
Inputs:
- f_s (tensor): feature representations on source domain, :math:`f^s`
- f_t (tensor): feature representations on target domain, :math:`f^t`
Shape:
- f_s, f_t: :math:`(N, F)` where F means the dimension of input features.
- Outputs: scalar.
"""
def __init__(self):
super(BatchSpectralPenalizationLoss, self).__init__()
def forward(self, f_s, f_t):
_, s_s, _ = torch.svd(f_s)
_, s_t, _ = torch.svd(f_t)
loss = torch.pow(s_s[0], 2) + torch.pow(s_t[0], 2)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_pow_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tl.store(out_ptr0 + x0, tmp4, 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 = torch.ops.aten._linalg_svd.default(arg0_1)
del arg0_1
buf2 = buf0[1]
del buf0
buf4 = torch.ops.aten._linalg_svd.default(arg1_1)
del arg1_1
buf6 = buf4[1]
del buf4
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_pow_0[grid(16)](buf2, buf6, buf8, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del buf2
del buf6
return buf8,
class BatchSpectralPenalizationLossNew(nn.Module):
"""Batch spectral penalization loss from `Transferability vs. Discriminability: Batch
Spectral Penalization for Adversarial Domain Adaptation (ICML 2019)
<http://ise.thss.tsinghua.edu.cn/~mlong/doc/batch-spectral-penalization-icml19.pdf>`_.
Given source features :math:`f_s` and target features :math:`f_t` in current mini batch, singular value
decomposition is first performed
.. math::
f_s = U_s\\Sigma_sV_s^T
.. math::
f_t = U_t\\Sigma_tV_t^T
Then batch spectral penalization loss is calculated as
.. math::
loss=\\sum_{i=1}^k(\\sigma_{s,i}^2+\\sigma_{t,i}^2)
where :math:`\\sigma_{s,i},\\sigma_{t,i}` refer to the :math:`i-th` largest singular value of source features
and target features respectively. We empirically set :math:`k=1`.
Inputs:
- f_s (tensor): feature representations on source domain, :math:`f^s`
- f_t (tensor): feature representations on target domain, :math:`f^t`
Shape:
- f_s, f_t: :math:`(N, F)` where F means the dimension of input features.
- Outputs: scalar.
"""
def __init__(self):
super(BatchSpectralPenalizationLossNew, 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]
|
neka-nat/Transfer-Learning-Library
|
BatchSpectralPenalizationLoss
| false
| 16,137
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
conv_embedding
|
import torch
from torch import nn
class conv_embedding(nn.Module):
def __init__(self, in_channels, out_channels, patch_size, stride, padding):
super(conv_embedding, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=
patch_size, stride=stride, padding=padding, bias=True)
def forward(self, x):
x = self.conv(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'patch_size': 4,
'stride': 1, 'padding': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import 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 = 1296
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 81 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (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=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 9, 9), (324, 81, 9, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(1296)](buf1, primals_2, 1296,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class conv_embeddingNew(nn.Module):
def __init__(self, in_channels, out_channels, patch_size, stride, padding):
super(conv_embeddingNew, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=
patch_size, stride=stride, padding=padding, bias=True)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
naver-ai/PfLayer
|
conv_embedding
| false
| 16,138
|
[
"Apache-2.0"
] | 59
|
da8f80b2ea3b6bd7fbee3beee8b1516c89bc0441
|
https://github.com/naver-ai/PfLayer/tree/da8f80b2ea3b6bd7fbee3beee8b1516c89bc0441
|
MLP_G
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class MLP_G(nn.Module):
def __init__(self, opt):
super(MLP_G, self).__init__()
self.fc1 = nn.Linear(opt.attSize + opt.nz, opt.ngh)
self.fc2 = nn.Linear(opt.ngh, opt.ngh)
self.fc3 = nn.Linear(opt.ngh, opt.resSize)
self.lrelu = nn.LeakyReLU(0.2, True)
self.relu = nn.ReLU(True)
self.apply(weights_init)
def forward(self, noise, att):
h = torch.cat((noise, att), 1)
h = self.lrelu(self.fc1(h))
h = self.relu(self.fc2(h))
h = self.relu(self.fc3(h))
return h
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'opt': _mock_config(attSize=4, nz=4, ngh=4, resSize=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_leaky_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x2, tmp7, xmask)
@triton.jit
def triton_poi_fused_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 8), (8, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8
), 0), out=buf1)
del primals_3
buf2 = buf1
del buf1
triton_poi_fused_leaky_relu_1[grid(16)](buf2, primals_4, 16, XBLOCK
=16, num_warps=1, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4
), 0), out=buf3)
buf4 = buf3
del buf3
triton_poi_fused_relu_2[grid(16)](buf4, primals_6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_7, (4, 4), (1, 4
), 0), out=buf5)
buf6 = buf5
del buf5
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(16)](buf6,
primals_8, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_8
return buf6, buf0, buf2, buf4, buf7, primals_7, primals_5
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class MLP_GNew(nn.Module):
def __init__(self, opt):
super(MLP_GNew, self).__init__()
self.fc1 = nn.Linear(opt.attSize + opt.nz, opt.ngh)
self.fc2 = nn.Linear(opt.ngh, opt.ngh)
self.fc3 = nn.Linear(opt.ngh, opt.resSize)
self.lrelu = nn.LeakyReLU(0.2, True)
self.relu = nn.ReLU(True)
self.apply(weights_init)
def forward(self, input_0, input_1):
primals_3 = self.fc1.weight
primals_4 = self.fc1.bias
primals_1 = self.fc2.weight
primals_6 = self.fc2.bias
primals_2 = self.fc3.weight
primals_8 = self.fc3.bias
primals_5 = input_0
primals_7 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
naraysa/gzsl-od
|
MLP_G
| false
| 16,139
|
[
"MIT"
] | 50
|
be771e12e17a4c02386c70697c4b26e3170a7557
|
https://github.com/naraysa/gzsl-od/tree/be771e12e17a4c02386c70697c4b26e3170a7557
|
PyramidPoolingModule
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class PyramidPoolingModule(nn.Module):
def __init__(self, pyramids=[1, 2, 3, 6]):
super(PyramidPoolingModule, self).__init__()
self.pyramids = pyramids
def forward(self, input):
feat = input
height, width = input.shape[2:]
for bin_size in self.pyramids:
x = F.adaptive_avg_pool2d(input, output_size=bin_size)
x = F.interpolate(x, size=(height, width), mode='bilinear',
align_corners=True)
feat = feat + x
return feat
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__adaptive_avg_pool2d_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 = 2 * x1 // 3
tmp1 = (9 + 4 * x1) // 6
tmp2 = tmp0 < tmp1
tmp3 = 2 * x0 // 3
tmp4 = (9 + 4 * x0) // 6
tmp5 = tmp3 < tmp4
tmp6 = tmp2 & tmp5
tmp7 = tl.load(in_ptr0 + (4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 // 3),
tmp6 & xmask, eviction_policy='evict_last', other=0.0)
tmp8 = 1 + 2 * x0 // 3
tmp9 = tmp8 < tmp4
tmp10 = tmp2 & tmp9
tmp11 = tl.load(in_ptr0 + (1 + 4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 //
3), tmp10 & xmask, eviction_policy='evict_last', other=0.0)
tmp12 = tmp11 + tmp7
tmp13 = 1 + 2 * x1 // 3
tmp14 = tmp13 < tmp1
tmp15 = tmp14 & tmp5
tmp16 = tl.load(in_ptr0 + (4 + 4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 //
3), tmp15 & xmask, eviction_policy='evict_last', other=0.0)
tmp17 = tmp16 + tmp12
tmp18 = tmp14 & tmp9
tmp19 = tl.load(in_ptr0 + (5 + 4 * (2 * x1 // 3) + 16 * x2 + 2 * x0 //
3), tmp18 & xmask, eviction_policy='evict_last', other=0.0)
tmp20 = tmp19 + tmp17
tmp21 = 1.0
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp6, tmp21, tmp22)
tmp24 = tl.where(tmp10, tmp21, tmp22)
tmp25 = tmp24 + tmp23
tmp26 = tl.where(tmp15, tmp21, tmp22)
tmp27 = tmp26 + tmp25
tmp28 = tl.where(tmp18, tmp21, tmp22)
tmp29 = tmp28 + tmp27
tmp30 = tmp20 / tmp29
tl.store(out_ptr0 + x4, tmp30, xmask)
@triton.jit
def triton_poi_fused__adaptive_avg_pool2d_1(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 = 4 * x1 // 3
tmp1 = 2 + 4 * x1 // 3
tmp2 = tmp0 < tmp1
tmp3 = 4 * x0 // 3
tmp4 = 2 + 4 * x0 // 3
tmp5 = tmp3 < tmp4
tmp6 = tmp2 & tmp5
tmp7 = tl.load(in_ptr0 + (4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 // 3),
tmp6 & xmask, other=0.0)
tmp8 = 1 + 4 * x0 // 3
tmp9 = tmp8 < tmp4
tmp10 = tmp2 & tmp9
tmp11 = tl.load(in_ptr0 + (1 + 4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 //
3), tmp10 & xmask, other=0.0)
tmp12 = tmp11 + tmp7
tmp13 = 1 + 4 * x1 // 3
tmp14 = tmp13 < tmp1
tmp15 = tmp14 & tmp5
tmp16 = tl.load(in_ptr0 + (4 + 4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 //
3), tmp15 & xmask, other=0.0)
tmp17 = tmp16 + tmp12
tmp18 = tmp14 & tmp9
tmp19 = tl.load(in_ptr0 + (5 + 4 * (4 * x1 // 3) + 16 * x2 + 4 * x0 //
3), tmp18 & xmask, other=0.0)
tmp20 = tmp19 + tmp17
tmp21 = 1.0
tmp22 = tl.full(tmp21.shape, 0.0, tmp21.dtype)
tmp23 = tl.where(tmp6, tmp21, tmp22)
tmp24 = tl.where(tmp10, tmp21, tmp22)
tmp25 = tmp24 + tmp23
tmp26 = tl.where(tmp15, tmp21, tmp22)
tmp27 = tmp26 + tmp25
tmp28 = tl.where(tmp18, tmp21, tmp22)
tmp29 = tmp28 + tmp27
tmp30 = tmp20 / tmp29
tl.store(out_ptr0 + x4, tmp30, xmask)
@triton.jit
def triton_per_fused__adaptive_avg_pool2d__to_copy__unsafe_index_add_arange_clamp_mean_mul_sub_2(
in_out_ptr4, in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r3 = rindex // 4
r2 = rindex % 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 = r3
tmp6 = tmp5.to(tl.float32)
tmp7 = 0.3333333333333333
tmp8 = tmp6 * tmp7
tmp9 = 0.0
tmp10 = triton_helpers.maximum(tmp8, tmp9)
tmp11 = tmp10.to(tl.int32)
tmp12 = tl.full([1, 1], 1, tl.int64)
tmp13 = tmp11 + tmp12
tmp14 = triton_helpers.minimum(tmp13, tmp12)
tmp15 = r2
tmp16 = tmp15.to(tl.float32)
tmp17 = tmp16 * tmp7
tmp18 = triton_helpers.maximum(tmp17, tmp9)
tmp19 = tmp18.to(tl.int32)
tmp20 = tmp19 + tmp12
tmp21 = triton_helpers.minimum(tmp20, tmp12)
tmp22 = tl.load(in_ptr0 + (2 * tmp21 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp23 = tl.load(in_ptr0 + (1 + 2 * tmp21 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp24 = tmp23 + tmp22
tmp25 = tl.load(in_ptr0 + (4 + 2 * tmp21 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp26 = tmp25 + tmp24
tmp27 = tl.load(in_ptr0 + (5 + 2 * tmp21 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp28 = tmp27 + tmp26
tmp29 = 0.25
tmp30 = tmp28 * tmp29
tmp31 = tl.load(in_ptr0 + (2 * tmp19 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp32 = tl.load(in_ptr0 + (1 + 2 * tmp19 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp33 = tmp32 + tmp31
tmp34 = tl.load(in_ptr0 + (4 + 2 * tmp19 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp35 = tmp34 + tmp33
tmp36 = tl.load(in_ptr0 + (5 + 2 * tmp19 + 8 * tmp14 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp37 = tmp36 + tmp35
tmp38 = tmp37 * tmp29
tmp39 = tmp30 - tmp38
tmp40 = tl.load(in_ptr0 + (2 * tmp21 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp41 = tl.load(in_ptr0 + (1 + 2 * tmp21 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp42 = tmp41 + tmp40
tmp43 = tl.load(in_ptr0 + (4 + 2 * tmp21 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp44 = tmp43 + tmp42
tmp45 = tl.load(in_ptr0 + (5 + 2 * tmp21 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp46 = tmp45 + tmp44
tmp47 = tmp46 * tmp29
tmp48 = tl.load(in_ptr0 + (2 * tmp19 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp49 = tl.load(in_ptr0 + (1 + 2 * tmp19 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp50 = tmp49 + tmp48
tmp51 = tl.load(in_ptr0 + (4 + 2 * tmp19 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp52 = tmp51 + tmp50
tmp53 = tl.load(in_ptr0 + (5 + 2 * tmp19 + 8 * tmp11 + 16 * x0), xmask,
eviction_policy='evict_last')
tmp54 = tmp53 + tmp52
tmp55 = tmp54 * tmp29
tmp56 = tmp47 - tmp55
tmp57 = tmp19.to(tl.float32)
tmp58 = tmp18 - tmp57
tmp59 = triton_helpers.maximum(tmp58, tmp9)
tmp60 = 1.0
tmp61 = triton_helpers.minimum(tmp59, tmp60)
tmp62 = tmp39 * tmp61
tmp63 = tmp38 + tmp62
tmp64 = tmp56 * tmp61
tmp65 = tmp55 + tmp64
tmp66 = 16.0
tmp67 = tmp4 / tmp66
tmp68 = tmp67 - tmp67
tmp69 = tmp68 * tmp9
tmp70 = tmp67 + tmp69
tmp71 = tmp70 - tmp70
tmp72 = tmp71 * tmp9
tmp73 = tmp70 + tmp72
tmp74 = tmp0 + tmp73
tmp75 = tmp63 - tmp65
tmp76 = tmp11.to(tl.float32)
tmp77 = tmp10 - tmp76
tmp78 = triton_helpers.maximum(tmp77, tmp9)
tmp79 = triton_helpers.minimum(tmp78, tmp60)
tmp80 = tmp75 * tmp79
tmp81 = tmp65 + tmp80
tmp82 = tmp74 + tmp81
tmp83 = 0.6666666666666666
tmp84 = tmp6 * tmp83
tmp85 = triton_helpers.maximum(tmp84, tmp9)
tmp86 = tmp85.to(tl.int32)
tmp87 = tmp86 + tmp12
tmp88 = tl.full([1, 1], 2, tl.int64)
tmp89 = triton_helpers.minimum(tmp87, tmp88)
tmp90 = tmp16 * tmp83
tmp91 = triton_helpers.maximum(tmp90, tmp9)
tmp92 = tmp91.to(tl.int32)
tmp93 = tl.load(in_ptr1 + (tmp92 + 3 * tmp89 + 9 * x0), xmask,
eviction_policy='evict_last')
tmp94 = tmp92 + tmp12
tmp95 = triton_helpers.minimum(tmp94, tmp88)
tmp96 = tl.load(in_ptr1 + (tmp95 + 3 * tmp89 + 9 * x0), xmask,
eviction_policy='evict_last')
tmp97 = tmp96 - tmp93
tmp98 = tmp92.to(tl.float32)
tmp99 = tmp91 - tmp98
tmp100 = triton_helpers.maximum(tmp99, tmp9)
tmp101 = triton_helpers.minimum(tmp100, tmp60)
tmp102 = tmp97 * tmp101
tmp103 = tmp93 + tmp102
tmp104 = tl.load(in_ptr1 + (tmp92 + 3 * tmp86 + 9 * x0), xmask,
eviction_policy='evict_last')
tmp105 = tl.load(in_ptr1 + (tmp95 + 3 * tmp86 + 9 * x0), xmask,
eviction_policy='evict_last')
tmp106 = tmp105 - tmp104
tmp107 = tmp106 * tmp101
tmp108 = tmp104 + tmp107
tmp109 = tmp103 - tmp108
tmp110 = tmp86.to(tl.float32)
tmp111 = tmp85 - tmp110
tmp112 = triton_helpers.maximum(tmp111, tmp9)
tmp113 = triton_helpers.minimum(tmp112, tmp60)
tmp114 = tmp109 * tmp113
tmp115 = tmp108 + tmp114
tmp116 = 1.6666666666666667
tmp117 = tmp6 * tmp116
tmp118 = triton_helpers.maximum(tmp117, tmp9)
tmp119 = tmp118.to(tl.int32)
tmp120 = tmp119 + tmp12
tmp121 = tl.full([1, 1], 5, tl.int64)
tmp122 = triton_helpers.minimum(tmp120, tmp121)
tmp123 = tmp16 * tmp116
tmp124 = triton_helpers.maximum(tmp123, tmp9)
tmp125 = tmp124.to(tl.int32)
tmp126 = tl.load(in_ptr2 + (tmp125 + 6 * tmp122 + 36 * x0), xmask,
eviction_policy='evict_last')
tmp127 = tmp125 + tmp12
tmp128 = triton_helpers.minimum(tmp127, tmp121)
tmp129 = tl.load(in_ptr2 + (tmp128 + 6 * tmp122 + 36 * x0), xmask,
eviction_policy='evict_last')
tmp130 = tmp129 - tmp126
tmp131 = tmp125.to(tl.float32)
tmp132 = tmp124 - tmp131
tmp133 = triton_helpers.maximum(tmp132, tmp9)
tmp134 = triton_helpers.minimum(tmp133, tmp60)
tmp135 = tmp130 * tmp134
tmp136 = tmp126 + tmp135
tmp137 = tl.load(in_ptr2 + (tmp125 + 6 * tmp119 + 36 * x0), xmask,
eviction_policy='evict_last')
tmp138 = tl.load(in_ptr2 + (tmp128 + 6 * tmp119 + 36 * x0), xmask,
eviction_policy='evict_last')
tmp139 = tmp138 - tmp137
tmp140 = tmp139 * tmp134
tmp141 = tmp137 + tmp140
tmp142 = tmp136 - tmp141
tmp143 = tmp119.to(tl.float32)
tmp144 = tmp118 - tmp143
tmp145 = triton_helpers.maximum(tmp144, tmp9)
tmp146 = triton_helpers.minimum(tmp145, tmp60)
tmp147 = tmp142 * tmp146
tmp148 = tmp141 + tmp147
tmp149 = tmp82 + tmp115
tmp150 = tmp149 + tmp148
tl.store(in_out_ptr4 + (r1 + 16 * x0), tmp150, 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)
buf10 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32
)
get_raw_stream(0)
triton_poi_fused__adaptive_avg_pool2d_0[grid(576)](arg0_1, buf10,
576, XBLOCK=256, num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
triton_poi_fused__adaptive_avg_pool2d_1[grid(144)](arg0_1, buf7,
144, XBLOCK=256, num_warps=4, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf12 = buf11
del buf11
buf13 = buf12
del buf12
triton_per_fused__adaptive_avg_pool2d__to_copy__unsafe_index_add_arange_clamp_mean_mul_sub_2[
grid(16)](buf13, arg0_1, buf7, buf10, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del arg0_1
del buf10
del buf7
return buf13,
class PyramidPoolingModuleNew(nn.Module):
def __init__(self, pyramids=[1, 2, 3, 6]):
super(PyramidPoolingModuleNew, self).__init__()
self.pyramids = pyramids
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nassir90/ICNet-pytorch
|
PyramidPoolingModule
| false
| 16,140
|
[
"MIT"
] | 83
|
af6eec01a4419ce43c52d295bc502c366478fbd7
|
https://github.com/nassir90/ICNet-pytorch/tree/af6eec01a4419ce43c52d295bc502c366478fbd7
|
RobertaClassificationHead
|
import torch
import torch.nn as nn
from typing import Optional
class RobertaClassificationHead(nn.Module):
def __init__(self, num_classes, input_dim, inner_dim: 'Optional[int]'=
None, dropout: 'float'=0.1, activation=nn.ReLU):
super().__init__()
if not inner_dim:
inner_dim = input_dim
self.dense = nn.Linear(input_dim, inner_dim)
self.dropout = nn.Dropout(dropout)
self.out_proj = nn.Linear(inner_dim, num_classes)
self.activation_fn = activation()
def forward(self, features):
x = features[:, 0, :]
x = self.dropout(x)
x = self.dense(x)
x = self.activation_fn(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_classes': 4, 'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
from typing import Optional
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_relu_threshold_backward_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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (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_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf2,
primals_3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(buf0, (16, 4), (4, 1), 0), reinterpret_tensor(
buf2, (16, 4), (4, 1), 0), primals_4, buf4
class RobertaClassificationHeadNew(nn.Module):
def __init__(self, num_classes, input_dim, inner_dim: 'Optional[int]'=
None, dropout: 'float'=0.1, activation=nn.ReLU):
super().__init__()
if not inner_dim:
inner_dim = input_dim
self.dense = nn.Linear(input_dim, inner_dim)
self.dropout = nn.Dropout(dropout)
self.out_proj = nn.Linear(inner_dim, num_classes)
self.activation_fn = activation()
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_4 = self.out_proj.weight
primals_5 = self.out_proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
nateanl/text
|
RobertaClassificationHead
| false
| 16,141
|
[
"BSD-3-Clause"
] | 3,172
|
b26e9350ad387a84aefe131443bbbf1c51a8a618
|
https://github.com/nateanl/text/tree/b26e9350ad387a84aefe131443bbbf1c51a8a618
|
BatchSpectralShrinkage
|
import torch
import torch.nn as nn
import torch.utils.data
class BatchSpectralShrinkage(nn.Module):
"""
The regularization term in `Catastrophic Forgetting Meets Negative Transfer:
Batch Spectral Shrinkage for Safe Transfer Learning (NIPS 2019) <https://proceedings.neurips.cc/paper/2019/file/c6bff625bdb0393992c9d4db0c6bbe45-Paper.pdf>`_.
The BSS regularization of feature matrix :math:`F` can be described as:
.. math::
L_{bss}(F) = \\sum_{i=1}^{k} \\sigma_{-i}^2 ,
where :math:`k` is the number of singular values to be penalized, :math:`\\sigma_{-i}` is the :math:`i`-th smallest singular value of feature matrix :math:`F`.
All the singular values of feature matrix :math:`F` are computed by `SVD`:
.. math::
F = U\\Sigma V^T,
where the main diagonal elements of the singular value matrix :math:`\\Sigma` is :math:`[\\sigma_1, \\sigma_2, ..., \\sigma_b]`.
Args:
k (int): The number of singular values to be penalized. Default: 1
Shape:
- Input: :math:`(b, |\\mathcal{f}|)` where :math:`b` is the batch size and :math:`|\\mathcal{f}|` is feature dimension.
- Output: scalar.
"""
def __init__(self, k=1):
super(BatchSpectralShrinkage, self).__init__()
self.k = k
def forward(self, feature):
result = 0
_u, s, _v = torch.svd(feature.t())
num = s.size(0)
for i in range(self.k):
result += torch.pow(s[num - 1 - i], 2)
return result
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
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_pow_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
tmp0 = tl.load(in_ptr0 + 3)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tmp1 * tmp1
tmp3 = 0.0
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp4, 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 = torch.ops.aten._linalg_svd.default(reinterpret_tensor(arg0_1,
(4, 4), (1, 4), 0))
del arg0_1
buf2 = buf0[1]
del buf0
buf4 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_pow_0[grid(1)](buf2, buf4, 1, XBLOCK=1,
num_warps=1, num_stages=1)
del buf2
return buf4,
class BatchSpectralShrinkageNew(nn.Module):
"""
The regularization term in `Catastrophic Forgetting Meets Negative Transfer:
Batch Spectral Shrinkage for Safe Transfer Learning (NIPS 2019) <https://proceedings.neurips.cc/paper/2019/file/c6bff625bdb0393992c9d4db0c6bbe45-Paper.pdf>`_.
The BSS regularization of feature matrix :math:`F` can be described as:
.. math::
L_{bss}(F) = \\sum_{i=1}^{k} \\sigma_{-i}^2 ,
where :math:`k` is the number of singular values to be penalized, :math:`\\sigma_{-i}` is the :math:`i`-th smallest singular value of feature matrix :math:`F`.
All the singular values of feature matrix :math:`F` are computed by `SVD`:
.. math::
F = U\\Sigma V^T,
where the main diagonal elements of the singular value matrix :math:`\\Sigma` is :math:`[\\sigma_1, \\sigma_2, ..., \\sigma_b]`.
Args:
k (int): The number of singular values to be penalized. Default: 1
Shape:
- Input: :math:`(b, |\\mathcal{f}|)` where :math:`b` is the batch size and :math:`|\\mathcal{f}|` is feature dimension.
- Output: scalar.
"""
def __init__(self, k=1):
super(BatchSpectralShrinkageNew, self).__init__()
self.k = k
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
BatchSpectralShrinkage
| false
| 16,142
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
CIFAR10_Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CIFAR10_Net(nn.Module):
def __init__(self):
super(CIFAR10_Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 32, kernel_size=5)
self.conv3 = nn.Conv2d(32, 64, kernel_size=5)
self.fc1 = nn.Linear(1024, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = F.relu(F.max_pool2d(self.conv3(x), 2))
x = x.view(-1, 1024)
e1 = F.relu(self.fc1(x))
x = F.dropout(e1, training=self.training)
x = self.fc2(x)
return x, e1
def get_embedding_dim(self):
return 50
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
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 3600 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 3136 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_2(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 28
x1 = xindex // 28
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 112 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 112 * x1), None, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (56 + 2 * x0 + 112 * x1), None,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (57 + 2 * x0 + 112 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tmp17 = tl.full([1], 0, tl.int32)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tl.store(out_ptr0 + x2, tmp15, None)
tl.store(out_ptr1 + x2, tmp18, None)
@triton.jit
def triton_poi_fused_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 576 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_threshold_backward_4(in_ptr0,
out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 48 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 48 * x1), None, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (24 + 2 * x0 + 48 * x1), None, eviction_policy
='evict_last')
tmp12 = tl.load(in_ptr0 + (25 + 2 * x0 + 48 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tmp17 = tl.full([1], 0, tl.int32)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp19 = 0.0
tmp20 = tmp18 <= tmp19
tl.store(out_ptr0 + x2, tmp15, None)
tl.store(out_ptr1 + x2, tmp18, None)
tl.store(out_ptr2 + x2, tmp20, None)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1800
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 50
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (32, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (32, 32, 5, 5), (800, 25, 5, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (64, 32, 5, 5), (800, 25, 5, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (50, 1024), (1024, 1))
assert_size_stride(primals_9, (50,), (1,))
assert_size_stride(primals_10, (10, 50), (50, 1))
assert_size_stride(primals_11, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 60, 60), (115200, 3600, 60, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(460800)](buf1, primals_2,
460800, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 56, 56), (100352, 3136, 56, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(401408)](buf3, primals_5,
401408, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 32, 28, 28), (25088, 784, 28, 1),
torch.int8)
buf5 = empty_strided_cuda((4, 32, 28, 28), (25088, 784, 28, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_relu_2[grid(100352)](buf3,
buf4, buf5, 100352, XBLOCK=512, num_warps=8, num_stages=1)
buf6 = extern_kernels.convolution(buf5, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 64, 24, 24), (36864, 576, 24, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_3[grid(147456)](buf7, primals_7,
147456, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf8 = empty_strided_cuda((4, 64, 12, 12), (9216, 144, 12, 1),
torch.int8)
buf9 = empty_strided_cuda((4, 64, 12, 12), (9216, 144, 12, 1),
torch.float32)
buf13 = empty_strided_cuda((4, 64, 12, 12), (9216, 144, 12, 1),
torch.bool)
triton_poi_fused_max_pool2d_with_indices_relu_threshold_backward_4[grid
(36864)](buf7, buf8, buf9, buf13, 36864, XBLOCK=512, num_warps=
4, num_stages=1)
buf10 = empty_strided_cuda((36, 50), (50, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf9, (36, 1024), (1024, 1), 0
), reinterpret_tensor(primals_8, (1024, 50), (1, 1024), 0), out
=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_5[grid(1800)](buf11, primals_9, 1800, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((36, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_11, buf11, reinterpret_tensor(
primals_10, (50, 10), (1, 50), 0), alpha=1, beta=1, out=buf12)
del primals_11
return (buf12, buf11, primals_1, primals_3, primals_4, primals_6, buf1,
buf3, buf4, buf5, buf7, buf8, reinterpret_tensor(buf9, (36, 1024),
(1024, 1), 0), buf11, primals_10, primals_8, buf13)
class CIFAR10_NetNew(nn.Module):
def __init__(self):
super(CIFAR10_NetNew, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 32, kernel_size=5)
self.conv3 = nn.Conv2d(32, 64, kernel_size=5)
self.fc1 = nn.Linear(1024, 50)
self.fc2 = nn.Linear(50, 10)
def get_embedding_dim(self):
return 50
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.fc1.weight
primals_9 = self.fc1.bias
primals_10 = self.fc2.weight
primals_11 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0], output[1]
|
nannullna/deep-active-learning
|
CIFAR10_Net
| false
| 16,143
|
[
"MIT"
] | 465
|
c54a995640c63ba4679129c5a1fd5cec9a2858e6
|
https://github.com/nannullna/deep-active-learning/tree/c54a995640c63ba4679129c5a1fd5cec9a2858e6
|
BridgeFeatLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class BridgeFeatLoss(nn.Module):
def __init__(self):
super(BridgeFeatLoss, self).__init__()
def forward(self, f_s, f_t, f_mixed, lam):
dist_mixed2s = ((f_mixed - f_s) ** 2).sum(1, keepdim=True)
dist_mixed2t = ((f_mixed - f_t) ** 2).sum(1, keepdim=True)
dist_mixed2s = dist_mixed2s.clamp(min=1e-12).sqrt()
dist_mixed2t = dist_mixed2t.clamp(min=1e-12).sqrt()
dist_mixed = torch.cat((dist_mixed2s, dist_mixed2t), 1)
lam_dist_mixed = (lam * dist_mixed).sum(1, keepdim=True)
loss = lam_dist_mixed.mean()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 2, 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
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, 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_ptr1 + (x0 + 64 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tmp5 - tmp6
tmp8 = tmp7 * tmp7
tmp9 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp14 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = tmp19 - tmp20
tmp22 = tmp21 * tmp21
tmp23 = tmp18 + tmp22
tmp24 = 1e-12
tmp25 = triton_helpers.maximum(tmp23, tmp24)
tmp26 = libdevice.sqrt(tmp25)
tmp27 = tl.full(tmp26.shape, 0.0, tmp26.dtype)
tmp28 = tl.where(tmp4, tmp26, tmp27)
tmp29 = tmp0 >= tmp3
tl.full([1], 2, tl.int64)
tmp32 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp33 = tl.load(in_ptr2 + (x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp34 = tmp32 - tmp33
tmp35 = tmp34 * tmp34
tmp36 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp37 = tl.load(in_ptr2 + (16 + x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp38 = tmp36 - tmp37
tmp39 = tmp38 * tmp38
tmp40 = tmp35 + tmp39
tmp41 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp42 = tl.load(in_ptr2 + (32 + x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp43 = tmp41 - tmp42
tmp44 = tmp43 * tmp43
tmp45 = tmp40 + tmp44
tmp46 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp47 = tl.load(in_ptr2 + (48 + x0 + 64 * x2), tmp29 & xmask,
eviction_policy='evict_last', other=0.0)
tmp48 = tmp46 - tmp47
tmp49 = tmp48 * tmp48
tmp50 = tmp45 + tmp49
tmp51 = triton_helpers.maximum(tmp50, tmp24)
tmp52 = libdevice.sqrt(tmp51)
tmp53 = tl.full(tmp52.shape, 0.0, tmp52.dtype)
tmp54 = tl.where(tmp29, tmp52, tmp53)
tmp55 = tl.where(tmp4, tmp28, tmp54)
tl.store(out_ptr0 + x3, tmp55, xmask)
@triton.jit
def triton_per_fused_mean_mul_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 32 * r1), None)
tmp1 = tl.load(in_ptr1 + (r0 + 32 * r1), None)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 32 * r1), None)
tmp4 = tl.load(in_ptr1 + (16 + r0 + 32 * r1), None)
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp10 = 64.0
tmp11 = tmp9 / tmp10
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp11, 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, 2, 4, 4), (32, 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, arg1_1, arg2_1, buf0, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_mean_mul_sum_1[grid(1)](buf2, arg3_1, buf0, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del arg3_1
del buf0
return buf2,
class BridgeFeatLossNew(nn.Module):
def __init__(self):
super(BridgeFeatLossNew, self).__init__()
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]
|
neka-nat/Transfer-Learning-Library
|
BridgeFeatLoss
| false
| 16,144
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
DirectedGraphConvolution
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def normalize_adj(adj):
last_dim = adj.size(-1)
rowsum = adj.sum(2, keepdim=True).repeat(1, 1, last_dim)
return torch.div(adj, rowsum)
class DirectedGraphConvolution(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weight1 = nn.Parameter(torch.zeros((in_features, out_features)))
self.weight2 = nn.Parameter(torch.zeros((in_features, out_features)))
self.dropout = nn.Dropout(0.1)
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.weight1.data)
nn.init.xavier_uniform_(self.weight2.data)
def forward(self, inputs, adj):
norm_adj = normalize_adj(adj)
output1 = F.relu(torch.matmul(norm_adj, torch.matmul(inputs, self.
weight1)))
inv_norm_adj = normalize_adj(adj.transpose(1, 2))
output2 = F.relu(torch.matmul(inv_norm_adj, torch.matmul(inputs,
self.weight2)))
out = (output1 + output2) / 2
out = self.dropout(out)
return out
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_div_repeat_sum_0(in_ptr0, out_ptr0, out_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x1 = xindex // 4
x0 = xindex % 4
x3 = xindex // 16
tmp0 = tl.load(in_ptr0 + x4, 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')
tmp9 = tl.load(in_ptr0 + (x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr0 + (4 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr0 + (8 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (12 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp11 = tmp9 + tmp10
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp16 = tmp0 / tmp15
tl.store(out_ptr0 + x4, tmp8, xmask)
tl.store(out_ptr1 + x4, tmp16, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
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_clone_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x1 + 4 * x0 + 16 * x2), xmask,
eviction_policy='evict_last')
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_div_relu_threshold_backward_3(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp1, tmp3)
tmp5 = tmp2 + tmp4
tmp6 = 0.5
tmp7 = tmp5 * tmp6
tmp8 = 0.0
tmp9 = tmp4 <= tmp8
tmp10 = tmp2 <= tmp8
tl.store(out_ptr0 + x0, tmp7, xmask)
tl.store(out_ptr1 + x0, tmp9, xmask)
tl.store(out_ptr2 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4), (16, 1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_repeat_sum_0[grid(64)](primals_1, buf1, buf5,
64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_1
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(256)](buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1), 0), out=buf3)
buf4 = buf0
del buf0
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
primals_4, out=buf4)
del primals_4
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
buf7 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0), out=buf7)
buf8 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_div_relu_threshold_backward_3[grid(256)](buf3,
buf7, buf8, buf9, buf10, 256, XBLOCK=256, num_warps=4, num_stages=1
)
del buf3
del buf7
return buf8, buf9, reinterpret_tensor(buf6, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(primals_3, (4, 64), (1, 4), 0
), buf10, reinterpret_tensor(buf2, (16, 4, 4), (16, 1, 4), 0)
def normalize_adj(adj):
last_dim = adj.size(-1)
rowsum = adj.sum(2, keepdim=True).repeat(1, 1, last_dim)
return torch.div(adj, rowsum)
class DirectedGraphConvolutionNew(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weight1 = nn.Parameter(torch.zeros((in_features, out_features)))
self.weight2 = nn.Parameter(torch.zeros((in_features, out_features)))
self.dropout = nn.Dropout(0.1)
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.weight1.data)
nn.init.xavier_uniform_(self.weight2.data)
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
def forward(self, input_0, input_1):
primals_2 = self.weight1
primals_4 = self.weight2
primals_3 = input_0
primals_1 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
naszilla/naszilla
|
DirectedGraphConvolution
| false
| 16,145
|
[
"Apache-2.0"
] | 112
|
5575cc8c95e79ce5743e8ea7ef53d6da900f8480
|
https://github.com/naszilla/naszilla/tree/5575cc8c95e79ce5743e8ea7ef53d6da900f8480
|
ShapedSineModel
|
import torch
import torch.utils.data
class ShapedSineModel(torch.nn.Module):
def __init__(self, theta=None):
super(ShapedSineModel, self).__init__()
if theta is None:
self.freq = torch.nn.Parameter(torch.Tensor([0.1]))
else:
self.freq = torch.nn.Parameter(torch.Tensor([theta]))
self.learning_rate = 1.0
def forward(self, x):
return torch.sin(self.freq * 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.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_sin_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 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp3 = tmp1 * tmp2
tmp4 = tl_math.sin(tmp3)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = 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)](primals_1, primals_2, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf0, primals_1, primals_2
class ShapedSineModelNew(torch.nn.Module):
def __init__(self, theta=None):
super(ShapedSineModelNew, self).__init__()
if theta is None:
self.freq = torch.nn.Parameter(torch.Tensor([0.1]))
else:
self.freq = torch.nn.Parameter(torch.Tensor([theta]))
self.learning_rate = 1.0
def forward(self, input_0):
primals_1 = self.freq
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
neha191091/LearningToLearn
|
ShapedSineModel
| false
| 16,146
|
[
"MIT"
] | 76
|
3619d27bb3b7a836d9423dfbdd8da82460d4fa73
|
https://github.com/neha191091/LearningToLearn/tree/3619d27bb3b7a836d9423dfbdd8da82460d4fa73
|
VanillaGenerativeAdversarialLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class VanillaGenerativeAdversarialLoss(nn.Module):
"""
Loss for `Vanilla Generative Adversarial Network <https://arxiv.org/abs/1406.2661>`_
Args:
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs:
- prediction (tensor): unnormalized discriminator predictions
- real (bool): if the ground truth label is for real images or fake images. Default: true
.. warning::
Do not use sigmoid as the last layer of Discriminator.
"""
def __init__(self, reduction='mean'):
super(VanillaGenerativeAdversarialLoss, self).__init__()
self.bce_loss = nn.BCEWithLogitsLoss(reduction=reduction)
def forward(self, prediction, real=True):
if real:
label = torch.ones_like(prediction)
else:
label = torch.zeros_like(prediction)
return self.bce_loss(prediction, label)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_binary_cross_entropy_with_logits_0(in_out_ptr0,
in_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 0.0
tmp2 = tmp1 * tmp0
tmp3 = triton_helpers.minimum(tmp1, tmp0)
tmp4 = tl_math.abs(tmp0)
tmp5 = -tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = libdevice.log1p(tmp6)
tmp8 = tmp3 - tmp7
tmp9 = tmp2 - tmp8
tmp10 = tl.broadcast_to(tmp9, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp13 = 256.0
tmp14 = tmp12 / tmp13
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_with_logits_0[grid(1)](buf1,
arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class VanillaGenerativeAdversarialLossNew(nn.Module):
"""
Loss for `Vanilla Generative Adversarial Network <https://arxiv.org/abs/1406.2661>`_
Args:
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs:
- prediction (tensor): unnormalized discriminator predictions
- real (bool): if the ground truth label is for real images or fake images. Default: true
.. warning::
Do not use sigmoid as the last layer of Discriminator.
"""
def __init__(self, reduction='mean'):
super(VanillaGenerativeAdversarialLossNew, self).__init__()
self.bce_loss = nn.BCEWithLogitsLoss(reduction=reduction)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
VanillaGenerativeAdversarialLoss
| false
| 16,147
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
LeastSquaresGenerativeAdversarialLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class LeastSquaresGenerativeAdversarialLoss(nn.Module):
"""
Loss for `Least Squares Generative Adversarial Network (LSGAN) <https://arxiv.org/abs/1611.04076>`_
Args:
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs:
- prediction (tensor): unnormalized discriminator predictions
- real (bool): if the ground truth label is for real images or fake images. Default: true
.. warning::
Do not use sigmoid as the last layer of Discriminator.
"""
def __init__(self, reduction='mean'):
super(LeastSquaresGenerativeAdversarialLoss, self).__init__()
self.mse_loss = nn.MSELoss(reduction=reduction)
def forward(self, prediction, real=True):
if real:
label = torch.ones_like(prediction)
else:
label = torch.zeros_like(prediction)
return self.mse_loss(prediction, label)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mse_loss_ones_like_0(in_out_ptr0, in_ptr0, xnumel, rnumel
):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = 256.0
tmp8 = tmp6 / tmp7
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp8, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mse_loss_ones_like_0[grid(1)](buf1, arg0_1, 1, 256,
num_warps=2, num_stages=1)
del arg0_1
return buf1,
class LeastSquaresGenerativeAdversarialLossNew(nn.Module):
"""
Loss for `Least Squares Generative Adversarial Network (LSGAN) <https://arxiv.org/abs/1611.04076>`_
Args:
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs:
- prediction (tensor): unnormalized discriminator predictions
- real (bool): if the ground truth label is for real images or fake images. Default: true
.. warning::
Do not use sigmoid as the last layer of Discriminator.
"""
def __init__(self, reduction='mean'):
super(LeastSquaresGenerativeAdversarialLossNew, self).__init__()
self.mse_loss = nn.MSELoss(reduction=reduction)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
LeastSquaresGenerativeAdversarialLoss
| false
| 16,148
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
Theta
|
from torch.autograd import Function
import torch
import torch.nn as nn
from typing import Tuple
from typing import Optional
from typing import Any
import torch.utils.data
class GradientReverseFunction(Function):
@staticmethod
def forward(ctx: 'Any', input: 'torch.Tensor', coeff: 'Optional[float]'=1.0
) ->torch.Tensor:
ctx.coeff = coeff
output = input * 1.0
return output
@staticmethod
def backward(ctx: 'Any', grad_output: 'torch.Tensor') ->Tuple[torch.
Tensor, Any]:
return grad_output.neg() * ctx.coeff, None
class GradientReverseLayer(nn.Module):
def __init__(self):
super(GradientReverseLayer, self).__init__()
def forward(self, *input):
return GradientReverseFunction.apply(*input)
class Theta(nn.Module):
"""
maximize loss respect to :math:` heta`
minimize loss respect to features
"""
def __init__(self, dim: 'int'):
super(Theta, self).__init__()
self.grl1 = GradientReverseLayer()
self.grl2 = GradientReverseLayer()
self.layer1 = nn.Linear(dim, dim)
nn.init.eye_(self.layer1.weight)
nn.init.zeros_(self.layer1.bias)
def forward(self, features: 'torch.Tensor') ->torch.Tensor:
features = self.grl1(features)
return self.grl2(self.layer1(features))
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.autograd import Function
import torch.nn as nn
from typing import Tuple
from typing import Optional
from typing import Any
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_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 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, 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, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
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, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused_mul_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 GradientReverseFunction(Function):
@staticmethod
def forward(ctx: 'Any', input: 'torch.Tensor', coeff: 'Optional[float]'=1.0
) ->torch.Tensor:
ctx.coeff = coeff
output = input * 1.0
return output
@staticmethod
def backward(ctx: 'Any', grad_output: 'torch.Tensor') ->Tuple[torch.
Tensor, Any]:
return grad_output.neg() * ctx.coeff, None
class GradientReverseLayer(nn.Module):
def __init__(self):
super(GradientReverseLayer, self).__init__()
def forward(self, *input):
return GradientReverseFunction.apply(*input)
class ThetaNew(nn.Module):
"""
maximize loss respect to :math:` heta`
minimize loss respect to features
"""
def __init__(self, dim: 'int'):
super(ThetaNew, self).__init__()
self.grl1 = GradientReverseLayer()
self.grl2 = GradientReverseLayer()
self.layer1 = nn.Linear(dim, dim)
nn.init.eye_(self.layer1.weight)
nn.init.zeros_(self.layer1.bias)
def forward(self, input_0):
primals_2 = self.layer1.weight
primals_3 = self.layer1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
Theta
| false
| 16,149
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
GaussianKernel
|
import torch
import torch.nn as nn
from typing import Optional
import torch.utils.data
class GaussianKernel(nn.Module):
"""Gaussian Kernel Matrix
Gaussian Kernel k is defined by
.. math::
k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)
where :math:`x_1, x_2 \\in R^d` are 1-d tensors.
Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`
.. math::
K(X)_{i,j} = k(x_i, x_j)
Also by default, during training this layer keeps running estimates of the
mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.
Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.
If :attr:`track_running_stats` is set to ``False``, this layer then does not
keep running estimates, and use a fixed :math:`\\sigma` instead.
Args:
sigma (float, optional): bandwidth :math:`\\sigma`. Default: None
track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.
Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``
alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``
Inputs:
- X (tensor): input group :math:`X`
Shape:
- Inputs: :math:`(minibatch, F)` where F means the dimension of input features.
- Outputs: :math:`(minibatch, minibatch)`
"""
def __init__(self, sigma: 'Optional[float]'=None, track_running_stats:
'Optional[bool]'=True, alpha: 'Optional[float]'=1.0):
super(GaussianKernel, self).__init__()
assert track_running_stats or sigma is not None
self.sigma_square = torch.tensor(sigma * sigma
) if sigma is not None else None
self.track_running_stats = track_running_stats
self.alpha = alpha
def forward(self, X: 'torch.Tensor') ->torch.Tensor:
l2_distance_square = ((X.unsqueeze(0) - X.unsqueeze(1)) ** 2).sum(2)
if self.track_running_stats:
self.sigma_square = self.alpha * torch.mean(l2_distance_square.
detach())
return torch.exp(-l2_distance_square / (2 * self.sigma_square))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from typing import Optional
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_div_exp_mean_mul_neg_pow_sub_sum_0(in_out_ptr0,
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 % 16
r1 = rindex // 16 % 4
r2 = rindex // 64
r3 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None, eviction_policy='evict_last'
)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tl.broadcast_to(tmp18, [RBLOCK])
tmp21 = triton_helpers.promote_to_tensor(tl.sum(tmp19, 0))
tmp22 = 256.0
tmp23 = tmp21 / tmp22
tmp24 = 1.0
tmp25 = tmp23 * tmp24
tmp26 = -tmp18
tmp27 = 2.0
tmp28 = tmp25 * tmp27
tmp29 = tmp26 / tmp28
tmp30 = tl_math.exp(tmp29)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp25, None)
tl.store(out_ptr1 + tl.broadcast_to(r3, [RBLOCK]), tmp30, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_div_exp_mean_mul_neg_pow_sub_sum_0[grid(1)](buf2,
arg0_1, buf3, 1, 256, num_warps=2, num_stages=1)
del arg0_1
return buf3, buf2
class GaussianKernelNew(nn.Module):
"""Gaussian Kernel Matrix
Gaussian Kernel k is defined by
.. math::
k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)
where :math:`x_1, x_2 \\in R^d` are 1-d tensors.
Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`
.. math::
K(X)_{i,j} = k(x_i, x_j)
Also by default, during training this layer keeps running estimates of the
mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.
Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.
If :attr:`track_running_stats` is set to ``False``, this layer then does not
keep running estimates, and use a fixed :math:`\\sigma` instead.
Args:
sigma (float, optional): bandwidth :math:`\\sigma`. Default: None
track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.
Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``
alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``
Inputs:
- X (tensor): input group :math:`X`
Shape:
- Inputs: :math:`(minibatch, F)` where F means the dimension of input features.
- Outputs: :math:`(minibatch, minibatch)`
"""
def __init__(self, sigma: 'Optional[float]'=None, track_running_stats:
'Optional[bool]'=True, alpha: 'Optional[float]'=1.0):
super(GaussianKernelNew, self).__init__()
assert track_running_stats or sigma is not None
self.sigma_square = torch.tensor(sigma * sigma
) if sigma is not None else None
self.track_running_stats = track_running_stats
self.alpha = alpha
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
GaussianKernel
| false
| 16,150
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
DivLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class DivLoss(nn.Module):
def __init__(self):
super(DivLoss, self).__init__()
def forward(self, lam):
mu = lam.mean(0)
std = ((lam - mu) ** 2).mean(0, keepdim=True).clamp(min=1e-12).sqrt()
loss_std = -std.sum()
return loss_std
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_clamp_mean_neg_pow_sqrt_sub_sum_0(in_out_ptr0, in_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr0 + (64 + r0), None)
tmp3 = tl.load(in_ptr0 + (128 + r0), None)
tmp5 = tl.load(in_ptr0 + (192 + r0), None)
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-12
tmp22 = triton_helpers.maximum(tmp20, tmp21)
tmp23 = libdevice.sqrt(tmp22)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp26 = tl.sum(tmp24, 1)[:, None]
tmp27 = -tmp26
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp27, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_clamp_mean_neg_pow_sqrt_sub_sum_0[grid(1)](buf1,
arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class DivLossNew(nn.Module):
def __init__(self):
super(DivLossNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
DivLoss
| false
| 16,151
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
CorrelationAlignmentLoss
|
import torch
import torch.nn as nn
import torch.utils.data
class CorrelationAlignmentLoss(nn.Module):
"""The `Correlation Alignment Loss` in
`Deep CORAL: Correlation Alignment for Deep Domain Adaptation (ECCV 2016) <https://arxiv.org/pdf/1607.01719.pdf>`_.
Given source features :math:`f_S` and target features :math:`f_T`, the covariance matrices are given by
.. math::
C_S = \\frac{1}{n_S-1}(f_S^Tf_S-\\frac{1}{n_S}(\\textbf{1}^Tf_S)^T(\\textbf{1}^Tf_S))
.. math::
C_T = \\frac{1}{n_T-1}(f_T^Tf_T-\\frac{1}{n_T}(\\textbf{1}^Tf_T)^T(\\textbf{1}^Tf_T))
where :math:`\\textbf{1}` denotes a column vector with all elements equal to 1, :math:`n_S, n_T` denotes number of
source and target samples, respectively. We use :math:`d` to denote feature dimension, use
:math:`{\\Vert\\cdot\\Vert}^2_F` to denote the squared matrix `Frobenius norm`. The correlation alignment loss is
given by
.. math::
l_{CORAL} = \\frac{1}{4d^2}\\Vert C_S-C_T \\Vert^2_F
Inputs:
- f_s (tensor): feature representations on source domain, :math:`f^s`
- f_t (tensor): feature representations on target domain, :math:`f^t`
Shape:
- f_s, f_t: :math:`(N, d)` where d means the dimension of input features, :math:`N=n_S=n_T` is mini-batch size.
- Outputs: scalar.
"""
def __init__(self):
super(CorrelationAlignmentLoss, self).__init__()
def forward(self, f_s: 'torch.Tensor', f_t: 'torch.Tensor') ->torch.Tensor:
mean_s = f_s.mean(0, keepdim=True)
mean_t = f_t.mean(0, keepdim=True)
cent_s = f_s - mean_s
cent_t = f_t - mean_t
cov_s = torch.mm(cent_s.t(), cent_s) / (len(f_s) - 1)
cov_t = torch.mm(cent_t.t(), cent_t) / (len(f_t) - 1)
mean_diff = (mean_s - mean_t).pow(2).mean()
cov_diff = (cov_s - cov_t).pow(2).mean()
return mean_diff + cov_diff
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_pow_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr0 + (4 + r0), None)
tmp3 = tl.load(in_ptr0 + (8 + r0), None)
tmp5 = tl.load(in_ptr0 + (12 + r0), None)
tmp9 = tl.load(in_ptr1 + r0, None)
tmp10 = tl.load(in_ptr1 + (4 + r0), None)
tmp12 = tl.load(in_ptr1 + (8 + r0), None)
tmp14 = tl.load(in_ptr1 + (12 + r0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp11 = tmp9 + tmp10
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp16 = tmp15 / tmp7
tmp17 = tmp8 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp21 = tl.sum(tmp19, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp21, None)
@triton.jit
def triton_poi_fused_mean_sub_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_per_fused_add_div_mean_pow_sub_2(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)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp10 = tl.load(in_out_ptr0 + 0)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, 1])
tmp1 = 0.3333333333333333
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 - tmp4
tmp6 = tmp5 * tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = 16.0
tmp15 = tmp9 / tmp14
tmp16 = tmp13 + tmp15
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp16, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_mean_pow_sub_0[grid(1)](arg0_1, arg1_1, buf0, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mean_sub_1[grid(16)](arg0_1, buf1, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (4, 4), (1, 4), 0), buf1,
out=buf2)
buf3 = buf1
del buf1
triton_poi_fused_mean_sub_1[grid(16)](arg1_1, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg1_1
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (4, 4), (1, 4), 0), buf3,
out=buf4)
del buf3
buf6 = buf0
del buf0
triton_per_fused_add_div_mean_pow_sub_2[grid(1)](buf6, buf2, buf4,
1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf2
del buf4
return buf6,
class CorrelationAlignmentLossNew(nn.Module):
"""The `Correlation Alignment Loss` in
`Deep CORAL: Correlation Alignment for Deep Domain Adaptation (ECCV 2016) <https://arxiv.org/pdf/1607.01719.pdf>`_.
Given source features :math:`f_S` and target features :math:`f_T`, the covariance matrices are given by
.. math::
C_S = \\frac{1}{n_S-1}(f_S^Tf_S-\\frac{1}{n_S}(\\textbf{1}^Tf_S)^T(\\textbf{1}^Tf_S))
.. math::
C_T = \\frac{1}{n_T-1}(f_T^Tf_T-\\frac{1}{n_T}(\\textbf{1}^Tf_T)^T(\\textbf{1}^Tf_T))
where :math:`\\textbf{1}` denotes a column vector with all elements equal to 1, :math:`n_S, n_T` denotes number of
source and target samples, respectively. We use :math:`d` to denote feature dimension, use
:math:`{\\Vert\\cdot\\Vert}^2_F` to denote the squared matrix `Frobenius norm`. The correlation alignment loss is
given by
.. math::
l_{CORAL} = \\frac{1}{4d^2}\\Vert C_S-C_T \\Vert^2_F
Inputs:
- f_s (tensor): feature representations on source domain, :math:`f^s`
- f_t (tensor): feature representations on target domain, :math:`f^t`
Shape:
- f_s, f_t: :math:`(N, d)` where d means the dimension of input features, :math:`N=n_S=n_T` is mini-batch size.
- Outputs: scalar.
"""
def __init__(self):
super(CorrelationAlignmentLossNew, 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]
|
neka-nat/Transfer-Learning-Library
|
CorrelationAlignmentLoss
| false
| 16,152
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
Accuracy
|
from torch.nn import Module
import torch
from torch import Tensor
class Accuracy(Module):
"""
Class for calculating the accuracy for a given prediction and the labels
for comparison.
Expects the inputs to be from a range of 0 to 1 and sets a crossing threshold at 0.5
the labels are similarly rounded.
"""
def forward(self, pred: 'Tensor', lab: 'Tensor') ->Tensor:
"""
:param pred: the models prediction to compare with
:param lab: the labels for the data to compare to
:return: the calculated accuracy
"""
return Accuracy.calculate(pred, lab)
@staticmethod
def calculate(pred: 'Tensor', lab: 'Tensor'):
"""
:param pred: the models prediction to compare with
:param lab: the labels for the data to compare to
:return: the calculated accuracy
"""
pred = pred >= 0.5
lab = lab >= 0.5
correct = (pred == lab).sum()
total = lab.numel()
acc = correct.float() / total * 100.0
return acc
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.nn import Module
from torch import Tensor
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused__to_copy_div_eq_ge_mul_sum_0(in_ptr0, in_ptr1,
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)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 0.5
tmp2 = tmp0 >= tmp1
tmp4 = tmp3 >= tmp1
tmp5 = tmp2 == tmp4
tmp6 = tmp5.to(tl.int64)
tmp7 = tl.broadcast_to(tmp6, [RBLOCK])
tmp9 = triton_helpers.promote_to_tensor(tl.sum(tmp7, 0))
tmp10 = tmp9.to(tl.float32)
tmp11 = 0.00390625
tmp12 = tmp10 * tmp11
tmp13 = 100.0
tmp14 = tmp12 * tmp13
tl.store(out_ptr1 + tl.full([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)
buf1 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused__to_copy_div_eq_ge_mul_sum_0[grid(1)](arg0_1,
arg1_1, buf1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class AccuracyNew(Module):
"""
Class for calculating the accuracy for a given prediction and the labels
for comparison.
Expects the inputs to be from a range of 0 to 1 and sets a crossing threshold at 0.5
the labels are similarly rounded.
"""
@staticmethod
def calculate(pred: 'Tensor', lab: 'Tensor'):
"""
:param pred: the models prediction to compare with
:param lab: the labels for the data to compare to
:return: the calculated accuracy
"""
pred = pred >= 0.5
lab = lab >= 0.5
correct = (pred == lab).sum()
total = lab.numel()
acc = correct.float() / total * 100.0
return acc
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
neuralmagic/sparseml
|
Accuracy
| false
| 16,153
|
[
"Apache-2.0"
] | 922
|
3fe5f4d75796eba43508401de4070cb494370683
|
https://github.com/neuralmagic/sparseml/tree/3fe5f4d75796eba43508401de4070cb494370683
|
DiceLoss
|
import torch
import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self, smooth=0, eps=1e-07):
super(DiceLoss, self).__init__()
self.smooth = smooth
self.eps = eps
def forward(self, output, target):
return 1 - (2 * torch.sum(output * target) + self.smooth) / (torch.
sum(output) + torch.sum(target) + self.smooth + self.eps)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mul_rsub_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)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp6 = tl.broadcast_to(tmp0, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = tl.broadcast_to(tmp1, [RBLOCK])
tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0))
tmp12 = 2.0
tmp13 = tmp5 * tmp12
tmp14 = 0.0
tmp15 = tmp13 + tmp14
tmp16 = tmp8 + tmp11
tmp17 = tmp16 + tmp14
tmp18 = 1e-07
tmp19 = tmp17 + tmp18
tmp20 = tmp15 / tmp19
tmp21 = 1.0
tmp22 = tmp21 - tmp20
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp22, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mul_rsub_sum_0[grid(1)](buf3, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf3,
class DiceLossNew(nn.Module):
def __init__(self, smooth=0, eps=1e-07):
super(DiceLossNew, self).__init__()
self.smooth = smooth
self.eps = eps
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
neptune-ml/data-science-bowl-2018
|
DiceLoss
| false
| 16,154
|
[
"MIT"
] | 92
|
2f76f2fc9836e53ada16d1e084afa0108b119011
|
https://github.com/neptune-ml/data-science-bowl-2018/tree/2f76f2fc9836e53ada16d1e084afa0108b119011
|
FocalLoss
|
import torch
import torch.nn as nn
import torch.optim
class FocalLoss(torch.nn.Module):
"""Sigmoid focal cross entropy loss.
Focal loss down-weights well classified examples and focusses on the hard
examples. See https://arxiv.org/pdf/1708.02002.pdf for the loss definition.
"""
def __init__(self, gamma=2.0, alpha=0.25):
"""Constructor.
Args:
gamma: exponent of the modulating factor (1 - p_t)^gamma.
alpha: optional alpha weighting factor to balance positives vs negatives,
with alpha in [0, 1] for class 1 and 1-alpha for class 0.
In practice alpha may be set by inverse class frequency,
so that for a low number of positives, its weight is high.
"""
super(FocalLoss, self).__init__()
self._alpha = alpha
self._gamma = gamma
self.BCEWithLogits = nn.BCEWithLogitsLoss(reduction='none')
def forward(self, prediction_tensor, target_tensor):
"""Compute loss function.
Args:
prediction_tensor: A float tensor of shape [batch_size, num_anchors,
num_classes] representing the predicted logits for each class
target_tensor: A float tensor of shape [batch_size, num_anchors,
num_classes] representing one-hot encoded classification targets.
Returns:
loss: a float tensor of shape [batch_size, num_anchors, num_classes]
representing the value of the loss function.
"""
per_entry_cross_ent = self.BCEWithLogits(prediction_tensor,
target_tensor)
prediction_probabilities = torch.sigmoid(prediction_tensor)
p_t = target_tensor * prediction_probabilities + (1 - target_tensor
) * (1 - prediction_probabilities)
modulating_factor = 1.0
if self._gamma:
modulating_factor = torch.pow(1.0 - p_t, self._gamma)
alpha_weight_factor = 1.0
if self._alpha is not None:
alpha_weight_factor = target_tensor * self._alpha + (1 -
target_tensor) * (1 - self._alpha)
focal_cross_entropy_loss = (modulating_factor * alpha_weight_factor *
per_entry_cross_ent)
return torch.mean(focal_cross_entropy_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
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_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tmp4 = 1.0
tmp5 = tmp4 - tmp0
tmp6 = tmp4 - tmp2
tmp7 = tmp5 * tmp6
tmp8 = tmp3 + tmp7
tmp9 = tmp4 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = 0.25
tmp12 = tmp0 * tmp11
tmp13 = 0.75
tmp14 = tmp5 * tmp13
tmp15 = tmp12 + tmp14
tmp16 = tmp10 * tmp15
tmp17 = tmp5 * tmp1
tmp18 = 0.0
tmp19 = triton_helpers.minimum(tmp18, tmp1)
tmp20 = tl_math.abs(tmp1)
tmp21 = -tmp20
tmp22 = tl_math.exp(tmp21)
tmp23 = libdevice.log1p(tmp22)
tmp24 = tmp19 - tmp23
tmp25 = tmp17 - tmp24
tmp26 = tmp16 * tmp25
tmp27 = tl.broadcast_to(tmp26, [RBLOCK])
tmp29 = triton_helpers.promote_to_tensor(tl.sum(tmp27, 0))
tmp30 = 256.0
tmp31 = tmp29 / tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp31, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_binary_cross_entropy_with_logits_mean_mul_pow_rsub_sigmoid_0[
grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class FocalLossNew(torch.nn.Module):
"""Sigmoid focal cross entropy loss.
Focal loss down-weights well classified examples and focusses on the hard
examples. See https://arxiv.org/pdf/1708.02002.pdf for the loss definition.
"""
def __init__(self, gamma=2.0, alpha=0.25):
"""Constructor.
Args:
gamma: exponent of the modulating factor (1 - p_t)^gamma.
alpha: optional alpha weighting factor to balance positives vs negatives,
with alpha in [0, 1] for class 1 and 1-alpha for class 0.
In practice alpha may be set by inverse class frequency,
so that for a low number of positives, its weight is high.
"""
super(FocalLossNew, self).__init__()
self._alpha = alpha
self._gamma = gamma
self.BCEWithLogits = nn.BCEWithLogitsLoss(reduction='none')
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
neuralsyn/self-supervised-relational-reasoning
|
FocalLoss
| false
| 16,155
|
[
"MIT"
] | 130
|
6ecfafcf4a36c2eacef7ddd5bd1b23c28fbb14c8
|
https://github.com/neuralsyn/self-supervised-relational-reasoning/tree/6ecfafcf4a36c2eacef7ddd5bd1b23c28fbb14c8
|
StackTime
|
import torch
from torchvision.models.quantization import *
class StackTime(torch.nn.Module):
__constants__ = ['factor']
def __init__(self, factor):
super().__init__()
self.factor = int(factor)
def forward(self, x, x_lens):
r = torch.transpose(x, 0, 1)
s = r.shape
zeros = torch.zeros(s[0], -s[1] % self.factor, s[2], dtype=r.dtype,
device=r.device)
r = torch.cat([r, zeros], 1)
s = r.shape
rs = [s[0], s[1] // self.factor, s[2] * self.factor]
r = torch.reshape(r, rs)
rt = torch.transpose(r, 0, 1)
x_lens = torch.ceil(x_lens.float() / self.factor).int()
return rt, x_lens
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'factor': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torchvision.models.quantization import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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__to_copy_ceil_div_1(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.25
tmp2 = tmp0 * tmp1
tmp3 = libdevice.ceil(tmp2)
tmp4 = tmp3.to(tl.int32)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 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_clone_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int32)
triton_poi_fused__to_copy_ceil_div_1[grid(256)](arg1_1, buf1, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
return reinterpret_tensor(buf0, (1, 4, 16), (16, 16, 1), 0), buf1
class StackTimeNew(torch.nn.Module):
__constants__ = ['factor']
def __init__(self, factor):
super().__init__()
self.factor = int(factor)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
mlperf/inference
|
StackTime
| false
| 16,156
|
[
"Apache-2.0"
] | 388
|
b284212941bcce7a558813c31ba2d356bac71885
|
https://github.com/mlperf/inference/tree/b284212941bcce7a558813c31ba2d356bac71885
|
SVHN_Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SVHN_Net(nn.Module):
def __init__(self):
super(SVHN_Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 32, kernel_size=3)
self.conv3 = nn.Conv2d(32, 32, kernel_size=3)
self.conv3_drop = nn.Dropout2d()
self.fc1 = nn.Linear(1152, 400)
self.fc2 = nn.Linear(400, 50)
self.fc3 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(F.max_pool2d(self.conv2(x), 2))
x = F.relu(F.max_pool2d(self.conv3_drop(self.conv3(x)), 2))
x = x.view(-1, 1152)
x = F.relu(self.fc1(x))
e1 = F.relu(self.fc2(x))
x = F.dropout(e1, training=self.training)
x = self.fc3(x)
return x, e1
def get_embedding_dim(self):
return 50
def get_inputs():
return [torch.rand([4, 3, 32, 32])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 115200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 900 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 784 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_2(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 25088
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 14
x1 = xindex // 14
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 56 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 56 * x1), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (28 + 2 * x0 + 56 * x1), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (29 + 2 * x0 + 56 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tmp17 = tl.full([1], 0, tl.int32)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp18, xmask)
@triton.jit
def triton_poi_fused_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 144 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_threshold_backward_4(in_ptr0,
out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 4608
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 24 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 24 * x1), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (12 + 2 * x0 + 24 * x1), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (13 + 2 * x0 + 24 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tmp17 = tl.full([1], 0, tl.int32)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp19 = 0.0
tmp20 = tmp18 <= tmp19
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp18, xmask)
tl.store(out_ptr2 + x2, tmp20, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 400
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 50
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (32, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 32, 32), (3072, 1024, 32, 1))
assert_size_stride(primals_4, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (400, 1152), (1152, 1))
assert_size_stride(primals_9, (400,), (1,))
assert_size_stride(primals_10, (50, 400), (400, 1))
assert_size_stride(primals_11, (50,), (1,))
assert_size_stride(primals_12, (10, 50), (50, 1))
assert_size_stride(primals_13, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 30, 30), (28800, 900, 30, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(115200)](buf1, primals_2,
115200, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 28, 28), (25088, 784, 28, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(100352)](buf3, primals_5,
100352, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 32, 14, 14), (6272, 196, 14, 1),
torch.int8)
buf5 = empty_strided_cuda((4, 32, 14, 14), (6272, 196, 14, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_relu_2[grid(25088)](buf3,
buf4, buf5, 25088, XBLOCK=128, num_warps=4, num_stages=1)
buf6 = extern_kernels.convolution(buf5, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 32, 12, 12), (4608, 144, 12, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_3[grid(18432)](buf7, primals_7, 18432,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf8 = empty_strided_cuda((4, 32, 6, 6), (1152, 36, 6, 1), torch.int8)
buf9 = empty_strided_cuda((4, 32, 6, 6), (1152, 36, 6, 1), torch.
float32)
buf15 = empty_strided_cuda((4, 32, 6, 6), (1152, 36, 6, 1), torch.bool)
triton_poi_fused_max_pool2d_with_indices_relu_threshold_backward_4[grid
(4608)](buf7, buf8, buf9, buf15, 4608, XBLOCK=128, num_warps=4,
num_stages=1)
buf10 = empty_strided_cuda((4, 400), (400, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf9, (4, 1152), (1152, 1), 0),
reinterpret_tensor(primals_8, (1152, 400), (1, 1152), 0), out=buf10
)
buf11 = buf10
del buf10
triton_poi_fused_relu_5[grid(1600)](buf11, primals_9, 1600, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((4, 50), (50, 1), torch.float32)
extern_kernels.mm(buf11, reinterpret_tensor(primals_10, (400, 50),
(1, 400), 0), out=buf12)
buf13 = buf12
del buf12
triton_poi_fused_relu_6[grid(200)](buf13, primals_11, 200, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_11
buf14 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_13, buf13, reinterpret_tensor(
primals_12, (50, 10), (1, 50), 0), alpha=1, beta=1, out=buf14)
del primals_13
return (buf14, buf13, primals_1, primals_3, primals_4, primals_6, buf1,
buf3, buf4, buf5, buf7, buf8, reinterpret_tensor(buf9, (4, 1152), (
1152, 1), 0), buf11, buf13, primals_12, primals_10, primals_8, buf15)
class SVHN_NetNew(nn.Module):
def __init__(self):
super(SVHN_NetNew, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 32, kernel_size=3)
self.conv3 = nn.Conv2d(32, 32, kernel_size=3)
self.conv3_drop = nn.Dropout2d()
self.fc1 = nn.Linear(1152, 400)
self.fc2 = nn.Linear(400, 50)
self.fc3 = nn.Linear(50, 10)
def get_embedding_dim(self):
return 50
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.fc1.weight
primals_9 = self.fc1.bias
primals_10 = self.fc2.weight
primals_11 = self.fc2.bias
primals_12 = self.fc3.weight
primals_13 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0], output[1]
|
nannullna/deep-active-learning
|
SVHN_Net
| false
| 16,157
|
[
"MIT"
] | 465
|
c54a995640c63ba4679129c5a1fd5cec9a2858e6
|
https://github.com/nannullna/deep-active-learning/tree/c54a995640c63ba4679129c5a1fd5cec9a2858e6
|
TripletLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms.functional as F
import torch.utils.data
def hard_examples_mining(dist_mat, identity_mat, return_idxes=False):
"""Select hard positives and hard negatives according to `In defense of the Triplet Loss for Person
Re-Identification (ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_
Args:
dist_mat (tensor): pairwise distance matrix between two sets of features
identity_mat (tensor): a matrix of shape :math:`(N, M)`. If two images :math:`P[i]` of set :math:`P` and
:math:`Q[j]` of set :math:`Q` come from the same person, then :math:`identity\\_mat[i, j] = 1`,
otherwise :math:`identity\\_mat[i, j] = 0`
return_idxes (bool, optional): if True, also return indexes of hard examples. Default: False
"""
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + -10000000.0 * (1 -
identity_mat), dim=1, descending=True)
dist_ap = sorted_dist_mat[:, 0]
hard_positive_idxes = sorted_idxes[:, 0]
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + 10000000.0 *
identity_mat, dim=1, descending=False)
dist_an = sorted_dist_mat[:, 0]
hard_negative_idxes = sorted_idxes[:, 0]
if return_idxes:
return dist_ap, dist_an, hard_positive_idxes, hard_negative_idxes
return dist_ap, dist_an
def pairwise_euclidean_distance(x, y):
"""Compute pairwise euclidean distance between two sets of features"""
m, n = x.size(0), y.size(0)
dist_mat = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) + torch.pow(y,
2).sum(1, keepdim=True).expand(n, m).t() - 2 * torch.matmul(x, y.t())
dist_mat = dist_mat.clamp(min=1e-12).sqrt()
return dist_mat
class TripletLoss(nn.Module):
"""Triplet loss augmented with batch hard from `In defense of the Triplet Loss for Person Re-Identification
(ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_.
Args:
margin (float): margin of triplet loss
normalize_feature (bool, optional): if True, normalize features into unit norm first before computing loss.
Default: False.
"""
def __init__(self, margin, normalize_feature=False):
super(TripletLoss, self).__init__()
self.margin = margin
self.normalize_feature = normalize_feature
self.margin_loss = nn.MarginRankingLoss(margin=margin)
def forward(self, f, labels):
if self.normalize_feature:
f = F.normalize(f)
dist_mat = pairwise_euclidean_distance(f, f)
n = dist_mat.size(0)
identity_mat = labels.expand(n, n).eq(labels.expand(n, n).t()).float()
dist_ap, dist_an = hard_examples_mining(dist_mat, identity_mat)
y = torch.ones_like(dist_ap)
loss = self.margin_loss(dist_an, dist_ap, y)
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'margin': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__to_copy_add_clamp_eq_mul_rsub_sort_sqrt_sub_0(in_out_ptr0
, in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex
r1 = rindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + 4 * r1, None, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr0 + (1 + 4 * r1), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (2 + 4 * r1), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr0 + (3 + 4 * r1), None, eviction_policy='evict_last')
tmp23 = tl.load(in_out_ptr0 + (r1 + 4 * x0), xmask, other=0.0)
tmp30 = tl.load(in_ptr1 + (r1 + 4 * x0), xmask, other=0.0)
tmp31 = tl.load(in_ptr1 + (x0 + 4 * r1), xmask, other=0.0)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp12 = tmp11 * tmp11
tmp14 = tmp13 * tmp13
tmp15 = tmp12 + tmp14
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp10 + tmp21
tmp24 = 2.0
tmp25 = tmp23 * tmp24
tmp26 = tmp22 - tmp25
tmp27 = 1e-12
tmp28 = triton_helpers.maximum(tmp26, tmp27)
tmp29 = libdevice.sqrt(tmp28)
tmp32 = tmp30 == tmp31
tmp33 = tmp32.to(tl.float32)
tmp34 = 1.0
tmp35 = tmp34 - tmp33
tmp36 = -10000000.0
tmp37 = tmp35 * tmp36
tmp38 = tmp29 + tmp37
tmp39 = r1
tmp40 = tmp39.to(tl.int16)
tmp41 = tl.broadcast_to(tmp38, [XBLOCK, RBLOCK])
tmp42 = tl.broadcast_to(tmp40, [XBLOCK, RBLOCK])
tmp43, _tmp44 = triton_helpers.sort_with_index(tmp41, tmp42, None, 1,
stable=False, descending=True)
tmp45 = 10000000.0
tmp46 = tmp33 * tmp45
tmp47 = tmp29 + tmp46
tmp48 = tl.broadcast_to(tmp47, [XBLOCK, RBLOCK])
tmp49, _tmp50 = triton_helpers.sort_with_index(tmp48, tmp42, None, 1,
stable=False, descending=False)
tl.store(in_out_ptr0 + (r1 + 4 * x0), tmp26, xmask)
tl.store(out_ptr0 + (r1 + 4 * x0), tmp43, xmask)
tl.store(out_ptr1 + (r1 + 4 * x0), tmp49, xmask)
@triton.jit
def triton_per_fused_add_clamp_min_mean_mul_neg_sub_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp3 = -1.0
tmp4 = tmp3 * tmp2
tmp5 = 4.0
tmp6 = tmp4 + tmp5
tmp7 = 0.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.sum(tmp9, 1)[:, None]
tmp12 = tmp11 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp12, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
0), out=buf0)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__to_copy_add_clamp_eq_mul_rsub_sort_sqrt_sub_0[grid(4)
](buf1, arg0_1, arg1_1, buf2, buf4, 4, 4, XBLOCK=1, num_warps=2,
num_stages=1)
del arg0_1
del arg1_1
del buf1
buf6 = empty_strided_cuda((), (), torch.float32)
buf7 = buf6
del buf6
triton_per_fused_add_clamp_min_mean_mul_neg_sub_1[grid(1)](buf7,
buf4, buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf2
del buf4
return buf7,
def hard_examples_mining(dist_mat, identity_mat, return_idxes=False):
"""Select hard positives and hard negatives according to `In defense of the Triplet Loss for Person
Re-Identification (ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_
Args:
dist_mat (tensor): pairwise distance matrix between two sets of features
identity_mat (tensor): a matrix of shape :math:`(N, M)`. If two images :math:`P[i]` of set :math:`P` and
:math:`Q[j]` of set :math:`Q` come from the same person, then :math:`identity\\_mat[i, j] = 1`,
otherwise :math:`identity\\_mat[i, j] = 0`
return_idxes (bool, optional): if True, also return indexes of hard examples. Default: False
"""
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + -10000000.0 * (1 -
identity_mat), dim=1, descending=True)
dist_ap = sorted_dist_mat[:, 0]
hard_positive_idxes = sorted_idxes[:, 0]
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + 10000000.0 *
identity_mat, dim=1, descending=False)
dist_an = sorted_dist_mat[:, 0]
hard_negative_idxes = sorted_idxes[:, 0]
if return_idxes:
return dist_ap, dist_an, hard_positive_idxes, hard_negative_idxes
return dist_ap, dist_an
def pairwise_euclidean_distance(x, y):
"""Compute pairwise euclidean distance between two sets of features"""
m, n = x.size(0), y.size(0)
dist_mat = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) + torch.pow(y,
2).sum(1, keepdim=True).expand(n, m).t() - 2 * torch.matmul(x, y.t())
dist_mat = dist_mat.clamp(min=1e-12).sqrt()
return dist_mat
class TripletLossNew(nn.Module):
"""Triplet loss augmented with batch hard from `In defense of the Triplet Loss for Person Re-Identification
(ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_.
Args:
margin (float): margin of triplet loss
normalize_feature (bool, optional): if True, normalize features into unit norm first before computing loss.
Default: False.
"""
def __init__(self, margin, normalize_feature=False):
super(TripletLossNew, self).__init__()
self.margin = margin
self.normalize_feature = normalize_feature
self.margin_loss = nn.MarginRankingLoss(margin=margin)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
TripletLoss
| false
| 16,158
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
MockOpticalFlowModel
|
import torch
import torch.nn as nn
class MockOpticalFlowModel(nn.Module):
def __init__(self, img_channels):
super().__init__()
self.model = nn.Conv2d(img_channels * 2, 2, kernel_size=1)
def forward(self, img1, img2):
x = torch.cat([img1, img2], dim=-3)
return self.model(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'img_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_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask,
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 2
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (2, 8, 1, 1), (8, 1, 1, 1))
assert_size_stride(primals_4, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](primals_1, primals_2, buf0, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = extern_kernels.convolution(buf0, primals_3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 2, 4, 4), (32, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(128)](buf2, primals_4, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_4
return buf2, primals_3, buf0
class MockOpticalFlowModelNew(nn.Module):
def __init__(self, img_channels):
super().__init__()
self.model = nn.Conv2d(img_channels * 2, 2, kernel_size=1)
def forward(self, input_0, input_1):
primals_3 = self.model.weight
primals_4 = self.model.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
neu-vig/ezflow
|
MockOpticalFlowModel
| false
| 16,159
|
[
"MIT"
] | 94
|
1eb6f675e72b1de6db7b35d61ca4ef0082bae890
|
https://github.com/neu-vig/ezflow/tree/1eb6f675e72b1de6db7b35d61ca4ef0082bae890
|
Softplus
|
import torch
import torch.onnx
import torch.nn as nn
class Softplus(nn.Module):
def forward(self, x):
return torch.nn.Softplus()(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.onnx
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_softplus_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = 20.0
tmp4 = tmp2 > tmp3
tmp5 = tl_math.exp(tmp2)
tmp6 = libdevice.log1p(tmp5)
tmp7 = tmp6 * tmp1
tmp8 = tl.where(tmp4, tmp0, tmp7)
tl.store(out_ptr0 + x0, tmp8, xmask)
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_softplus_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SoftplusNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
mil-tokyo/webdnn
|
Softplus
| false
| 16,160
|
[
"MIT"
] | 1,967
|
38a60fd3e1a4e72bc01108189a3aa51e0752aecd
|
https://github.com/mil-tokyo/webdnn/tree/38a60fd3e1a4e72bc01108189a3aa51e0752aecd
|
RepresentationSubspaceDistance
|
import torch
import torch.nn as nn
import torch.utils.data
class RepresentationSubspaceDistance(nn.Module):
"""
`Representation Subspace Distance (ICML 2021) <http://ise.thss.tsinghua.edu.cn/~mlong/doc/Representation-Subspace-Distance-for-Domain-Adaptation-Regression-icml21.pdf>`_
Args:
trade_off (float): The trade-off value between Representation Subspace Distance
and Base Mismatch Penalization. Default: 0.1
Inputs:
- f_s (tensor): feature representations on source domain, :math:`f^s`
- f_t (tensor): feature representations on target domain, :math:`f^t`
"""
def __init__(self, trade_off=0.1):
super(RepresentationSubspaceDistance, self).__init__()
self.trade_off = trade_off
def forward(self, f_s, f_t):
U_s, _, _ = torch.svd(f_s.t())
U_t, _, _ = torch.svd(f_t.t())
P_s, cosine, P_t = torch.svd(torch.mm(U_s.t(), U_t))
sine = torch.sqrt(1 - torch.pow(cosine, 2))
rsd = torch.norm(sine, 1)
bmp = torch.norm(torch.abs(P_s) - torch.abs(P_t), 2)
return rsd + self.trade_off * bmp
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_linalg_vector_norm_pow_rsub_sqrt_0(in_ptr0, out_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tmp0 * tmp0
tmp2 = 1.0
tmp3 = tmp2 - tmp1
tmp4 = libdevice.sqrt(tmp3)
tmp5 = tl_math.abs(tmp4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None)
@triton.jit
def triton_per_fused_abs_add_linalg_vector_norm_mul_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)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp9 = tl.load(in_out_ptr0 + 0)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, 1])
tmp1 = tl_math.abs(tmp0)
tmp3 = tl_math.abs(tmp2)
tmp4 = tmp1 - tmp3
tmp5 = tmp4 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tmp11 = libdevice.sqrt(tmp8)
tmp12 = 0.1
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + 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, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten._linalg_svd.default(reinterpret_tensor(arg0_1,
(4, 4), (1, 4), 0))
del arg0_1
buf1 = buf0[0]
del buf0
buf4 = torch.ops.aten._linalg_svd.default(reinterpret_tensor(arg1_1,
(4, 4), (1, 4), 0))
del arg1_1
buf5 = buf4[0]
del buf4
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (4, 4), (4, 1), 0), buf5,
out=buf8)
del buf1
del buf5
buf9 = torch.ops.aten._linalg_svd.default(buf8)
del buf8
buf10 = buf9[0]
buf11 = buf9[1]
buf12 = buf9[2]
del buf9
buf13 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_linalg_vector_norm_pow_rsub_sqrt_0[grid(1)](buf11,
buf13, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf11
buf15 = buf13
del buf13
triton_per_fused_abs_add_linalg_vector_norm_mul_sub_1[grid(1)](buf15,
buf10, buf12, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf10
del buf12
return buf15,
class RepresentationSubspaceDistanceNew(nn.Module):
"""
`Representation Subspace Distance (ICML 2021) <http://ise.thss.tsinghua.edu.cn/~mlong/doc/Representation-Subspace-Distance-for-Domain-Adaptation-Regression-icml21.pdf>`_
Args:
trade_off (float): The trade-off value between Representation Subspace Distance
and Base Mismatch Penalization. Default: 0.1
Inputs:
- f_s (tensor): feature representations on source domain, :math:`f^s`
- f_t (tensor): feature representations on target domain, :math:`f^t`
"""
def __init__(self, trade_off=0.1):
super(RepresentationSubspaceDistanceNew, self).__init__()
self.trade_off = trade_off
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
RepresentationSubspaceDistance
| false
| 16,161
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
CMul
|
import torch
import torch.nn
import torch.nn as nn
import torch.nn.parallel
class CMul(nn.Module):
"""
nn.CMul in Torch7.
"""
def __init__(self):
super(CMul, self).__init__()
def forward(self, x):
return x[0] * x[1]
def __repr__(self):
return self.__class__.__name__
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0), xmask)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class CMulNew(nn.Module):
"""
nn.CMul in Torch7.
"""
def __init__(self):
super(CMulNew, self).__init__()
def __repr__(self):
return self.__class__.__name__
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nhonth/DeLF-pytorch
|
CMul
| false
| 16,162
|
[
"MIT"
] | 315
|
5577a447a0330b9e976cff56a10fc91669216b8c
|
https://github.com/nhonth/DeLF-pytorch/tree/5577a447a0330b9e976cff56a10fc91669216b8c
|
BesselBasis
|
import math
import torch
import torch.jit
import torch.nn.functional
from torch import nn
import torch.nn
import torch.utils.data
class BesselBasis(nn.Module):
r_max: 'float'
prefactor: 'float'
def __init__(self, r_max, num_basis=8, trainable=True):
"""Radial Bessel Basis, as proposed in DimeNet: https://arxiv.org/abs/2003.03123
Parameters
----------
r_max : float
Cutoff radius
num_basis : int
Number of Bessel Basis functions
trainable : bool
Train the :math:`n \\pi` part or not.
"""
super(BesselBasis, self).__init__()
self.trainable = trainable
self.num_basis = num_basis
self.r_max = float(r_max)
self.prefactor = 2.0 / self.r_max
bessel_weights = torch.linspace(start=1.0, end=num_basis, steps=
num_basis) * math.pi
if self.trainable:
self.bessel_weights = nn.Parameter(bessel_weights)
else:
self.register_buffer('bessel_weights', bessel_weights)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
"""
Evaluate Bessel Basis for input x.
Parameters
----------
x : torch.Tensor
Input
"""
numerator = torch.sin(self.bessel_weights * x.unsqueeze(-1) / self.
r_max)
return self.prefactor * (numerator / x.unsqueeze(-1))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'r_max': 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 math as tl_math
import math
import torch.jit
import torch.nn.functional
from torch import nn
import torch.nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_mul_sin_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 0.25
tmp4 = tmp2 * tmp3
tmp5 = tl_math.sin(tmp4)
tmp6 = tmp5 / tmp1
tmp7 = 0.5
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (8,), (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, 8), (512, 128, 32, 8, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_div_mul_sin_0[grid(2048)](primals_1, primals_2,
buf0, 2048, XBLOCK=256, num_warps=4, num_stages=1)
return buf0, primals_1, primals_2
class BesselBasisNew(nn.Module):
r_max: 'float'
prefactor: 'float'
def __init__(self, r_max, num_basis=8, trainable=True):
"""Radial Bessel Basis, as proposed in DimeNet: https://arxiv.org/abs/2003.03123
Parameters
----------
r_max : float
Cutoff radius
num_basis : int
Number of Bessel Basis functions
trainable : bool
Train the :math:`n \\pi` part or not.
"""
super(BesselBasisNew, self).__init__()
self.trainable = trainable
self.num_basis = num_basis
self.r_max = float(r_max)
self.prefactor = 2.0 / self.r_max
bessel_weights = torch.linspace(start=1.0, end=num_basis, steps=
num_basis) * math.pi
if self.trainable:
self.bessel_weights = nn.Parameter(bessel_weights)
else:
self.register_buffer('bessel_weights', bessel_weights)
def forward(self, input_0):
primals_1 = self.bessel_weights
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
mir-group/nequip
|
BesselBasis
| false
| 16,163
|
[
"MIT"
] | 153
|
4e6a0914a289cf000da57a6b6e79678efdf3347f
|
https://github.com/mir-group/nequip/tree/4e6a0914a289cf000da57a6b6e79678efdf3347f
|
PriorDiscriminator
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
class PriorDiscriminator(nn.Module):
"""The prior discriminator class.
This discriminate between a vector drawn from random uniform,
and the vector y obtained as output of the encoder.
It enforces y to be close to a uniform distribution.
"""
def __init__(self, y_size):
super().__init__()
self.l0 = nn.Linear(y_size, 512)
self.l1 = nn.Linear(512, 128)
self.l2 = nn.Linear(128, 1)
def forward(self, x):
h = F.relu(self.l0(x))
h = F.relu(self.l1(h))
return torch.sigmoid(self.l2(h))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'y_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.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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 % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_sigmoid_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (512, 4), (4, 1))
assert_size_stride(primals_2, (512,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (128, 512), (512, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (1, 128), (128, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 512), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 512), (8192, 2048, 512, 1), 0
)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 512), (8192, 2048, 512, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(32768)](buf1,
primals_2, buf7, 32768, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 512), (512, 1), 0),
reinterpret_tensor(primals_4, (512, 128), (1, 512), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf2
buf6 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(8192)](buf3,
primals_5, buf6, 8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_6, (128, 1), (1, 128), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf4
triton_poi_fused_sigmoid_2[grid(64)](buf5, primals_7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_7
return buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 512), (512, 1), 0
), reinterpret_tensor(buf3, (64, 128), (128, 1), 0
), buf5, primals_6, buf6, primals_4, buf7
class PriorDiscriminatorNew(nn.Module):
"""The prior discriminator class.
This discriminate between a vector drawn from random uniform,
and the vector y obtained as output of the encoder.
It enforces y to be close to a uniform distribution.
"""
def __init__(self, y_size):
super().__init__()
self.l0 = nn.Linear(y_size, 512)
self.l1 = nn.Linear(512, 128)
self.l2 = nn.Linear(128, 1)
def forward(self, input_0):
primals_1 = self.l0.weight
primals_2 = self.l0.bias
primals_4 = self.l1.weight
primals_5 = self.l1.bias
primals_6 = self.l2.weight
primals_7 = self.l2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
neuralsyn/self-supervised-relational-reasoning
|
PriorDiscriminator
| false
| 16,164
|
[
"MIT"
] | 130
|
6ecfafcf4a36c2eacef7ddd5bd1b23c28fbb14c8
|
https://github.com/neuralsyn/self-supervised-relational-reasoning/tree/6ecfafcf4a36c2eacef7ddd5bd1b23c28fbb14c8
|
MaskedMSE
|
import torch
import torch.nn as nn
class MaskedMSE(nn.Module):
def __init__(self):
super(MaskedMSE, self).__init__()
self.criterion = nn.MSELoss()
def forward(self, input, target, mask):
self.loss = self.criterion(input, target * mask)
return self.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
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_mse_loss_mul_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tl.load(in_ptr2 + r0, None)
tmp3 = tmp1 * tmp2
tmp4 = tmp0 - tmp3
tmp5 = tmp4 * tmp4
tmp6 = tl.broadcast_to(tmp5, [RBLOCK])
tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
tmp9 = 256.0
tmp10 = tmp8 / tmp9
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp10, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mse_loss_mul_0[grid(1)](buf1, arg2_1, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf1,
class MaskedMSENew(nn.Module):
def __init__(self):
super(MaskedMSENew, self).__init__()
self.criterion = nn.MSELoss()
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]
|
ngerstle/soccerontable
|
MaskedMSE
| false
| 16,165
|
[
"BSD-2-Clause"
] | 465
|
25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c
|
https://github.com/ngerstle/soccerontable/tree/25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c
|
MaskedBCE
|
import torch
import torch.nn as nn
class MaskedBCE(nn.Module):
def __init__(self):
super(MaskedBCE, self).__init__()
self.criterion = nn.BCELoss()
def forward(self, input, target, mask):
self.loss = self.criterion(input, target * mask)
return self.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 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_mul_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp5 = tl.load(in_ptr2 + r0, None)
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 - tmp3
tmp6 = -tmp5
tmp7 = libdevice.log1p(tmp6)
tmp8 = -100.0
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tmp4 * tmp9
tmp11 = tl_math.log(tmp5)
tmp12 = triton_helpers.maximum(tmp11, tmp8)
tmp13 = tmp2 * tmp12
tmp14 = tmp10 - tmp13
tmp15 = tl.broadcast_to(tmp14, [RBLOCK])
tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0))
tmp18 = 256.0
tmp19 = tmp17 / tmp18
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp19, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_mul_0[grid(1)](buf1, arg0_1,
arg1_1, arg2_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf1,
class MaskedBCENew(nn.Module):
def __init__(self):
super(MaskedBCENew, self).__init__()
self.criterion = nn.BCELoss()
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]
|
ngerstle/soccerontable
|
MaskedBCE
| false
| 16,166
|
[
"BSD-2-Clause"
] | 465
|
25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c
|
https://github.com/ngerstle/soccerontable/tree/25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c
|
PSAModule
|
import torch
from torch import nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1,
dilation=1, groups=1):
"""standard convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride
=stride, padding=padding, dilation=dilation, groups=groups, bias=False)
class SEWeightModule(nn.Module):
def __init__(self, channels, reduction=16):
super(SEWeightModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,
padding=0)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,
padding=0)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
out = self.avg_pool(x)
out = self.fc1(out)
out = self.relu(out)
out = self.fc2(out)
weight = self.sigmoid(out)
return weight
class PSAModule(nn.Module):
def __init__(self, inplans, planes, conv_kernels=[3, 5, 7, 9], stride=1,
conv_groups=[1, 4, 8, 16]):
super(PSAModule, self).__init__()
self.conv_1 = conv(inplans, planes // 4, kernel_size=conv_kernels[0
], padding=conv_kernels[0] // 2, stride=stride, groups=
conv_groups[0])
self.conv_2 = conv(inplans, planes // 4, kernel_size=conv_kernels[1
], padding=conv_kernels[1] // 2, stride=stride, groups=
conv_groups[1])
self.conv_3 = conv(inplans, planes // 4, kernel_size=conv_kernels[2
], padding=conv_kernels[2] // 2, stride=stride, groups=
conv_groups[2])
self.conv_4 = conv(inplans, planes // 4, kernel_size=conv_kernels[3
], padding=conv_kernels[3] // 2, stride=stride, groups=
conv_groups[3])
self.se = SEWeightModule(planes // 4)
self.split_channel = planes // 4
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
batch_size = x.shape[0]
x1 = self.conv_1(x)
x2 = self.conv_2(x)
x3 = self.conv_3(x)
x4 = self.conv_4(x)
feats = torch.cat((x1, x2, x3, x4), dim=1)
feats = feats.view(batch_size, 4, self.split_channel, feats.shape[2
], feats.shape[3])
x1_se = self.se(x1)
x2_se = self.se(x2)
x3_se = self.se(x3)
x4_se = self.se(x4)
x_se = torch.cat((x1_se, x2_se, x3_se, x4_se), dim=1)
attention_vectors = x_se.view(batch_size, 4, self.split_channel, 1, 1)
attention_vectors = self.softmax(attention_vectors)
feats_weight = feats * attention_vectors
for i in range(4):
x_se_weight_fp = feats_weight[:, i, :, :]
if i == 0:
out = x_se_weight_fp
else:
out = torch.cat((x_se_weight_fp, out), 1)
return out
def get_inputs():
return [torch.rand([4, 64, 64, 64])]
def get_init_inputs():
return [[], {'inplans': 64, 'planes': 64}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 64
x0 = xindex % 4096
x2 = xindex // 262144
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], 32, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (x0 + 4096 * (-16 + x1) + 65536 * x2), tmp9,
other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 48, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr2 + (x0 + 4096 * (-32 + x1) + 65536 * x2), tmp14,
other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 64, tl.int64)
tmp19 = tl.load(in_ptr3 + (x0 + 4096 * (-48 + x1) + 65536 * x2), tmp16,
other=0.0)
tmp20 = tl.where(tmp14, tmp15, tmp19)
tmp21 = tl.where(tmp9, tmp10, tmp20)
tmp22 = tl.where(tmp4, tmp5, tmp21)
tl.store(out_ptr0 + x3, tmp22, None)
@triton.jit
def triton_red_fused_mean_1(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 64
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
_tmp2 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = _tmp2 + tmp1
_tmp2 = tl.where(rmask & xmask, tmp3, _tmp2)
tmp2 = tl.sum(_tmp2, 1)[:, None]
tmp4 = 4096.0
tmp5 = tmp2 / tmp4
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_out_ptr1,
in_out_ptr2, in_out_ptr3, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp6 = tl.load(in_out_ptr1 + x0, xmask)
tmp9 = tl.load(in_out_ptr2 + x0, xmask)
tmp12 = tl.load(in_out_ptr3 + x0, xmask)
tmp3 = tmp0 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp7 = tmp6 + tmp2
tmp8 = triton_helpers.maximum(tmp4, tmp7)
tmp10 = tmp9 + tmp2
tmp11 = triton_helpers.maximum(tmp4, tmp10)
tmp13 = tmp12 + tmp2
tmp14 = triton_helpers.maximum(tmp4, tmp13)
tl.store(in_out_ptr0 + x0, tmp5, xmask)
tl.store(in_out_ptr1 + x0, tmp8, xmask)
tl.store(in_out_ptr2 + x0, tmp11, xmask)
tl.store(in_out_ptr3 + x0, tmp14, xmask)
@triton.jit
def triton_poi_fused_convolution_3(in_out_ptr0, in_out_ptr1, in_out_ptr2,
in_out_ptr3, 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 % 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr1 + x2, xmask)
tmp5 = tl.load(in_out_ptr2 + x2, xmask)
tmp7 = tl.load(in_out_ptr3 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp3 + tmp1
tmp6 = tmp5 + tmp1
tmp8 = tmp7 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(in_out_ptr1 + x2, tmp4, xmask)
tl.store(in_out_ptr2 + x2, tmp6, xmask)
tl.store(in_out_ptr3 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x1 = xindex // 64
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 16, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (16 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.sigmoid(tmp5)
tmp7 = tl.full(tmp6.shape, 0.0, tmp6.dtype)
tmp8 = tl.where(tmp4, tmp6, tmp7)
tmp9 = tmp0 >= tmp3
tmp10 = tl.full([1], 32, tl.int64)
tmp11 = tmp0 < tmp10
tmp12 = tmp9 & tmp11
tmp13 = tl.load(in_ptr1 + (16 * x1 + (-16 + x0)), tmp12 & xmask,
eviction_policy='evict_last', other=0.0)
tmp14 = tl.sigmoid(tmp13)
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp12, tmp14, tmp15)
tmp17 = tmp0 >= tmp10
tmp18 = tl.full([1], 48, tl.int64)
tmp19 = tmp0 < tmp18
tmp20 = tmp17 & tmp19
tmp21 = tl.load(in_ptr2 + (16 * x1 + (-32 + x0)), tmp20 & xmask,
eviction_policy='evict_last', other=0.0)
tmp22 = tl.sigmoid(tmp21)
tmp23 = tl.full(tmp22.shape, 0.0, tmp22.dtype)
tmp24 = tl.where(tmp20, tmp22, tmp23)
tmp25 = tmp0 >= tmp18
tl.full([1], 64, tl.int64)
tmp28 = tl.load(in_ptr3 + (16 * x1 + (-48 + x0)), tmp25 & xmask,
eviction_policy='evict_last', other=0.0)
tmp29 = tl.sigmoid(tmp28)
tmp30 = tl.full(tmp29.shape, 0.0, tmp29.dtype)
tmp31 = tl.where(tmp25, tmp29, tmp30)
tmp32 = tl.where(tmp20, tmp24, tmp31)
tmp33 = tl.where(tmp12, tmp16, tmp32)
tmp34 = tl.where(tmp4, tmp8, tmp33)
tl.store(out_ptr0 + x2, tmp34, 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
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_6(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_7(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 64
x0 = xindex % 4096
x2 = xindex // 262144
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 + (196608 + x0 + 4096 * x1 + 262144 * x2), tmp4,
other=0.0)
tmp6 = tl.load(in_ptr1 + (48 + 64 * x2 + x1), tmp4, eviction_policy=
'evict_last', other=0.0)
tmp7 = tmp5 * tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 64, tl.int64)
tmp13 = -16 + x1
tmp15 = tmp13 < tmp3
tmp16 = tmp15 & tmp10
tmp17 = tl.load(in_ptr0 + (131072 + x0 + 4096 * (-16 + x1) + 262144 *
x2), tmp16, other=0.0)
tmp18 = tl.load(in_ptr1 + (32 + 64 * x2 + (-16 + x1)), tmp16,
eviction_policy='evict_last', other=0.0)
tmp19 = tmp17 * tmp18
tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype)
tmp21 = tl.where(tmp16, tmp19, tmp20)
tmp22 = tmp13 >= tmp3
tl.full([1], 48, tl.int64)
tmp25 = tmp22 & tmp10
tmp26 = -16 + (-16 + x1)
tmp28 = tmp26 < tmp3
tmp29 = tmp28 & tmp25
tmp30 = tl.load(in_ptr0 + (65536 + x0 + 4096 * (-16 + (-16 + x1)) +
262144 * x2), tmp29, other=0.0)
tmp31 = tl.load(in_ptr1 + (16 + 64 * x2 + (-16 + (-16 + x1))), tmp29,
eviction_policy='evict_last', other=0.0)
tmp32 = tmp30 * tmp31
tmp33 = tl.full(tmp32.shape, 0.0, tmp32.dtype)
tmp34 = tl.where(tmp29, tmp32, tmp33)
tmp35 = tmp26 >= tmp3
tl.full([1], 32, tl.int64)
tmp38 = tmp35 & tmp25
tmp39 = tl.load(in_ptr0 + (x0 + 4096 * (-16 + (-16 + (-16 + x1))) +
262144 * x2), tmp38, other=0.0)
tmp40 = tl.load(in_ptr1 + (64 * x2 + (-16 + (-16 + (-16 + x1)))), tmp38,
eviction_policy='evict_last', other=0.0)
tmp41 = tmp39 * tmp40
tmp42 = tl.full(tmp41.shape, 0.0, tmp41.dtype)
tmp43 = tl.where(tmp38, tmp41, tmp42)
tmp44 = tl.where(tmp28, tmp34, tmp43)
tmp45 = tl.full(tmp44.shape, 0.0, tmp44.dtype)
tmp46 = tl.where(tmp25, tmp44, tmp45)
tmp47 = tl.where(tmp15, tmp21, tmp46)
tmp48 = tl.full(tmp47.shape, 0.0, tmp47.dtype)
tmp49 = tl.where(tmp10, tmp47, tmp48)
tmp50 = tl.where(tmp4, tmp9, tmp49)
tl.store(out_ptr0 + x3, tmp50, None)
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, 64, 64, 64), (262144, 4096, 64, 1))
assert_size_stride(primals_2, (16, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_3, (16, 16, 5, 5), (400, 25, 5, 1))
assert_size_stride(primals_4, (16, 8, 7, 7), (392, 49, 7, 1))
assert_size_stride(primals_5, (16, 4, 9, 9), (324, 81, 9, 1))
assert_size_stride(primals_6, (1, 16, 1, 1), (16, 1, 1, 1))
assert_size_stride(primals_7, (1,), (1,))
assert_size_stride(primals_8, (16, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_9, (16,), (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, 16, 64, 64), (65536, 4096, 64, 1))
buf1 = extern_kernels.convolution(primals_1, primals_3, stride=(1,
1), padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf1, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf2 = extern_kernels.convolution(primals_1, primals_4, stride=(1,
1), padding=(3, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=8, bias=None)
assert_size_stride(buf2, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf3 = extern_kernels.convolution(primals_1, primals_5, stride=(1,
1), padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=16, bias=None)
assert_size_stride(buf3, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf4 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(1048576)](buf0, buf1, buf2, buf3, buf4,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 64, 64), torch.float32
)
buf6 = reinterpret_tensor(buf5, (4, 16, 1, 1), (16, 1, 1, 1), 0)
del buf5
triton_red_fused_mean_1[grid(64)](buf6, buf0, 64, 4096, XBLOCK=1,
RBLOCK=2048, num_warps=16, num_stages=1)
del buf0
buf7 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 1, 1, 1), (1, 1, 1, 1))
buf11 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 64, 64), torch.
float32)
buf12 = reinterpret_tensor(buf11, (4, 16, 1, 1), (16, 1, 1, 1), 0)
del buf11
triton_red_fused_mean_1[grid(64)](buf12, buf1, 64, 4096, XBLOCK=1,
RBLOCK=2048, num_warps=16, num_stages=1)
del buf1
buf13 = extern_kernels.convolution(buf12, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (4, 1, 1, 1), (1, 1, 1, 1))
buf17 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 64, 64), torch.
float32)
buf18 = reinterpret_tensor(buf17, (4, 16, 1, 1), (16, 1, 1, 1), 0)
del buf17
triton_red_fused_mean_1[grid(64)](buf18, buf2, 64, 4096, XBLOCK=1,
RBLOCK=2048, num_warps=16, num_stages=1)
del buf2
buf19 = extern_kernels.convolution(buf18, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 1, 1, 1), (1, 1, 1, 1))
buf23 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 64, 64), torch.
float32)
buf24 = reinterpret_tensor(buf23, (4, 16, 1, 1), (16, 1, 1, 1), 0)
del buf23
triton_red_fused_mean_1[grid(64)](buf24, buf3, 64, 4096, XBLOCK=1,
RBLOCK=2048, num_warps=16, num_stages=1)
del buf3
buf25 = extern_kernels.convolution(buf24, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf25, (4, 1, 1, 1), (1, 1, 1, 1))
buf8 = buf7
del buf7
buf14 = buf13
del buf13
buf20 = buf19
del buf19
buf26 = buf25
del buf25
triton_poi_fused_convolution_relu_2[grid(4)](buf8, buf14, buf20,
buf26, primals_7, 4, XBLOCK=4, num_warps=1, num_stages=1)
del primals_7
buf9 = extern_kernels.convolution(buf8, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 16, 1, 1), (16, 1, 1, 1))
buf15 = extern_kernels.convolution(buf14, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf15, (4, 16, 1, 1), (16, 1, 1, 1))
buf21 = extern_kernels.convolution(buf20, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf21, (4, 16, 1, 1), (16, 1, 1, 1))
buf27 = extern_kernels.convolution(buf26, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 16, 1, 1), (16, 1, 1, 1))
buf10 = buf9
del buf9
buf16 = buf15
del buf15
buf22 = buf21
del buf21
buf28 = buf27
del buf27
triton_poi_fused_convolution_3[grid(64)](buf10, buf16, buf22, buf28,
primals_9, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf29 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 1, 1), torch.float32)
triton_poi_fused_cat_4[grid(256)](buf10, buf16, buf22, buf28, buf29,
256, XBLOCK=128, num_warps=4, num_stages=1)
buf30 = empty_strided_cuda((4, 4, 16, 1, 1), (64, 16, 1, 256, 256),
torch.float32)
triton_poi_fused__softmax_5[grid(256)](buf29, buf30, 256, XBLOCK=
128, num_warps=4, num_stages=1)
buf31 = empty_strided_cuda((4, 4, 16, 1, 1), (64, 16, 1, 256, 256),
torch.float32)
triton_poi_fused__softmax_6[grid(256)](buf30, buf31, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf30
buf32 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_7[grid(1048576)](buf4, buf31, buf32, 1048576,
XBLOCK=1024, num_warps=4, num_stages=1)
del buf31
return (buf32, primals_1, primals_2, primals_3, primals_4, primals_5,
primals_6, primals_8, buf4, buf6, buf8, buf10, buf12, buf14, buf16,
buf18, buf20, buf22, buf24, buf26, buf28, buf29)
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1,
dilation=1, groups=1):
"""standard convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride
=stride, padding=padding, dilation=dilation, groups=groups, bias=False)
class SEWeightModule(nn.Module):
def __init__(self, channels, reduction=16):
super(SEWeightModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,
padding=0)
self.relu = nn.ReLU(inplace=True)
self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,
padding=0)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
out = self.avg_pool(x)
out = self.fc1(out)
out = self.relu(out)
out = self.fc2(out)
weight = self.sigmoid(out)
return weight
class PSAModuleNew(nn.Module):
def __init__(self, inplans, planes, conv_kernels=[3, 5, 7, 9], stride=1,
conv_groups=[1, 4, 8, 16]):
super(PSAModuleNew, self).__init__()
self.conv_1 = conv(inplans, planes // 4, kernel_size=conv_kernels[0
], padding=conv_kernels[0] // 2, stride=stride, groups=
conv_groups[0])
self.conv_2 = conv(inplans, planes // 4, kernel_size=conv_kernels[1
], padding=conv_kernels[1] // 2, stride=stride, groups=
conv_groups[1])
self.conv_3 = conv(inplans, planes // 4, kernel_size=conv_kernels[2
], padding=conv_kernels[2] // 2, stride=stride, groups=
conv_groups[2])
self.conv_4 = conv(inplans, planes // 4, kernel_size=conv_kernels[3
], padding=conv_kernels[3] // 2, stride=stride, groups=
conv_groups[3])
self.se = SEWeightModule(planes // 4)
self.split_channel = planes // 4
self.softmax = nn.Softmax(dim=1)
def forward(self, input_0):
primals_2 = self.conv_1.weight
primals_3 = self.conv_2.weight
primals_4 = self.conv_3.weight
primals_5 = self.conv_4.weight
primals_6 = self.se.fc1.weight
primals_7 = self.se.fc1.bias
primals_8 = self.se.fc2.weight
primals_9 = self.se.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
murufeng/EPSANet
|
PSAModule
| false
| 16,167
|
[
"MIT"
] | 120
|
9955041a1db4591fae080d2e6edb25e2a2914d47
|
https://github.com/murufeng/EPSANet/tree/9955041a1db4591fae080d2e6edb25e2a2914d47
|
TripletLossXBM
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms.functional as F
import torch.utils.data
def hard_examples_mining(dist_mat, identity_mat, return_idxes=False):
"""Select hard positives and hard negatives according to `In defense of the Triplet Loss for Person
Re-Identification (ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_
Args:
dist_mat (tensor): pairwise distance matrix between two sets of features
identity_mat (tensor): a matrix of shape :math:`(N, M)`. If two images :math:`P[i]` of set :math:`P` and
:math:`Q[j]` of set :math:`Q` come from the same person, then :math:`identity\\_mat[i, j] = 1`,
otherwise :math:`identity\\_mat[i, j] = 0`
return_idxes (bool, optional): if True, also return indexes of hard examples. Default: False
"""
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + -10000000.0 * (1 -
identity_mat), dim=1, descending=True)
dist_ap = sorted_dist_mat[:, 0]
hard_positive_idxes = sorted_idxes[:, 0]
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + 10000000.0 *
identity_mat, dim=1, descending=False)
dist_an = sorted_dist_mat[:, 0]
hard_negative_idxes = sorted_idxes[:, 0]
if return_idxes:
return dist_ap, dist_an, hard_positive_idxes, hard_negative_idxes
return dist_ap, dist_an
def pairwise_euclidean_distance(x, y):
"""Compute pairwise euclidean distance between two sets of features"""
m, n = x.size(0), y.size(0)
dist_mat = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) + torch.pow(y,
2).sum(1, keepdim=True).expand(n, m).t() - 2 * torch.matmul(x, y.t())
dist_mat = dist_mat.clamp(min=1e-12).sqrt()
return dist_mat
class TripletLossXBM(nn.Module):
"""Triplet loss augmented with batch hard from `In defense of the Triplet Loss for Person Re-Identification
(ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_. The only difference from triplet loss lies in that
both features from current mini batch and external storage (XBM) are involved.
Args:
margin (float, optional): margin of triplet loss. Default: 0.3
normalize_feature (bool, optional): if True, normalize features into unit norm first before computing loss.
Default: False
Inputs:
- f (tensor): features of current mini batch, :math:`f`
- labels (tensor): identity labels for current mini batch, :math:`labels`
- xbm_f (tensor): features collected from XBM, :math:`xbm\\_f`
- xbm_labels (tensor): corresponding identity labels of xbm_f, :math:`xbm\\_labels`
Shape:
- f: :math:`(minibatch, F)`, where :math:`F` is the feature dimension
- labels: :math:`(minibatch, )`
- xbm_f: :math:`(minibatch, F)`
- xbm_labels: :math:`(minibatch, )`
"""
def __init__(self, margin=0.3, normalize_feature=False):
super(TripletLossXBM, self).__init__()
self.margin = margin
self.normalize_feature = normalize_feature
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
def forward(self, f, labels, xbm_f, xbm_labels):
if self.normalize_feature:
f = F.normalize(f)
xbm_f = F.normalize(xbm_f)
dist_mat = pairwise_euclidean_distance(f, xbm_f)
n, m = f.size(0), xbm_f.size(0)
identity_mat = labels.expand(m, n).t().eq(xbm_labels.expand(n, m)
).float()
dist_ap, dist_an = hard_examples_mining(dist_mat, identity_mat)
y = torch.ones_like(dist_an)
loss = self.ranking_loss(dist_an, dist_ap, y)
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4]),
torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__to_copy_add_clamp_eq_mul_rsub_sort_sqrt_sub_0(in_out_ptr0
, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex
r1 = rindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + 4 * r1, None, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + (1 + 4 * r1), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr1 + (2 + 4 * r1), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr1 + (3 + 4 * r1), None, eviction_policy='evict_last')
tmp23 = tl.load(in_out_ptr0 + (r1 + 4 * x0), xmask, other=0.0)
tmp30 = tl.load(in_ptr2 + (x0 + 4 * r1), xmask, other=0.0)
tmp31 = tl.load(in_ptr3 + (r1 + 4 * x0), xmask, other=0.0)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp12 = tmp11 * tmp11
tmp14 = tmp13 * tmp13
tmp15 = tmp12 + tmp14
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp10 + tmp21
tmp24 = 2.0
tmp25 = tmp23 * tmp24
tmp26 = tmp22 - tmp25
tmp27 = 1e-12
tmp28 = triton_helpers.maximum(tmp26, tmp27)
tmp29 = libdevice.sqrt(tmp28)
tmp32 = tmp30 == tmp31
tmp33 = tmp32.to(tl.float32)
tmp34 = 1.0
tmp35 = tmp34 - tmp33
tmp36 = -10000000.0
tmp37 = tmp35 * tmp36
tmp38 = tmp29 + tmp37
tmp39 = r1
tmp40 = tmp39.to(tl.int16)
tmp41 = tl.broadcast_to(tmp38, [XBLOCK, RBLOCK])
tmp42 = tl.broadcast_to(tmp40, [XBLOCK, RBLOCK])
tmp43, _tmp44 = triton_helpers.sort_with_index(tmp41, tmp42, None, 1,
stable=False, descending=True)
tmp45 = 10000000.0
tmp46 = tmp33 * tmp45
tmp47 = tmp29 + tmp46
tmp48 = tl.broadcast_to(tmp47, [XBLOCK, RBLOCK])
tmp49, _tmp50 = triton_helpers.sort_with_index(tmp48, tmp42, None, 1,
stable=False, descending=False)
tl.store(in_out_ptr0 + (r1 + 4 * x0), tmp26, xmask)
tl.store(out_ptr0 + (r1 + 4 * x0), tmp43, xmask)
tl.store(out_ptr1 + (r1 + 4 * x0), tmp49, xmask)
@triton.jit
def triton_per_fused_add_clamp_min_mean_mul_neg_sub_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp3 = -1.0
tmp4 = tmp3 * tmp2
tmp5 = 0.3
tmp6 = tmp4 + tmp5
tmp7 = 0.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.sum(tmp9, 1)[:, None]
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4), (4, 1))
assert_size_stride(arg3_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg0_1, reinterpret_tensor(arg1_1, (4, 4), (1, 4),
0), out=buf0)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__to_copy_add_clamp_eq_mul_rsub_sort_sqrt_sub_0[grid(4)
](buf1, arg0_1, arg1_1, arg2_1, arg3_1, buf2, buf4, 4, 4,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
del buf1
buf6 = empty_strided_cuda((), (), torch.float32)
buf7 = buf6
del buf6
triton_per_fused_add_clamp_min_mean_mul_neg_sub_1[grid(1)](buf7,
buf4, buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf2
del buf4
return buf7,
def hard_examples_mining(dist_mat, identity_mat, return_idxes=False):
"""Select hard positives and hard negatives according to `In defense of the Triplet Loss for Person
Re-Identification (ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_
Args:
dist_mat (tensor): pairwise distance matrix between two sets of features
identity_mat (tensor): a matrix of shape :math:`(N, M)`. If two images :math:`P[i]` of set :math:`P` and
:math:`Q[j]` of set :math:`Q` come from the same person, then :math:`identity\\_mat[i, j] = 1`,
otherwise :math:`identity\\_mat[i, j] = 0`
return_idxes (bool, optional): if True, also return indexes of hard examples. Default: False
"""
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + -10000000.0 * (1 -
identity_mat), dim=1, descending=True)
dist_ap = sorted_dist_mat[:, 0]
hard_positive_idxes = sorted_idxes[:, 0]
sorted_dist_mat, sorted_idxes = torch.sort(dist_mat + 10000000.0 *
identity_mat, dim=1, descending=False)
dist_an = sorted_dist_mat[:, 0]
hard_negative_idxes = sorted_idxes[:, 0]
if return_idxes:
return dist_ap, dist_an, hard_positive_idxes, hard_negative_idxes
return dist_ap, dist_an
def pairwise_euclidean_distance(x, y):
"""Compute pairwise euclidean distance between two sets of features"""
m, n = x.size(0), y.size(0)
dist_mat = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) + torch.pow(y,
2).sum(1, keepdim=True).expand(n, m).t() - 2 * torch.matmul(x, y.t())
dist_mat = dist_mat.clamp(min=1e-12).sqrt()
return dist_mat
class TripletLossXBMNew(nn.Module):
"""Triplet loss augmented with batch hard from `In defense of the Triplet Loss for Person Re-Identification
(ICCV 2017) <https://arxiv.org/pdf/1703.07737v2.pdf>`_. The only difference from triplet loss lies in that
both features from current mini batch and external storage (XBM) are involved.
Args:
margin (float, optional): margin of triplet loss. Default: 0.3
normalize_feature (bool, optional): if True, normalize features into unit norm first before computing loss.
Default: False
Inputs:
- f (tensor): features of current mini batch, :math:`f`
- labels (tensor): identity labels for current mini batch, :math:`labels`
- xbm_f (tensor): features collected from XBM, :math:`xbm\\_f`
- xbm_labels (tensor): corresponding identity labels of xbm_f, :math:`xbm\\_labels`
Shape:
- f: :math:`(minibatch, F)`, where :math:`F` is the feature dimension
- labels: :math:`(minibatch, )`
- xbm_f: :math:`(minibatch, F)`
- xbm_labels: :math:`(minibatch, )`
"""
def __init__(self, margin=0.3, normalize_feature=False):
super(TripletLossXBMNew, self).__init__()
self.margin = margin
self.normalize_feature = normalize_feature
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
def forward(self, input_0, input_1, input_2, input_3):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0]
|
neka-nat/Transfer-Learning-Library
|
TripletLossXBM
| false
| 16,168
|
[
"MIT"
] | 1,474
|
a3b27b0d7562fa90a02e914140b37ab438469e6c
|
https://github.com/neka-nat/Transfer-Learning-Library/tree/a3b27b0d7562fa90a02e914140b37ab438469e6c
|
FeatExemplarAvgBlock
|
import torch
import torch.nn as nn
import torch.optim
import torch.nn.parallel
class FeatExemplarAvgBlock(nn.Module):
def __init__(self, nFeat):
super(FeatExemplarAvgBlock, self).__init__()
def forward(self, features_train, labels_train):
labels_train_transposed = labels_train.transpose(1, 2)
weight_novel = torch.bmm(labels_train_transposed, features_train)
weight_novel = weight_novel.div(labels_train_transposed.sum(dim=2,
keepdim=True).expand_as(weight_novel))
return weight_novel
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'nFeat': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.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_div_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
x2 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(in_out_ptr0 + x3, tmp8, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 4, 4), (16, 1, 4),
0), arg1_1, out=buf0)
del arg1_1
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_div_0[grid(64)](buf1, arg0_1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf1,
class FeatExemplarAvgBlockNew(nn.Module):
def __init__(self, nFeat):
super(FeatExemplarAvgBlockNew, 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]
|
nikran1/Few_shot
|
FeatExemplarAvgBlock
| false
| 16,169
|
[
"MIT"
] | 497
|
5298c98e208411e44ee7767e6f4d457006d373cb
|
https://github.com/nikran1/Few_shot/tree/5298c98e208411e44ee7767e6f4d457006d373cb
|
ResidualConnection
|
import torch
from torch import nn
class ResidualConnection(nn.Module):
def __init__(self, alpha=0.5):
super(ResidualConnection, self).__init__()
self.alpha = alpha
def forward(self, Xs: 'list'):
assert len(Xs) >= 1
return Xs[-1] if len(Xs) == 1 else (1 - self.alpha) * Xs[-1
] + self.alpha * Xs[-2]
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, 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 + (192 + x0), xmask)
tmp3 = tl.load(in_ptr0 + (128 + x0), xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 + tmp4
tl.store(out_ptr0 + x0, tmp5, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class ResidualConnectionNew(nn.Module):
def __init__(self, alpha=0.5):
super(ResidualConnectionNew, self).__init__()
self.alpha = alpha
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
ngohienduong/Deep_GCN_Benchmarking
|
ResidualConnection
| false
| 16,170
|
[
"MIT"
] | 70
|
3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
https://github.com/ngohienduong/Deep_GCN_Benchmarking/tree/3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
mean_norm
|
import torch
class mean_norm(torch.nn.Module):
def __init__(self):
super(mean_norm, self).__init__()
def forward(self, x):
col_mean = x.mean(dim=0)
x = x - col_mean
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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mean_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
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class mean_normNew(torch.nn.Module):
def __init__(self):
super(mean_normNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
ngohienduong/Deep_GCN_Benchmarking
|
mean_norm
| false
| 16,171
|
[
"MIT"
] | 70
|
3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
https://github.com/ngohienduong/Deep_GCN_Benchmarking/tree/3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
LocalDiscriminator
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
class LocalDiscriminator(nn.Module):
"""The local discriminator class.
A network that analyses the relation between the
output of the encoder y, and the feature map M.
It is called "local" because it compares y with
each one of the features in M. So if M is a [64, 6, 6]
feature map, and y is a [32] vector, the comparison is
done concatenating y along each one of the 6x6 features
in M:
(i) [32] -> [64, 1, 1]; (ii) [32] -> [64, 1, 2]
... (xxxvi) [32] -> [64, 6, 6].
This can be efficiently done expanding y to have same
dimensionality as M such that:
[32] torch.expand -> [32, 6, 6]
and then concatenate on the channel dimension:
[32, 6, 6] torch.cat(axis=0) -> [64, 6, 6] = [96, 6, 6]
The tensor is then feed to the local discriminator.
"""
def __init__(self, y_size, M_channels):
super().__init__()
self.c0 = nn.Conv2d(y_size + M_channels, 256, kernel_size=1)
self.c1 = nn.Conv2d(256, 256, kernel_size=1)
self.c2 = nn.Conv2d(256, 1, kernel_size=1)
def forward(self, x):
h = F.relu(self.c0(x))
h = F.relu(self.c1(h))
return self.c2(h)
def get_inputs():
return [torch.rand([4, 8, 64, 64])]
def get_init_inputs():
return [[], {'y_size': 4, 'M_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 32
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 % 8
y1 = yindex // 8
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 8 * x2 + 32768 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (256, 8, 1, 1), (8, 1, 1, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 8, 64, 64), (32768, 4096, 64, 1))
assert_size_stride(primals_4, (256, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_5, (256,), (1,))
assert_size_stride(primals_6, (1, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 64, 64), (32768, 1, 512, 8), torch
.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(32, 4096)](primals_3, buf0, 32, 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, 256, 64, 64), (1048576, 1, 16384, 256))
buf2 = buf1
del buf1
triton_poi_fused_convolution_relu_1[grid(4194304)](buf2, primals_2,
4194304, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 256, 64, 64), (1048576, 1, 16384, 256))
buf4 = buf3
del buf3
triton_poi_fused_convolution_relu_1[grid(4194304)](buf4, primals_5,
4194304, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf5 = extern_kernels.convolution(buf4, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 1, 64, 64), (4096, 1, 64, 1))
buf6 = reinterpret_tensor(buf5, (4, 1, 64, 64), (4096, 4096, 64, 1), 0)
del buf5
triton_poi_fused_convolution_2[grid(16384)](buf6, primals_7, 16384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
return buf6, primals_1, buf0, primals_4, primals_6, buf2, buf4
class LocalDiscriminatorNew(nn.Module):
"""The local discriminator class.
A network that analyses the relation between the
output of the encoder y, and the feature map M.
It is called "local" because it compares y with
each one of the features in M. So if M is a [64, 6, 6]
feature map, and y is a [32] vector, the comparison is
done concatenating y along each one of the 6x6 features
in M:
(i) [32] -> [64, 1, 1]; (ii) [32] -> [64, 1, 2]
... (xxxvi) [32] -> [64, 6, 6].
This can be efficiently done expanding y to have same
dimensionality as M such that:
[32] torch.expand -> [32, 6, 6]
and then concatenate on the channel dimension:
[32, 6, 6] torch.cat(axis=0) -> [64, 6, 6] = [96, 6, 6]
The tensor is then feed to the local discriminator.
"""
def __init__(self, y_size, M_channels):
super().__init__()
self.c0 = nn.Conv2d(y_size + M_channels, 256, kernel_size=1)
self.c1 = nn.Conv2d(256, 256, kernel_size=1)
self.c2 = nn.Conv2d(256, 1, kernel_size=1)
def forward(self, input_0):
primals_1 = self.c0.weight
primals_2 = self.c0.bias
primals_4 = self.c1.weight
primals_5 = self.c1.bias
primals_6 = self.c2.weight
primals_7 = self.c2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
neuralsyn/self-supervised-relational-reasoning
|
LocalDiscriminator
| false
| 16,172
|
[
"MIT"
] | 130
|
6ecfafcf4a36c2eacef7ddd5bd1b23c28fbb14c8
|
https://github.com/neuralsyn/self-supervised-relational-reasoning/tree/6ecfafcf4a36c2eacef7ddd5bd1b23c28fbb14c8
|
LinearDiag
|
import torch
import torch.nn as nn
import torch.optim
import torch.nn.parallel
class LinearDiag(nn.Module):
def __init__(self, num_features, bias=False):
super(LinearDiag, self).__init__()
weight = torch.FloatTensor(num_features).fill_(1)
self.weight = nn.Parameter(weight, requires_grad=True)
if bias:
bias = torch.FloatTensor(num_features).fill_(0)
self.bias = nn.Parameter(bias, requires_grad=True)
else:
self.register_parameter('bias', None)
def forward(self, X):
assert X.dim() == 2 and X.size(1) == self.weight.size(0)
out = X * self.weight.expand_as(X)
if self.bias is not None:
out = out + self.bias.expand_as(out)
return out
def get_inputs():
return [torch.rand([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
import torch.nn as nn
import torch.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_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 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, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_1, primals_2, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
return buf0, primals_1
class LinearDiagNew(nn.Module):
def __init__(self, num_features, bias=False):
super(LinearDiagNew, self).__init__()
weight = torch.FloatTensor(num_features).fill_(1)
self.weight = nn.Parameter(weight, requires_grad=True)
if bias:
bias = torch.FloatTensor(num_features).fill_(0)
self.bias = nn.Parameter(bias, requires_grad=True)
else:
self.register_parameter('bias', None)
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
nikran1/Few_shot
|
LinearDiag
| false
| 16,173
|
[
"MIT"
] | 497
|
5298c98e208411e44ee7767e6f4d457006d373cb
|
https://github.com/nikran1/Few_shot/tree/5298c98e208411e44ee7767e6f4d457006d373cb
|
node_norm
|
import torch
class node_norm(torch.nn.Module):
def __init__(self, node_norm_type='n', unbiased=False, eps=1e-05,
power_root=2, **kwargs):
super(node_norm, self).__init__()
self.unbiased = unbiased
self.eps = eps
self.node_norm_type = node_norm_type
self.power = 1 / power_root
def forward(self, x):
if self.node_norm_type == 'n':
mean = torch.mean(x, dim=1, keepdim=True)
std = (torch.var(x, unbiased=self.unbiased, dim=1, keepdim=True
) + self.eps).sqrt()
x = (x - mean) / std
elif self.node_norm_type == 'v':
std = (torch.var(x, unbiased=self.unbiased, dim=1, keepdim=True
) + self.eps).sqrt()
x = x / std
elif self.node_norm_type == 'm':
mean = torch.mean(x, dim=1, keepdim=True)
x = x - mean
elif self.node_norm_type == 'srv':
std = (torch.var(x, unbiased=self.unbiased, dim=1, keepdim=True
) + self.eps).sqrt()
x = x / torch.sqrt(std)
elif self.node_norm_type == 'pr':
std = (torch.var(x, unbiased=self.unbiased, dim=1, keepdim=True
) + self.eps).sqrt()
x = x / torch.pow(std, self.power)
return x
def __repr__(self):
original_str = super().__repr__()
components = list(original_str)
node_norm_type_str = f'node_norm_type={self.node_norm_type}'
components.insert(-1, node_norm_type_str)
new_str = ''.join(components)
return new_str
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
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_sqrt_sub_var_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 = 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 = tmp21 / tmp8
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.sqrt(tmp24)
tmp26 = tmp10 / tmp25
tl.store(out_ptr0 + x3, tmp26, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mean_sqrt_sub_var_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class node_normNew(torch.nn.Module):
def __init__(self, node_norm_type='n', unbiased=False, eps=1e-05,
power_root=2, **kwargs):
super(node_normNew, self).__init__()
self.unbiased = unbiased
self.eps = eps
self.node_norm_type = node_norm_type
self.power = 1 / power_root
def __repr__(self):
original_str = super().__repr__()
components = list(original_str)
node_norm_type_str = f'node_norm_type={self.node_norm_type}'
components.insert(-1, node_norm_type_str)
new_str = ''.join(components)
return new_str
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
ngohienduong/Deep_GCN_Benchmarking
|
node_norm
| false
| 16,174
|
[
"MIT"
] | 70
|
3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
https://github.com/ngohienduong/Deep_GCN_Benchmarking/tree/3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
InitialConnection
|
import torch
from torch import nn
class InitialConnection(nn.Module):
def __init__(self, alpha=0.5):
super(InitialConnection, self).__init__()
self.alpha = alpha
def forward(self, Xs: 'list'):
assert len(Xs) >= 1
return Xs[-1] if len(Xs) == 1 else (1 - self.alpha) * Xs[-1
] + self.alpha * Xs[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 import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, 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 + (192 + x0), xmask)
tmp3 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 + tmp4
tl.store(out_ptr0 + x0, tmp5, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class InitialConnectionNew(nn.Module):
def __init__(self, alpha=0.5):
super(InitialConnectionNew, self).__init__()
self.alpha = alpha
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
ngohienduong/Deep_GCN_Benchmarking
|
InitialConnection
| false
| 16,175
|
[
"MIT"
] | 70
|
3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
https://github.com/ngohienduong/Deep_GCN_Benchmarking/tree/3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
MaskedSmoothL1
|
import torch
import torch.nn as nn
class MaskedSmoothL1(nn.Module):
def __init__(self):
super(MaskedSmoothL1, self).__init__()
self.criterion = nn.SmoothL1Loss(size_average=True)
def forward(self, input, target, mask):
self.loss = self.criterion(input, target * mask)
return self.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_per_fused_mul_smooth_l1_loss_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tl.load(in_ptr2 + r0, None)
tmp3 = tmp1 * tmp2
tmp4 = tmp0 - tmp3
tmp5 = tl_math.abs(tmp4)
tmp6 = 1.0
tmp7 = tmp5 < tmp6
tmp8 = tmp5 * tmp5
tmp9 = 0.5
tmp10 = tmp8 * tmp9
tmp11 = tmp10 * tmp6
tmp12 = tmp5 - tmp9
tmp13 = tl.where(tmp7, tmp11, tmp12)
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = 256.0
tmp18 = tmp16 / tmp17
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp18, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mul_smooth_l1_loss_0[grid(1)](buf1, arg2_1, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf1,
class MaskedSmoothL1New(nn.Module):
def __init__(self):
super(MaskedSmoothL1New, self).__init__()
self.criterion = nn.SmoothL1Loss(size_average=True)
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]
|
ngerstle/soccerontable
|
MaskedSmoothL1
| false
| 16,176
|
[
"BSD-2-Clause"
] | 465
|
25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c
|
https://github.com/ngerstle/soccerontable/tree/25426ff0f8fe0ce008b99c5c0fdbb35091d8d92c
|
Unet
|
import torch
import torch.nn as nn
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, dropout=False, norm=
'batch', residual=True, activation='leakyrelu', transpose=False):
super(ConvBlock, self).__init__()
self.dropout = dropout
self.residual = residual
self.activation = activation
self.transpose = transpose
if self.dropout:
self.dropout1 = nn.Dropout2d(p=0.05)
self.dropout2 = nn.Dropout2d(p=0.05)
self.norm1 = None
self.norm2 = None
if norm == 'batch':
self.norm1 = nn.BatchNorm2d(out_channels)
self.norm2 = nn.BatchNorm2d(out_channels)
elif norm == 'instance':
self.norm1 = nn.InstanceNorm2d(out_channels, affine=True)
self.norm2 = nn.InstanceNorm2d(out_channels, affine=True)
elif norm == 'mixed':
self.norm1 = nn.BatchNorm2d(out_channels, affine=True)
self.norm2 = nn.InstanceNorm2d(out_channels, affine=True)
if self.transpose:
self.conv1 = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size=3, padding=1)
self.conv2 = nn.ConvTranspose2d(out_channels, out_channels,
kernel_size=3, padding=1)
else:
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=
3, padding=1)
if self.activation == 'relu':
self.actfun1 = nn.ReLU()
self.actfun2 = nn.ReLU()
elif self.activation == 'leakyrelu':
self.actfun1 = nn.LeakyReLU()
self.actfun2 = nn.LeakyReLU()
elif self.activation == 'elu':
self.actfun1 = nn.ELU()
self.actfun2 = nn.ELU()
elif self.activation == 'selu':
self.actfun1 = nn.SELU()
self.actfun2 = nn.SELU()
def forward(self, x):
ox = x
x = self.conv1(x)
if self.dropout:
x = self.dropout1(x)
if self.norm1:
x = self.norm1(x)
x = self.actfun1(x)
x = self.conv2(x)
if self.dropout:
x = self.dropout2(x)
if self.norm2:
x = self.norm2(x)
if self.residual:
x[:, 0:min(ox.shape[1], x.shape[1]), :, :] += ox[:, 0:min(ox.
shape[1], x.shape[1]), :, :]
x = self.actfun2(x)
return x
class Unet(nn.Module):
def __init__(self, n_channel_in=1, n_channel_out=1, residual=False,
down='conv', up='tconv', activation='selu'):
super(Unet, self).__init__()
self.residual = residual
if down == 'maxpool':
self.down1 = nn.MaxPool2d(kernel_size=2)
self.down2 = nn.MaxPool2d(kernel_size=2)
self.down3 = nn.MaxPool2d(kernel_size=2)
self.down4 = nn.MaxPool2d(kernel_size=2)
elif down == 'avgpool':
self.down1 = nn.AvgPool2d(kernel_size=2)
self.down2 = nn.AvgPool2d(kernel_size=2)
self.down3 = nn.AvgPool2d(kernel_size=2)
self.down4 = nn.AvgPool2d(kernel_size=2)
elif down == 'conv':
self.down1 = nn.Conv2d(32, 32, kernel_size=2, stride=2, groups=32)
self.down2 = nn.Conv2d(64, 64, kernel_size=2, stride=2, groups=64)
self.down3 = nn.Conv2d(128, 128, kernel_size=2, stride=2,
groups=128)
self.down4 = nn.Conv2d(256, 256, kernel_size=2, stride=2,
groups=256)
self.down1.weight.data = 0.01 * self.down1.weight.data + 0.25
self.down2.weight.data = 0.01 * self.down2.weight.data + 0.25
self.down3.weight.data = 0.01 * self.down3.weight.data + 0.25
self.down4.weight.data = 0.01 * self.down4.weight.data + 0.25
self.down1.bias.data = 0.01 * self.down1.bias.data + 0
self.down2.bias.data = 0.01 * self.down2.bias.data + 0
self.down3.bias.data = 0.01 * self.down3.bias.data + 0
self.down4.bias.data = 0.01 * self.down4.bias.data + 0
if up == 'bilinear' or up == 'nearest':
self.up1 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
self.up2 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
self.up3 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
self.up4 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
elif up == 'tconv':
self.up1 = nn.ConvTranspose2d(256, 256, kernel_size=2, stride=2,
groups=256)
self.up2 = nn.ConvTranspose2d(128, 128, kernel_size=2, stride=2,
groups=128)
self.up3 = nn.ConvTranspose2d(64, 64, kernel_size=2, stride=2,
groups=64)
self.up4 = nn.ConvTranspose2d(32, 32, kernel_size=2, stride=2,
groups=32)
self.up1.weight.data = 0.01 * self.up1.weight.data + 0.25
self.up2.weight.data = 0.01 * self.up2.weight.data + 0.25
self.up3.weight.data = 0.01 * self.up3.weight.data + 0.25
self.up4.weight.data = 0.01 * self.up4.weight.data + 0.25
self.up1.bias.data = 0.01 * self.up1.bias.data + 0
self.up2.bias.data = 0.01 * self.up2.bias.data + 0
self.up3.bias.data = 0.01 * self.up3.bias.data + 0
self.up4.bias.data = 0.01 * self.up4.bias.data + 0
self.conv1 = ConvBlock(n_channel_in, 32, residual, activation)
self.conv2 = ConvBlock(32, 64, residual, activation)
self.conv3 = ConvBlock(64, 128, residual, activation)
self.conv4 = ConvBlock(128, 256, residual, activation)
self.conv5 = ConvBlock(256, 256, residual, activation)
self.conv6 = ConvBlock(2 * 256, 128, residual, activation)
self.conv7 = ConvBlock(2 * 128, 64, residual, activation)
self.conv8 = ConvBlock(2 * 64, 32, residual, activation)
self.conv9 = ConvBlock(2 * 32, n_channel_out, residual, activation)
if self.residual:
self.convres = ConvBlock(n_channel_in, n_channel_out, residual,
activation)
def forward(self, x):
c0 = x
c1 = self.conv1(x)
x = self.down1(c1)
c2 = self.conv2(x)
x = self.down2(c2)
c3 = self.conv3(x)
x = self.down3(c3)
c4 = self.conv4(x)
x = self.down4(c4)
x = self.conv5(x)
x = self.up1(x)
x = torch.cat([x, c4], 1)
x = self.conv6(x)
x = self.up2(x)
x = torch.cat([x, c3], 1)
x = self.conv7(x)
x = self.up3(x)
x = torch.cat([x, c2], 1)
x = self.conv8(x)
x = self.up4(x)
x = torch.cat([x, c1], 1)
x = self.conv9(x)
if self.residual:
x = torch.add(x, self.convres(c0))
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_leaky_relu_0(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 4096 % 32
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_1(in_ptr0, in_ptr1, in_ptr2,
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)
x1 = xindex // 4096 % 32
x3 = xindex
x0 = xindex % 4096
x2 = xindex // 131072
tmp21 = tl.load(in_ptr0 + x3, None)
tmp22 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 1, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tmp2 & tmp2
tmp4 = tl.load(in_ptr0 + x3, tmp3, other=0.0)
tmp5 = tl.load(in_ptr1 + x1, tmp3, eviction_policy='evict_last', other=0.0)
tmp6 = tmp4 + tmp5
tmp7 = tl.load(in_ptr2 + (x0 + 4096 * x2), tmp3, eviction_policy=
'evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp10 = tl.where(tmp3, tmp8, tmp9)
tmp11 = tl.load(in_ptr0 + x3, tmp2, other=0.0)
tmp12 = tl.load(in_ptr1 + x1, tmp2, eviction_policy='evict_last', other=0.0
)
tmp13 = tmp11 + tmp12
tmp14 = tl.where(tmp2, tmp10, tmp13)
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp2, tmp14, tmp15)
tmp17 = tl.load(in_ptr2 + (x0 + 4096 * x2), tmp2, eviction_policy=
'evict_last', other=0.0)
tmp18 = tmp13 + tmp17
tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype)
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp23 = tmp21 + tmp22
tmp24 = tl.where(tmp2, tmp20, tmp23)
tmp25 = tl.where(tmp2, tmp16, tmp24)
tmp26 = 0.0
tmp27 = tmp25 > tmp26
tmp28 = 0.01
tmp29 = tmp25 * tmp28
tmp30 = tl.where(tmp27, tmp25, tmp29)
tl.store(out_ptr0 + x3, tmp27, None)
tl.store(out_ptr1 + x3, tmp30, None)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_3(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 1024 % 64
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_4(in_ptr0, in_ptr1, in_ptr2,
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)
x1 = xindex // 1024 % 64
x3 = xindex
x2 = xindex // 65536
x4 = xindex % 65536
tmp21 = tl.load(in_ptr0 + x3, None)
tmp22 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 32, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tmp2 & tmp2
tmp4 = tl.load(in_ptr0 + x3, tmp3, other=0.0)
tmp5 = tl.load(in_ptr1 + x1, tmp3, eviction_policy='evict_last', other=0.0)
tmp6 = tmp4 + tmp5
tmp7 = tl.load(in_ptr2 + (x4 + 32768 * x2), tmp3, other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp10 = tl.where(tmp3, tmp8, tmp9)
tmp11 = tl.load(in_ptr0 + x3, tmp2, other=0.0)
tmp12 = tl.load(in_ptr1 + x1, tmp2, eviction_policy='evict_last', other=0.0
)
tmp13 = tmp11 + tmp12
tmp14 = tl.where(tmp2, tmp10, tmp13)
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp2, tmp14, tmp15)
tmp17 = tl.load(in_ptr2 + (x4 + 32768 * x2), tmp2, other=0.0)
tmp18 = tmp13 + tmp17
tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype)
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp23 = tmp21 + tmp22
tmp24 = tl.where(tmp2, tmp20, tmp23)
tmp25 = tl.where(tmp2, tmp16, tmp24)
tmp26 = 0.0
tmp27 = tmp25 > tmp26
tmp28 = 0.01
tmp29 = tmp25 * tmp28
tmp30 = tl.where(tmp27, tmp25, tmp29)
tl.store(out_ptr0 + x3, tmp27, None)
tl.store(out_ptr1 + x3, tmp30, None)
@triton.jit
def triton_poi_fused_convolution_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_6(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 256 % 128
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_7(in_ptr0, in_ptr1, in_ptr2,
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)
x1 = xindex // 256 % 128
x3 = xindex
x2 = xindex // 32768
x4 = xindex % 32768
tmp21 = tl.load(in_ptr0 + x3, None)
tmp22 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 64, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tmp2 & tmp2
tmp4 = tl.load(in_ptr0 + x3, tmp3, other=0.0)
tmp5 = tl.load(in_ptr1 + x1, tmp3, eviction_policy='evict_last', other=0.0)
tmp6 = tmp4 + tmp5
tmp7 = tl.load(in_ptr2 + (x4 + 16384 * x2), tmp3, other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp10 = tl.where(tmp3, tmp8, tmp9)
tmp11 = tl.load(in_ptr0 + x3, tmp2, other=0.0)
tmp12 = tl.load(in_ptr1 + x1, tmp2, eviction_policy='evict_last', other=0.0
)
tmp13 = tmp11 + tmp12
tmp14 = tl.where(tmp2, tmp10, tmp13)
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp2, tmp14, tmp15)
tmp17 = tl.load(in_ptr2 + (x4 + 16384 * x2), tmp2, other=0.0)
tmp18 = tmp13 + tmp17
tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype)
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp23 = tmp21 + tmp22
tmp24 = tl.where(tmp2, tmp20, tmp23)
tmp25 = tl.where(tmp2, tmp16, tmp24)
tmp26 = 0.0
tmp27 = tmp25 > tmp26
tmp28 = 0.01
tmp29 = tmp25 * tmp28
tmp30 = tl.where(tmp27, tmp25, tmp29)
tl.store(out_ptr0 + x3, tmp27, None)
tl.store(out_ptr1 + x3, tmp30, None)
@triton.jit
def triton_poi_fused_convolution_8(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_9(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 64 % 256
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_10(in_ptr0, in_ptr1,
in_ptr2, 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)
x1 = xindex // 64 % 256
x3 = xindex
x2 = xindex // 16384
x4 = xindex % 16384
tmp21 = tl.load(in_ptr0 + x3, None)
tmp22 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp0 = x1
tmp1 = tl.full([1], 128, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = tmp2 & tmp2
tmp4 = tl.load(in_ptr0 + x3, tmp3, other=0.0)
tmp5 = tl.load(in_ptr1 + x1, tmp3, eviction_policy='evict_last', other=0.0)
tmp6 = tmp4 + tmp5
tmp7 = tl.load(in_ptr2 + (x4 + 8192 * x2), tmp3, other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp10 = tl.where(tmp3, tmp8, tmp9)
tmp11 = tl.load(in_ptr0 + x3, tmp2, other=0.0)
tmp12 = tl.load(in_ptr1 + x1, tmp2, eviction_policy='evict_last', other=0.0
)
tmp13 = tmp11 + tmp12
tmp14 = tl.where(tmp2, tmp10, tmp13)
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp2, tmp14, tmp15)
tmp17 = tl.load(in_ptr2 + (x4 + 8192 * x2), tmp2, other=0.0)
tmp18 = tmp13 + tmp17
tmp19 = tl.full(tmp18.shape, 0.0, tmp18.dtype)
tmp20 = tl.where(tmp2, tmp18, tmp19)
tmp23 = tmp21 + tmp22
tmp24 = tl.where(tmp2, tmp20, tmp23)
tmp25 = tl.where(tmp2, tmp16, tmp24)
tmp26 = 0.0
tmp27 = tmp25 > tmp26
tmp28 = 0.01
tmp29 = tmp25 * tmp28
tmp30 = tl.where(tmp27, tmp25, tmp29)
tl.store(out_ptr0 + x3, tmp27, None)
tl.store(out_ptr1 + x3, tmp30, None)
@triton.jit
def triton_poi_fused_convolution_11(in_out_ptr0, in_ptr0, xnumel, XBLOCK:
tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_12(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 16 % 256
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_13(in_ptr0, in_ptr1,
in_ptr2, 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)
x3 = xindex
x1 = xindex // 16 % 256
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x3, None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = tmp4 > tmp5
tmp7 = 0.01
tmp8 = tmp4 * tmp7
tmp9 = tl.where(tmp6, tmp4, tmp8)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp9, None)
@triton.jit
def triton_poi_fused_cat_14(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 64 % 512
x0 = xindex % 64
x2 = xindex // 32768
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 256, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x1 + 16384 * x2), tmp4, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 512, tl.int64)
tmp13 = tl.load(in_ptr2 + (x0 + 64 * (-256 + x1) + 16384 * x2), tmp10,
other=0.0)
tmp14 = tl.where(tmp4, tmp9, tmp13)
tl.store(out_ptr0 + x3, tmp14, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_15(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 64 % 128
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_16(in_ptr0, in_ptr1,
in_ptr2, 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)
x3 = xindex
x1 = xindex // 64 % 128
x2 = xindex // 8192
x4 = xindex % 8192
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x4 + 32768 * x2), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = tmp4 > tmp5
tmp7 = 0.01
tmp8 = tmp4 * tmp7
tmp9 = tl.where(tmp6, tmp4, tmp8)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp9, None)
@triton.jit
def triton_poi_fused_cat_17(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 256 % 256
x0 = xindex % 256
x2 = xindex // 65536
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 128, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 256 * x1 + 32768 * x2), tmp4, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 256, tl.int64)
tmp13 = tl.load(in_ptr2 + (x0 + 256 * (-128 + x1) + 32768 * x2), tmp10,
other=0.0)
tmp14 = tl.where(tmp4, tmp9, tmp13)
tl.store(out_ptr0 + x3, tmp14, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_18(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 256 % 64
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_19(in_ptr0, in_ptr1,
in_ptr2, 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)
x3 = xindex
x1 = xindex // 256 % 64
x2 = xindex // 16384
x4 = xindex % 16384
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x4 + 65536 * x2), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = tmp4 > tmp5
tmp7 = 0.01
tmp8 = tmp4 * tmp7
tmp9 = tl.where(tmp6, tmp4, tmp8)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp9, None)
@triton.jit
def triton_poi_fused_cat_20(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 1024 % 128
x0 = xindex % 1024
x2 = xindex // 131072
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 64, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 1024 * x1 + 65536 * x2), tmp4, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 128, tl.int64)
tmp13 = tl.load(in_ptr2 + (x0 + 1024 * (-64 + x1) + 65536 * x2), tmp10,
other=0.0)
tmp14 = tl.where(tmp4, tmp9, tmp13)
tl.store(out_ptr0 + x3, tmp14, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_21(in_ptr0, in_ptr1, 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)
x3 = xindex
x1 = xindex // 1024 % 32
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, 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 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_22(in_ptr0, in_ptr1,
in_ptr2, 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)
x3 = xindex
x1 = xindex // 1024 % 32
x2 = xindex // 32768
x4 = xindex % 32768
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x4 + 131072 * x2), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = tmp4 > tmp5
tmp7 = 0.01
tmp8 = tmp4 * tmp7
tmp9 = tl.where(tmp6, tmp4, tmp8)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp9, None)
@triton.jit
def triton_poi_fused_cat_23(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 64
x0 = xindex % 4096
x2 = xindex // 262144
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 32, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 131072 * x2), tmp4, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tl.full([1], 64, tl.int64)
tmp13 = tl.load(in_ptr2 + (x0 + 4096 * (-32 + x1) + 131072 * x2), tmp10,
other=0.0)
tmp14 = tl.where(tmp4, tmp9, tmp13)
tl.store(out_ptr0 + x3, tmp14, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_24(in_ptr0, in_ptr1, 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
tmp0 = tl.load(in_ptr0 + x0, None)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = 0.0
tmp5 = tmp3 > tmp4
tmp6 = 0.01
tmp7 = tmp3 * tmp6
tmp8 = tl.where(tmp5, tmp3, tmp7)
tl.store(out_ptr0 + x0, tmp5, None)
tl.store(out_ptr1 + x0, tmp8, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_25(in_ptr0, in_ptr1,
in_ptr2, 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)
x2 = xindex
x0 = xindex % 4096
x1 = xindex // 4096
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + (x0 + 262144 * x1), None)
tmp3 = tmp0 + tmp2
tmp5 = tmp3 + tmp4
tmp6 = 0.0
tmp7 = tmp5 > tmp6
tmp8 = 0.01
tmp9 = tmp5 * tmp8
tmp10 = tl.where(tmp7, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp7, None)
tl.store(out_ptr1 + x2, tmp10, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47,
primals_48, primals_49, primals_50, primals_51, primals_52, primals_53
) = args
args.clear()
assert_size_stride(primals_1, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_2, (32, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_3, (32,), (1,))
assert_size_stride(primals_4, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_7, (32,), (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, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_11, (64,), (1,))
assert_size_stride(primals_12, (64, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_15, (128,), (1,))
assert_size_stride(primals_16, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_17, (128,), (1,))
assert_size_stride(primals_18, (128, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_19, (128,), (1,))
assert_size_stride(primals_20, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_21, (256,), (1,))
assert_size_stride(primals_22, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_23, (256,), (1,))
assert_size_stride(primals_24, (256, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_25, (256,), (1,))
assert_size_stride(primals_26, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_27, (256,), (1,))
assert_size_stride(primals_28, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_29, (256,), (1,))
assert_size_stride(primals_30, (256, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_31, (256,), (1,))
assert_size_stride(primals_32, (128, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_33, (128,), (1,))
assert_size_stride(primals_34, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_35, (128,), (1,))
assert_size_stride(primals_36, (128, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_37, (128,), (1,))
assert_size_stride(primals_38, (64, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_39, (64,), (1,))
assert_size_stride(primals_40, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_41, (64,), (1,))
assert_size_stride(primals_42, (64, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_43, (64,), (1,))
assert_size_stride(primals_44, (32, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_45, (32,), (1,))
assert_size_stride(primals_46, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_47, (32,), (1,))
assert_size_stride(primals_48, (32, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(primals_49, (32,), (1,))
assert_size_stride(primals_50, (1, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_51, (1,), (1,))
assert_size_stride(primals_52, (1, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_53, (1,), (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, 32, 64, 64), (131072, 4096, 64, 1))
buf1 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.bool)
buf2 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_leaky_relu_0[grid(524288)](buf0,
primals_3, buf1, buf2, 524288, XBLOCK=1024, num_warps=4,
num_stages=1)
del primals_3
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf4 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.bool)
buf5 = buf0
del buf0
triton_poi_fused_add_convolution_leaky_relu_1[grid(524288)](buf3,
primals_5, primals_1, buf4, buf5, 524288, XBLOCK=1024,
num_warps=4, num_stages=1)
del primals_5
buf6 = extern_kernels.convolution(buf5, primals_6, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=32, bias=None)
assert_size_stride(buf6, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_2[grid(131072)](buf7, primals_7,
131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf9 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.bool)
buf10 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.float32)
triton_poi_fused_convolution_leaky_relu_3[grid(262144)](buf8,
primals_9, buf9, buf10, 262144, XBLOCK=1024, num_warps=4,
num_stages=1)
del primals_9
buf11 = extern_kernels.convolution(buf10, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf12 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.bool)
buf13 = buf8
del buf8
triton_poi_fused_add_convolution_leaky_relu_4[grid(262144)](buf11,
primals_11, buf7, buf12, buf13, 262144, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_11
buf14 = extern_kernels.convolution(buf13, primals_12, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=64, bias=None)
assert_size_stride(buf14, (4, 64, 16, 16), (16384, 256, 16, 1))
buf15 = buf14
del buf14
triton_poi_fused_convolution_5[grid(65536)](buf15, primals_13,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_13
buf16 = extern_kernels.convolution(buf15, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 128, 16, 16), (32768, 256, 16, 1))
buf17 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf18 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.float32)
triton_poi_fused_convolution_leaky_relu_6[grid(131072)](buf16,
primals_15, buf17, buf18, 131072, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_15
buf19 = extern_kernels.convolution(buf18, primals_16, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 128, 16, 16), (32768, 256, 16, 1))
buf20 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf21 = buf16
del buf16
triton_poi_fused_add_convolution_leaky_relu_7[grid(131072)](buf19,
primals_17, buf15, buf20, buf21, 131072, XBLOCK=512, num_warps=
8, num_stages=1)
del primals_17
buf22 = extern_kernels.convolution(buf21, primals_18, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=128, bias=None)
assert_size_stride(buf22, (4, 128, 8, 8), (8192, 64, 8, 1))
buf23 = buf22
del buf22
triton_poi_fused_convolution_8[grid(32768)](buf23, primals_19,
32768, XBLOCK=256, num_warps=4, num_stages=1)
del primals_19
buf24 = extern_kernels.convolution(buf23, primals_20, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf24, (4, 256, 8, 8), (16384, 64, 8, 1))
buf25 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.bool)
buf26 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.float32)
triton_poi_fused_convolution_leaky_relu_9[grid(65536)](buf24,
primals_21, buf25, buf26, 65536, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_21
buf27 = extern_kernels.convolution(buf26, primals_22, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 256, 8, 8), (16384, 64, 8, 1))
buf28 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.bool)
buf29 = buf24
del buf24
triton_poi_fused_add_convolution_leaky_relu_10[grid(65536)](buf27,
primals_23, buf23, buf28, buf29, 65536, XBLOCK=512, num_warps=4,
num_stages=1)
del buf27
del primals_23
buf30 = extern_kernels.convolution(buf29, primals_24, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=256, bias=None)
assert_size_stride(buf30, (4, 256, 4, 4), (4096, 16, 4, 1))
buf31 = buf30
del buf30
triton_poi_fused_convolution_11[grid(16384)](buf31, primals_25,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_25
buf32 = extern_kernels.convolution(buf31, primals_26, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf32, (4, 256, 4, 4), (4096, 16, 4, 1))
buf33 = empty_strided_cuda((4, 256, 4, 4), (4096, 16, 4, 1), torch.bool
)
buf34 = empty_strided_cuda((4, 256, 4, 4), (4096, 16, 4, 1), torch.
float32)
triton_poi_fused_convolution_leaky_relu_12[grid(16384)](buf32,
primals_27, buf33, buf34, 16384, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_27
buf35 = extern_kernels.convolution(buf34, primals_28, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf35, (4, 256, 4, 4), (4096, 16, 4, 1))
buf36 = empty_strided_cuda((4, 256, 4, 4), (4096, 16, 4, 1), torch.bool
)
buf37 = buf32
del buf32
triton_poi_fused_add_convolution_leaky_relu_13[grid(16384)](buf35,
primals_29, buf31, buf36, buf37, 16384, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_29
buf38 = extern_kernels.convolution(buf37, primals_30, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=256, bias=None)
assert_size_stride(buf38, (4, 256, 8, 8), (16384, 64, 8, 1))
buf39 = reinterpret_tensor(buf19, (4, 512, 8, 8), (32768, 64, 8, 1), 0)
del buf19
triton_poi_fused_cat_14[grid(131072)](buf38, primals_31, buf29,
buf39, 131072, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_31
buf40 = extern_kernels.convolution(buf39, primals_32, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf40, (4, 128, 8, 8), (8192, 64, 8, 1))
buf41 = empty_strided_cuda((4, 128, 8, 8), (8192, 64, 8, 1), torch.bool
)
buf42 = empty_strided_cuda((4, 128, 8, 8), (8192, 64, 8, 1), torch.
float32)
triton_poi_fused_convolution_leaky_relu_15[grid(32768)](buf40,
primals_33, buf41, buf42, 32768, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_33
buf43 = extern_kernels.convolution(buf42, primals_34, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf43, (4, 128, 8, 8), (8192, 64, 8, 1))
buf44 = empty_strided_cuda((4, 128, 8, 8), (8192, 64, 8, 1), torch.bool
)
buf45 = buf40
del buf40
triton_poi_fused_add_convolution_leaky_relu_16[grid(32768)](buf43,
primals_35, buf39, buf44, buf45, 32768, XBLOCK=128, num_warps=4,
num_stages=1)
del buf43
del primals_35
buf46 = extern_kernels.convolution(buf45, primals_36, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=128, bias=None)
assert_size_stride(buf46, (4, 128, 16, 16), (32768, 256, 16, 1))
buf47 = reinterpret_tensor(buf11, (4, 256, 16, 16), (65536, 256, 16,
1), 0)
del buf11
triton_poi_fused_cat_17[grid(262144)](buf46, primals_37, buf21,
buf47, 262144, XBLOCK=512, num_warps=8, num_stages=1)
del primals_37
buf48 = extern_kernels.convolution(buf47, primals_38, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf48, (4, 64, 16, 16), (16384, 256, 16, 1))
buf49 = empty_strided_cuda((4, 64, 16, 16), (16384, 256, 16, 1),
torch.bool)
buf50 = reinterpret_tensor(buf38, (4, 64, 16, 16), (16384, 256, 16,
1), 0)
del buf38
triton_poi_fused_convolution_leaky_relu_18[grid(65536)](buf48,
primals_39, buf49, buf50, 65536, XBLOCK=512, num_warps=4,
num_stages=1)
del primals_39
buf51 = extern_kernels.convolution(buf50, primals_40, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf51, (4, 64, 16, 16), (16384, 256, 16, 1))
buf52 = empty_strided_cuda((4, 64, 16, 16), (16384, 256, 16, 1),
torch.bool)
buf53 = buf48
del buf48
triton_poi_fused_add_convolution_leaky_relu_19[grid(65536)](buf51,
primals_41, buf47, buf52, buf53, 65536, XBLOCK=256, num_warps=4,
num_stages=1)
del buf51
del primals_41
buf54 = extern_kernels.convolution(buf53, primals_42, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=64, bias=None)
assert_size_stride(buf54, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf55 = reinterpret_tensor(buf3, (4, 128, 32, 32), (131072, 1024,
32, 1), 0)
del buf3
triton_poi_fused_cat_20[grid(524288)](buf54, primals_43, buf13,
buf55, 524288, XBLOCK=512, num_warps=8, num_stages=1)
del buf54
del primals_43
buf56 = extern_kernels.convolution(buf55, primals_44, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf56, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf57 = empty_strided_cuda((4, 32, 32, 32), (32768, 1024, 32, 1),
torch.bool)
buf58 = reinterpret_tensor(buf46, (4, 32, 32, 32), (32768, 1024, 32,
1), 0)
del buf46
triton_poi_fused_convolution_leaky_relu_21[grid(131072)](buf56,
primals_45, buf57, buf58, 131072, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_45
buf59 = extern_kernels.convolution(buf58, primals_46, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf59, (4, 32, 32, 32), (32768, 1024, 32, 1))
buf60 = empty_strided_cuda((4, 32, 32, 32), (32768, 1024, 32, 1),
torch.bool)
buf61 = buf56
del buf56
triton_poi_fused_add_convolution_leaky_relu_22[grid(131072)](buf59,
primals_47, buf55, buf60, buf61, 131072, XBLOCK=1024, num_warps
=4, num_stages=1)
del buf59
del primals_47
buf62 = extern_kernels.convolution(buf61, primals_48, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=32, bias=None)
assert_size_stride(buf62, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf63 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_23[grid(1048576)](buf62, primals_49, buf5,
buf63, 1048576, XBLOCK=512, num_warps=8, num_stages=1)
del buf62
del primals_49
buf64 = extern_kernels.convolution(buf63, primals_50, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf64, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf65 = empty_strided_cuda((4, 1, 64, 64), (4096, 4096, 64, 1),
torch.bool)
buf66 = reinterpret_tensor(buf35, (4, 1, 64, 64), (4096, 4096, 64,
1), 0)
del buf35
triton_poi_fused_convolution_leaky_relu_24[grid(16384)](buf64,
primals_51, buf65, buf66, 16384, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_51
buf67 = extern_kernels.convolution(buf66, primals_52, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf67, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf68 = empty_strided_cuda((4, 1, 64, 64), (4096, 4096, 64, 1),
torch.bool)
buf69 = buf64
del buf64
triton_poi_fused_add_convolution_leaky_relu_25[grid(16384)](buf67,
primals_53, buf63, buf68, buf69, 16384, XBLOCK=128, num_warps=4,
num_stages=1)
del buf67
del primals_53
return (buf69, primals_1, primals_2, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, primals_16, primals_18,
primals_20, primals_22, primals_24, primals_26, primals_28,
primals_30, primals_32, primals_34, primals_36, primals_38,
primals_40, primals_42, primals_44, primals_46, primals_48,
primals_50, primals_52, buf1, buf2, buf4, buf5, buf7, buf9, buf10,
buf12, buf13, buf15, buf17, buf18, buf20, buf21, buf23, buf25,
buf26, buf28, buf29, buf31, buf33, buf34, buf36, buf37, buf39,
buf41, buf42, buf44, buf45, buf47, buf49, buf50, buf52, buf53,
buf55, buf57, buf58, buf60, buf61, buf63, buf65, buf66, buf68)
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, dropout=False, norm=
'batch', residual=True, activation='leakyrelu', transpose=False):
super(ConvBlock, self).__init__()
self.dropout = dropout
self.residual = residual
self.activation = activation
self.transpose = transpose
if self.dropout:
self.dropout1 = nn.Dropout2d(p=0.05)
self.dropout2 = nn.Dropout2d(p=0.05)
self.norm1 = None
self.norm2 = None
if norm == 'batch':
self.norm1 = nn.BatchNorm2d(out_channels)
self.norm2 = nn.BatchNorm2d(out_channels)
elif norm == 'instance':
self.norm1 = nn.InstanceNorm2d(out_channels, affine=True)
self.norm2 = nn.InstanceNorm2d(out_channels, affine=True)
elif norm == 'mixed':
self.norm1 = nn.BatchNorm2d(out_channels, affine=True)
self.norm2 = nn.InstanceNorm2d(out_channels, affine=True)
if self.transpose:
self.conv1 = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size=3, padding=1)
self.conv2 = nn.ConvTranspose2d(out_channels, out_channels,
kernel_size=3, padding=1)
else:
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=
3, padding=1)
if self.activation == 'relu':
self.actfun1 = nn.ReLU()
self.actfun2 = nn.ReLU()
elif self.activation == 'leakyrelu':
self.actfun1 = nn.LeakyReLU()
self.actfun2 = nn.LeakyReLU()
elif self.activation == 'elu':
self.actfun1 = nn.ELU()
self.actfun2 = nn.ELU()
elif self.activation == 'selu':
self.actfun1 = nn.SELU()
self.actfun2 = nn.SELU()
def forward(self, x):
ox = x
x = self.conv1(x)
if self.dropout:
x = self.dropout1(x)
if self.norm1:
x = self.norm1(x)
x = self.actfun1(x)
x = self.conv2(x)
if self.dropout:
x = self.dropout2(x)
if self.norm2:
x = self.norm2(x)
if self.residual:
x[:, 0:min(ox.shape[1], x.shape[1]), :, :] += ox[:, 0:min(ox.
shape[1], x.shape[1]), :, :]
x = self.actfun2(x)
return x
class UnetNew(nn.Module):
def __init__(self, n_channel_in=1, n_channel_out=1, residual=False,
down='conv', up='tconv', activation='selu'):
super(UnetNew, self).__init__()
self.residual = residual
if down == 'maxpool':
self.down1 = nn.MaxPool2d(kernel_size=2)
self.down2 = nn.MaxPool2d(kernel_size=2)
self.down3 = nn.MaxPool2d(kernel_size=2)
self.down4 = nn.MaxPool2d(kernel_size=2)
elif down == 'avgpool':
self.down1 = nn.AvgPool2d(kernel_size=2)
self.down2 = nn.AvgPool2d(kernel_size=2)
self.down3 = nn.AvgPool2d(kernel_size=2)
self.down4 = nn.AvgPool2d(kernel_size=2)
elif down == 'conv':
self.down1 = nn.Conv2d(32, 32, kernel_size=2, stride=2, groups=32)
self.down2 = nn.Conv2d(64, 64, kernel_size=2, stride=2, groups=64)
self.down3 = nn.Conv2d(128, 128, kernel_size=2, stride=2,
groups=128)
self.down4 = nn.Conv2d(256, 256, kernel_size=2, stride=2,
groups=256)
self.down1.weight.data = 0.01 * self.down1.weight.data + 0.25
self.down2.weight.data = 0.01 * self.down2.weight.data + 0.25
self.down3.weight.data = 0.01 * self.down3.weight.data + 0.25
self.down4.weight.data = 0.01 * self.down4.weight.data + 0.25
self.down1.bias.data = 0.01 * self.down1.bias.data + 0
self.down2.bias.data = 0.01 * self.down2.bias.data + 0
self.down3.bias.data = 0.01 * self.down3.bias.data + 0
self.down4.bias.data = 0.01 * self.down4.bias.data + 0
if up == 'bilinear' or up == 'nearest':
self.up1 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
self.up2 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
self.up3 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
self.up4 = lambda x: nn.functional.interpolate(x, mode=up,
scale_factor=2)
elif up == 'tconv':
self.up1 = nn.ConvTranspose2d(256, 256, kernel_size=2, stride=2,
groups=256)
self.up2 = nn.ConvTranspose2d(128, 128, kernel_size=2, stride=2,
groups=128)
self.up3 = nn.ConvTranspose2d(64, 64, kernel_size=2, stride=2,
groups=64)
self.up4 = nn.ConvTranspose2d(32, 32, kernel_size=2, stride=2,
groups=32)
self.up1.weight.data = 0.01 * self.up1.weight.data + 0.25
self.up2.weight.data = 0.01 * self.up2.weight.data + 0.25
self.up3.weight.data = 0.01 * self.up3.weight.data + 0.25
self.up4.weight.data = 0.01 * self.up4.weight.data + 0.25
self.up1.bias.data = 0.01 * self.up1.bias.data + 0
self.up2.bias.data = 0.01 * self.up2.bias.data + 0
self.up3.bias.data = 0.01 * self.up3.bias.data + 0
self.up4.bias.data = 0.01 * self.up4.bias.data + 0
self.conv1 = ConvBlock(n_channel_in, 32, residual, activation)
self.conv2 = ConvBlock(32, 64, residual, activation)
self.conv3 = ConvBlock(64, 128, residual, activation)
self.conv4 = ConvBlock(128, 256, residual, activation)
self.conv5 = ConvBlock(256, 256, residual, activation)
self.conv6 = ConvBlock(2 * 256, 128, residual, activation)
self.conv7 = ConvBlock(2 * 128, 64, residual, activation)
self.conv8 = ConvBlock(2 * 64, 32, residual, activation)
self.conv9 = ConvBlock(2 * 32, n_channel_out, residual, activation)
if self.residual:
self.convres = ConvBlock(n_channel_in, n_channel_out, residual,
activation)
def forward(self, input_0):
primals_6 = self.down1.weight
primals_3 = self.down1.bias
primals_12 = self.down2.weight
primals_9 = self.down2.bias
primals_18 = self.down3.weight
primals_15 = self.down3.bias
primals_24 = self.down4.weight
primals_21 = self.down4.bias
primals_30 = self.up1.weight
primals_23 = self.up1.bias
primals_36 = self.up2.weight
primals_17 = self.up2.bias
primals_42 = self.up3.weight
primals_11 = self.up3.bias
primals_48 = self.up4.weight
primals_5 = self.up4.bias
primals_2 = self.conv1.conv1.weight
primals_7 = self.conv1.conv1.bias
primals_4 = self.conv1.conv2.weight
primals_45 = self.conv1.conv2.bias
primals_8 = self.conv2.conv1.weight
primals_13 = self.conv2.conv1.bias
primals_10 = self.conv2.conv2.weight
primals_39 = self.conv2.conv2.bias
primals_14 = self.conv3.conv1.weight
primals_19 = self.conv3.conv1.bias
primals_16 = self.conv3.conv2.weight
primals_33 = self.conv3.conv2.bias
primals_20 = self.conv4.conv1.weight
primals_25 = self.conv4.conv1.bias
primals_22 = self.conv4.conv2.weight
primals_27 = self.conv4.conv2.bias
primals_26 = self.conv5.conv1.weight
primals_29 = self.conv5.conv1.bias
primals_28 = self.conv5.conv2.weight
primals_31 = self.conv5.conv2.bias
primals_32 = self.conv6.conv1.weight
primals_35 = self.conv6.conv1.bias
primals_34 = self.conv6.conv2.weight
primals_37 = self.conv6.conv2.bias
primals_38 = self.conv7.conv1.weight
primals_41 = self.conv7.conv1.bias
primals_40 = self.conv7.conv2.weight
primals_43 = self.conv7.conv2.bias
primals_44 = self.conv8.conv1.weight
primals_47 = self.conv8.conv1.bias
primals_46 = self.conv8.conv2.weight
primals_49 = self.conv8.conv2.bias
primals_50 = self.conv9.conv1.weight
primals_51 = self.conv9.conv1.bias
primals_52 = self.conv9.conv2.weight
primals_53 = self.conv9.conv2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
primals_40, primals_41, primals_42, primals_43, primals_44,
primals_45, primals_46, primals_47, primals_48, primals_49,
primals_50, primals_51, primals_52, primals_53])
return output[0]
|
mlepori1/noise2self
|
Unet
| false
| 16,177
|
[
"MIT"
] | 257
|
78cbda2d0f62973f1ba0232bd48a941307cf78f9
|
https://github.com/mlepori1/noise2self/tree/78cbda2d0f62973f1ba0232bd48a941307cf78f9
|
AconC
|
import torch
import torch.nn as nn
class AconC(nn.Module):
""" ACON activation (activate or not).
# AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
# according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
"""
def __init__(self, width):
super().__init__()
self.p1 = nn.Parameter(torch.randn(1, width, 1, 1))
self.p2 = nn.Parameter(torch.randn(1, width, 1, 1))
self.beta = nn.Parameter(torch.ones(1, width, 1, 1))
def forward(self, x):
return (self.p1 * x - self.p2 * x) * torch.sigmoid(self.beta * (
self.p1 * x - self.p2 * x)) + self.p2 * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'width': 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_add_mul_sigmoid_sub_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
x1 = xindex // 16 % 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 - tmp4
tmp7 = tmp6 * tmp5
tmp8 = tl.sigmoid(tmp7)
tmp9 = tmp5 * tmp8
tmp10 = tmp9 + tmp4
tl.store(out_ptr0 + x3, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_4, (1, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_sigmoid_sub_0[grid(256)](primals_1,
primals_2, primals_3, primals_4, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return buf0, primals_1, primals_2, primals_3, primals_4
class AconCNew(nn.Module):
""" ACON activation (activate or not).
# AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
# according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
"""
def __init__(self, width):
super().__init__()
self.p1 = nn.Parameter(torch.randn(1, width, 1, 1))
self.p2 = nn.Parameter(torch.randn(1, width, 1, 1))
self.beta = nn.Parameter(torch.ones(1, width, 1, 1))
def forward(self, input_0):
primals_1 = self.p1
primals_3 = self.p2
primals_4 = self.beta
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
nmaac/acon
|
AconC
| false
| 16,178
|
[
"MIT"
] | 163
|
99fd67928a6ffb0543b54614303caada96c756f5
|
https://github.com/nmaac/acon/tree/99fd67928a6ffb0543b54614303caada96c756f5
|
Keypoint2DLoss
|
import torch
import torch.nn as nn
class Keypoint2DLoss(nn.Module):
def __init__(self, loss_type: 'str'='l1'):
"""
2D keypoint loss module.
Args:
loss_type (str): Choose between l1 and l2 losses.
"""
super(Keypoint2DLoss, self).__init__()
if loss_type == 'l1':
self.loss_fn = nn.L1Loss(reduction='none')
elif loss_type == 'l2':
self.loss_fn = nn.MSELoss(reduction='none')
else:
raise NotImplementedError('Unsupported loss function')
def forward(self, pred_keypoints_2d: 'torch.Tensor', gt_keypoints_2d:
'torch.Tensor') ->torch.Tensor:
"""
Compute 2D reprojection loss on the keypoints.
Args:
pred_keypoints_2d (torch.Tensor): Tensor of shape [B, S, N, 2] containing projected 2D keypoints (B: batch_size, S: num_samples, N: num_keypoints)
gt_keypoints_2d (torch.Tensor): Tensor of shape [B, S, N, 3] containing the ground truth 2D keypoints and confidence.
Returns:
torch.Tensor: 2D keypoint loss.
"""
conf = gt_keypoints_2d[:, :, :, -1].unsqueeze(-1).clone()
conf.shape[0]
loss = (conf * self.loss_fn(pred_keypoints_2d, gt_keypoints_2d[:, :,
:, :-1])).sum(dim=(2, 3))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 3]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_clone_mul_sub_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
rnumel = 12
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r2 = rindex // 3
x0 = xindex
r3 = rindex
r1 = rindex % 3
tmp0 = tl.load(in_ptr0 + (3 + 4 * r2 + 16 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tl.load(in_ptr1 + (r3 + 12 * x0), rmask & xmask, other=0.0)
tmp2 = tl.load(in_ptr0 + (r1 + 4 * r2 + 16 * x0), rmask & xmask, other=0.0)
tmp3 = tmp1 - tmp2
tmp4 = tl_math.abs(tmp3)
tmp5 = tmp0 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(rmask & xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tl.store(out_ptr0 + x0, tmp9, 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, 3), (48, 12, 3, 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_per_fused_abs_clone_mul_sub_sum_0[grid(16)](arg0_1, arg1_1,
buf0, 16, 12, XBLOCK=8, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class Keypoint2DLossNew(nn.Module):
def __init__(self, loss_type: 'str'='l1'):
"""
2D keypoint loss module.
Args:
loss_type (str): Choose between l1 and l2 losses.
"""
super(Keypoint2DLossNew, self).__init__()
if loss_type == 'l1':
self.loss_fn = nn.L1Loss(reduction='none')
elif loss_type == 'l2':
self.loss_fn = nn.MSELoss(reduction='none')
else:
raise NotImplementedError('Unsupported loss function')
def forward(self, input_0, input_1):
arg1_1 = input_0
arg0_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nkolot/ProHMR
|
Keypoint2DLoss
| false
| 16,179
|
[
"BSD-3-Clause"
] | 120
|
dac2409c0b451b6dd5d91f03cbe7132aa495792f
|
https://github.com/nkolot/ProHMR/tree/dac2409c0b451b6dd5d91f03cbe7132aa495792f
|
MatchingNetwork
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.optim
import torch.nn.functional as F
import torch.nn.parallel
class MatchingNetwork(nn.Module):
def __init__(self, opt):
super(MatchingNetwork, self).__init__()
scale_cls = opt['scale_cls'] if 'scale_cls' in opt else 10.0
self.scale_cls = nn.Parameter(torch.FloatTensor(1).fill_(scale_cls),
requires_grad=True)
def forward(self, features_test, features_train, labels_train):
"""Recognize novel categories based on the Matching Nets approach.
Classify the test examples (i.e., `features_test`) using the available
training examples (i.e., `features_test` and `labels_train`) using the
Matching Nets approach.
Args:
features_test: A 3D tensor with shape
[batch_size x num_test_examples x num_channels] that represents
the test features of each training episode in the batch.
features_train: A 3D tensor with shape
[batch_size x num_train_examples x num_channels] that represents
the train features of each training episode in the batch.
labels_train: A 3D tensor with shape
[batch_size x num_train_examples x nKnovel] that represents
the train labels (encoded as 1-hot vectors) of each training
episode in the batch.
Return:
scores_cls: A 3D tensor with shape
[batch_size x num_test_examples x nKnovel] that represents the
classification scores of the test feature vectors for the
nKnovel novel categories.
"""
assert features_train.dim() == 3
assert labels_train.dim() == 3
assert features_test.dim() == 3
assert features_train.size(0) == labels_train.size(0)
assert features_train.size(0) == features_test.size(0)
assert features_train.size(1) == labels_train.size(1)
assert features_train.size(2) == features_test.size(2)
batch_size, num_test_examples, _num_channels = features_test.size()
num_train_examples = features_train.size(1)
labels_train.size(2)
features_test = F.normalize(features_test, p=2, dim=features_test.
dim() - 1, eps=1e-12)
features_train = F.normalize(features_train, p=2, dim=
features_train.dim() - 1, eps=1e-12)
cosine_similarities = self.scale_cls * torch.bmm(features_test,
features_train.transpose(1, 2))
cosine_similarities = cosine_similarities.view(batch_size *
num_test_examples, num_train_examples)
cosine_scores = F.softmax(cosine_similarities)
cosine_scores = cosine_scores.view(batch_size, num_test_examples,
num_train_examples)
scores_cls = torch.bmm(cosine_scores, labels_train)
scores_cls = torch.log(torch.clamp(scores_cls, min=1e-07))
return scores_cls
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'opt': _mock_config(scale_cls=1.0)}]
|
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.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_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-12
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tmp1 * tmp2
tmp5 = tmp1 * tmp4
tmp6 = triton_helpers.maximum(tmp3, tmp5)
tmp8 = tmp1 * tmp7
tmp9 = triton_helpers.maximum(tmp6, tmp8)
tmp11 = tmp1 * tmp10
tmp12 = triton_helpers.maximum(tmp9, tmp11)
tmp13 = tmp3 - tmp12
tmp14 = tl_math.exp(tmp13)
tmp15 = tmp5 - tmp12
tmp16 = tl_math.exp(tmp15)
tmp17 = tmp14 + tmp16
tmp18 = tmp8 - tmp12
tmp19 = tl_math.exp(tmp18)
tmp20 = tmp17 + tmp19
tmp21 = tmp11 - tmp12
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp20 + tmp22
tl.store(out_ptr0 + x0, tmp12, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 * tmp2
tmp5 = tmp3 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clamp_log_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1e-07
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tl_math.log(tmp2)
tl.store(out_ptr0 + x0, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (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_div_0[grid(64)](primals_3, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_3
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_div_0[grid(64)](primals_1, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf0, reinterpret_tensor(buf1, (4, 4, 4), (16, 1,
4), 0), out=buf2)
buf3 = empty_strided_cuda((16, 1), (1, 16), torch.float32)
buf4 = empty_strided_cuda((16, 1), (1, 16), torch.float32)
triton_poi_fused__softmax_1[grid(16)](primals_4, buf2, buf3, buf4,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf5 = reinterpret_tensor(buf1, (16, 4), (4, 1), 0)
del buf1
triton_poi_fused__softmax_2[grid(64)](primals_4, buf2, buf3, buf4,
buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf3
del buf4
buf6 = buf0
del buf0
extern_kernels.bmm(reinterpret_tensor(buf5, (4, 4, 4), (16, 4, 1),
0), primals_2, out=buf6)
buf7 = reinterpret_tensor(buf5, (4, 4, 4), (16, 4, 1), 0)
del buf5
triton_poi_fused_clamp_log_3[grid(64)](buf6, buf7, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf7, primals_4, buf2, buf6, reinterpret_tensor(primals_2, (4, 4,
4), (16, 1, 4), 0)
class MatchingNetworkNew(nn.Module):
def __init__(self, opt):
super(MatchingNetworkNew, self).__init__()
scale_cls = opt['scale_cls'] if 'scale_cls' in opt else 10.0
self.scale_cls = nn.Parameter(torch.FloatTensor(1).fill_(scale_cls),
requires_grad=True)
def forward(self, input_0, input_1, input_2):
primals_4 = self.scale_cls
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
nikran1/Few_shot
|
MatchingNetwork
| false
| 16,180
|
[
"MIT"
] | 497
|
5298c98e208411e44ee7767e6f4d457006d373cb
|
https://github.com/nikran1/Few_shot/tree/5298c98e208411e44ee7767e6f4d457006d373cb
|
NormalizeScaleController
|
import torch
class ScaleControllerBase(torch.nn.Module):
"""
The base class for ScaleController.
ScaleController is a callable class that re-scale input tensor's value.
Traditional scale method may include:
soft-max, L2 normalize, relu and so on.
Advanced method:
Learnable scale parameter
"""
def __init__(self):
super(ScaleControllerBase, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
"""
Re-scale the input x into proper value scale.
:param x: the input tensor
:param dim: axis to scale(mostly used in traditional method)
:param p: p parameter used in traditional methods
:return: rescaled x
"""
raise NotImplementedError
class NormalizeScaleController(ScaleControllerBase):
def __init__(self):
super(NormalizeScaleController, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=-1, p: 'int'=1):
return torch.nn.functional.normalize(x, p=p, dim=dim)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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.abs(tmp1)
tmp4 = tl_math.abs(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.abs(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.abs(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = 1e-12
tmp13 = triton_helpers.maximum(tmp11, tmp12)
tmp14 = tmp0 / tmp13
tl.store(out_ptr0 + x2, tmp14, 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_div_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ScaleControllerBase(torch.nn.Module):
"""
The base class for ScaleController.
ScaleController is a callable class that re-scale input tensor's value.
Traditional scale method may include:
soft-max, L2 normalize, relu and so on.
Advanced method:
Learnable scale parameter
"""
def __init__(self):
super(ScaleControllerBase, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
"""
Re-scale the input x into proper value scale.
:param x: the input tensor
:param dim: axis to scale(mostly used in traditional method)
:param p: p parameter used in traditional methods
:return: rescaled x
"""
raise NotImplementedError
class NormalizeScaleControllerNew(ScaleControllerBase):
def __init__(self):
super(NormalizeScaleControllerNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
niloofar17/MetaDialog
|
NormalizeScaleController
| false
| 16,181
|
[
"Apache-2.0"
] | 204
|
d75b84a02807d53d9596e72c2f698e5a4f180369
|
https://github.com/niloofar17/MetaDialog/tree/d75b84a02807d53d9596e72c2f698e5a4f180369
|
ParameterLoss
|
import torch
import torch.nn as nn
class ParameterLoss(nn.Module):
def __init__(self):
"""
SMPL parameter loss module.
"""
super(ParameterLoss, self).__init__()
self.loss_fn = nn.MSELoss(reduction='none')
def forward(self, pred_param: 'torch.Tensor', gt_param: 'torch.Tensor',
has_param: 'torch.Tensor'):
"""
Compute SMPL parameter loss.
Args:
pred_param (torch.Tensor): Tensor of shape [B, S, ...] containing the predicted parameters (body pose / global orientation / betas)
gt_param (torch.Tensor): Tensor of shape [B, S, ...] containing the ground truth SMPL parameters.
Returns:
torch.Tensor: L2 parameter loss loss.
"""
batch_size = pred_param.shape[0]
num_samples = pred_param.shape[1]
num_dims = len(pred_param.shape)
mask_dimension = [batch_size, num_samples] + [1] * (num_dims - 2)
has_param = has_param.type(pred_param.type()).view(*mask_dimension)
loss_param = has_param * self.loss_fn(pred_param, gt_param)
return loss_param
def get_inputs():
return [torch.rand([4, 4, 1, 1]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 1, 1])]
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_mse_loss_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
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x2, xmask)
tmp3 = tmp1 - tmp2
tmp4 = tmp3 * tmp3
tmp5 = tmp0 * tmp4
tl.store(out_ptr0 + x2, tmp5, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(arg1_1, (4, 4, 1, 1), (4, 1, 1, 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_mse_loss_mul_0[grid(256)](arg1_1, arg0_1, arg2_1,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf0,
class ParameterLossNew(nn.Module):
def __init__(self):
"""
SMPL parameter loss module.
"""
super(ParameterLossNew, self).__init__()
self.loss_fn = nn.MSELoss(reduction='none')
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg2_1 = input_1
arg1_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
nkolot/ProHMR
|
ParameterLoss
| false
| 16,182
|
[
"BSD-3-Clause"
] | 120
|
dac2409c0b451b6dd5d91f03cbe7132aa495792f
|
https://github.com/nkolot/ProHMR/tree/dac2409c0b451b6dd5d91f03cbe7132aa495792f
|
Keypoint3DLoss
|
import torch
import torch.nn as nn
class Keypoint3DLoss(nn.Module):
def __init__(self, loss_type: 'str'='l1'):
"""
3D keypoint loss module.
Args:
loss_type (str): Choose between l1 and l2 losses.
"""
super(Keypoint3DLoss, self).__init__()
if loss_type == 'l1':
self.loss_fn = nn.L1Loss(reduction='none')
elif loss_type == 'l2':
self.loss_fn = nn.MSELoss(reduction='none')
else:
raise NotImplementedError('Unsupported loss function')
def forward(self, pred_keypoints_3d: 'torch.Tensor', gt_keypoints_3d:
'torch.Tensor', pelvis_id: 'int'=39):
"""
Compute 3D keypoint loss.
Args:
pred_keypoints_3d (torch.Tensor): Tensor of shape [B, S, N, 3] containing the predicted 3D keypoints (B: batch_size, S: num_samples, N: num_keypoints)
gt_keypoints_3d (torch.Tensor): Tensor of shape [B, S, N, 4] containing the ground truth 3D keypoints and confidence.
Returns:
torch.Tensor: 3D keypoint loss.
"""
pred_keypoints_3d.shape[0]
gt_keypoints_3d = gt_keypoints_3d.clone()
pred_keypoints_3d = pred_keypoints_3d - pred_keypoints_3d[:, :,
pelvis_id, :].unsqueeze(dim=2)
gt_keypoints_3d[:, :, :, :-1] = gt_keypoints_3d[:, :, :, :-1
] - gt_keypoints_3d[:, :, pelvis_id, :-1].unsqueeze(dim=2)
conf = gt_keypoints_3d[:, :, :, -1].unsqueeze(-1).clone()
gt_keypoints_3d = gt_keypoints_3d[:, :, :, :-1]
loss = (conf * self.loss_fn(pred_keypoints_3d, gt_keypoints_3d)).sum(
dim=(2, 3))
return loss
def get_inputs():
return [torch.rand([4, 4, 40, 3]), torch.rand([4, 4, 40, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_clone_mul_sub_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
rnumel = 120
RBLOCK: tl.constexpr = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r2 = rindex // 3
x0 = xindex
r3 = rindex
r1 = rindex % 3
tmp7 = tl.load(in_ptr0 + (3 + 4 * r2 + 160 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp9 = tl.load(in_ptr1 + (r3 + 120 * x0), rmask & xmask, other=0.0)
tmp10 = tl.load(in_ptr1 + (117 + r1 + 120 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp19 = tl.load(in_ptr0 + (r1 + 4 * r2 + 160 * x0), rmask & xmask,
other=0.0)
tmp0 = tl.full([1, 1], 3, tl.int64)
tmp1 = tmp0 < tmp0
tmp2 = tl.load(in_ptr0 + (3 + 4 * r2 + 160 * x0), rmask & tmp1 & xmask,
eviction_policy='evict_last', other=0.0)
tmp3 = tl.load(in_ptr0 + tl.broadcast_to(159 + 160 * x0, [XBLOCK,
RBLOCK]), rmask & tmp1 & xmask, eviction_policy='evict_last', other=0.0
)
tmp4 = tmp2 - tmp3
tmp5 = tl.full(tmp4.shape, 0.0, tmp4.dtype)
tmp6 = tl.where(tmp1, tmp4, tmp5)
tmp8 = tl.where(tmp1, tmp6, tmp7)
tmp11 = tmp9 - tmp10
tmp12 = r1
tmp13 = tmp12 < tmp0
tmp14 = tl.load(in_ptr0 + (r1 + 4 * r2 + 160 * x0), rmask & tmp13 &
xmask, other=0.0)
tmp15 = tl.load(in_ptr0 + (156 + r1 + 160 * x0), rmask & tmp13 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tmp14 - tmp15
tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype)
tmp18 = tl.where(tmp13, tmp16, tmp17)
tmp20 = tl.where(tmp13, tmp18, tmp19)
tmp21 = tmp11 - tmp20
tmp22 = tl_math.abs(tmp21)
tmp23 = tmp8 * tmp22
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp26 = tl.where(rmask & xmask, tmp24, 0)
tmp27 = tl.sum(tmp26, 1)[:, None]
tl.store(out_ptr0 + x0, tmp27, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 40, 3), (480, 120, 3, 1))
assert_size_stride(arg1_1, (4, 4, 40, 4), (640, 160, 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_per_fused_abs_clone_mul_sub_sum_0[grid(16)](arg1_1, arg0_1,
buf0, 16, 120, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class Keypoint3DLossNew(nn.Module):
def __init__(self, loss_type: 'str'='l1'):
"""
3D keypoint loss module.
Args:
loss_type (str): Choose between l1 and l2 losses.
"""
super(Keypoint3DLossNew, self).__init__()
if loss_type == 'l1':
self.loss_fn = nn.L1Loss(reduction='none')
elif loss_type == 'l2':
self.loss_fn = nn.MSELoss(reduction='none')
else:
raise NotImplementedError('Unsupported loss function')
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nkolot/ProHMR
|
Keypoint3DLoss
| false
| 16,183
|
[
"BSD-3-Clause"
] | 120
|
dac2409c0b451b6dd5d91f03cbe7132aa495792f
|
https://github.com/nkolot/ProHMR/tree/dac2409c0b451b6dd5d91f03cbe7132aa495792f
|
pair_norm
|
import torch
class pair_norm(torch.nn.Module):
def __init__(self):
super(pair_norm, self).__init__()
def forward(self, x):
col_mean = x.mean(dim=0)
x = x - col_mean
rownorm_mean = (1e-06 + x.pow(2).sum(dim=1).mean()).sqrt()
x = x / rownorm_mean
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mean_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
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_per_fused_mean_pow_sum_1(in_ptr0, out_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)
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)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp13 = tl.sum(tmp11, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
@triton.jit
def triton_poi_fused_add_div_mean_pow_sqrt_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
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = 64.0
tmp4 = tmp2 / tmp3
tmp5 = 1e-06
tmp6 = tmp4 + tmp5
tmp7 = libdevice.sqrt(tmp6)
tmp8 = tmp0 / tmp7
tl.store(in_out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_mean_pow_sum_1[grid(1)](buf0, buf1, 1, 64, XBLOCK=
1, num_warps=2, num_stages=1)
buf2 = buf0
del buf0
triton_poi_fused_add_div_mean_pow_sqrt_sum_2[grid(256)](buf2, buf1,
256, XBLOCK=256, num_warps=4, num_stages=1)
del buf1
return buf2,
class pair_normNew(torch.nn.Module):
def __init__(self):
super(pair_normNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
ngohienduong/Deep_GCN_Benchmarking
|
pair_norm
| false
| 16,184
|
[
"MIT"
] | 70
|
3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
https://github.com/ngohienduong/Deep_GCN_Benchmarking/tree/3ee57a265bbfd62d8e6f3ee6e3e9062dd5a44633
|
PrototypicalNetwork
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.optim
import torch.nn.parallel
def L2SquareDist(A, B, average=True):
assert A.dim() == 3
assert B.dim() == 3
assert A.size(0) == B.size(0) and A.size(2) == B.size(2)
nB = A.size(0)
Na = A.size(1)
Nb = B.size(1)
nC = A.size(2)
AB = torch.bmm(A, B.transpose(1, 2))
AA = (A * A).sum(dim=2, keepdim=True).view(nB, Na, 1)
BB = (B * B).sum(dim=2, keepdim=True).view(nB, 1, Nb)
dist = AA.expand_as(AB) + BB.expand_as(AB) - 2 * AB
if average:
dist = dist / nC
return dist
class PrototypicalNetwork(nn.Module):
def __init__(self, opt):
super(PrototypicalNetwork, self).__init__()
scale_cls = opt['scale_cls'] if 'scale_cls' in opt else 1.0
self.scale_cls = nn.Parameter(torch.FloatTensor(1).fill_(scale_cls),
requires_grad=True)
def forward(self, features_test, features_train, labels_train):
"""Recognize novel categories based on the Prototypical Nets approach.
Classify the test examples (i.e., `features_test`) using the available
training examples (i.e., `features_test` and `labels_train`) using the
Prototypical Nets approach.
Args:
features_test: A 3D tensor with shape
[batch_size x num_test_examples x num_channels] that represents
the test features of each training episode in the batch.
features_train: A 3D tensor with shape
[batch_size x num_train_examples x num_channels] that represents
the train features of each training episode in the batch.
labels_train: A 3D tensor with shape
[batch_size x num_train_examples x nKnovel] that represents
the train labels (encoded as 1-hot vectors) of each training
episode in the batch.
Return:
scores_cls: A 3D tensor with shape
[batch_size x num_test_examples x nKnovel] that represents the
classification scores of the test feature vectors for the
nKnovel novel categories.
"""
assert features_train.dim() == 3
assert labels_train.dim() == 3
assert features_test.dim() == 3
assert features_train.size(0) == labels_train.size(0)
assert features_train.size(0) == features_test.size(0)
assert features_train.size(1) == labels_train.size(1)
assert features_train.size(2) == features_test.size(2)
labels_train_transposed = labels_train.transpose(1, 2)
prototypes = torch.bmm(labels_train_transposed, features_train)
prototypes = prototypes.div(labels_train_transposed.sum(dim=2,
keepdim=True).expand_as(prototypes))
scores_cls = -self.scale_cls * L2SquareDist(features_test, prototypes)
return scores_cls
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'opt': _mock_config(scale_cls=1.0)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.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_div_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
x2 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(in_out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_neg_sub_1(in_out_ptr0, 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
x4 = xindex // 4
x0 = xindex % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x4, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x4), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x4), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x4), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + (4 * x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr1 + (1 + 4 * x0 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp16 = tl.load(in_ptr1 + (2 + 4 * x0 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0 + 16 * x2), xmask,
eviction_policy='evict_last')
tmp23 = tl.load(in_out_ptr0 + x3, xmask)
tmp29 = tl.load(in_ptr2 + 0)
tmp30 = tl.broadcast_to(tmp29, [XBLOCK])
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp12 = tmp11 * tmp11
tmp14 = tmp13 * tmp13
tmp15 = tmp12 + tmp14
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp10 + tmp21
tmp24 = 2.0
tmp25 = tmp23 * tmp24
tmp26 = tmp22 - tmp25
tmp27 = 0.25
tmp28 = tmp26 * tmp27
tmp31 = -tmp30
tmp32 = tmp31 * tmp28
tl.store(in_out_ptr0 + x3, tmp28, xmask)
tl.store(out_ptr0 + x3, tmp32, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (1,), (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(reinterpret_tensor(primals_2, (4, 4, 4), (16, 1,
4), 0), primals_1, out=buf0)
del primals_1
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_div_0[grid(64)](buf1, primals_2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(primals_3, reinterpret_tensor(buf1, (4, 4, 4), (
16, 1, 4), 0), out=buf2)
buf3 = buf2
del buf2
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mul_neg_sub_1[grid(64)](buf4, primals_3,
buf1, primals_4, buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf1
del primals_3
del primals_4
return buf5, buf4
def L2SquareDist(A, B, average=True):
assert A.dim() == 3
assert B.dim() == 3
assert A.size(0) == B.size(0) and A.size(2) == B.size(2)
nB = A.size(0)
Na = A.size(1)
Nb = B.size(1)
nC = A.size(2)
AB = torch.bmm(A, B.transpose(1, 2))
AA = (A * A).sum(dim=2, keepdim=True).view(nB, Na, 1)
BB = (B * B).sum(dim=2, keepdim=True).view(nB, 1, Nb)
dist = AA.expand_as(AB) + BB.expand_as(AB) - 2 * AB
if average:
dist = dist / nC
return dist
class PrototypicalNetworkNew(nn.Module):
def __init__(self, opt):
super(PrototypicalNetworkNew, self).__init__()
scale_cls = opt['scale_cls'] if 'scale_cls' in opt else 1.0
self.scale_cls = nn.Parameter(torch.FloatTensor(1).fill_(scale_cls),
requires_grad=True)
def forward(self, input_0, input_1, input_2):
primals_4 = self.scale_cls
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
nikran1/Few_shot
|
PrototypicalNetwork
| false
| 16,185
|
[
"MIT"
] | 497
|
5298c98e208411e44ee7767e6f4d457006d373cb
|
https://github.com/nikran1/Few_shot/tree/5298c98e208411e44ee7767e6f4d457006d373cb
|
FixedScaleController
|
import torch
class ScaleControllerBase(torch.nn.Module):
"""
The base class for ScaleController.
ScaleController is a callable class that re-scale input tensor's value.
Traditional scale method may include:
soft-max, L2 normalize, relu and so on.
Advanced method:
Learnable scale parameter
"""
def __init__(self):
super(ScaleControllerBase, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
"""
Re-scale the input x into proper value scale.
:param x: the input tensor
:param dim: axis to scale(mostly used in traditional method)
:param p: p parameter used in traditional methods
:return: rescaled x
"""
raise NotImplementedError
class FixedScaleController(ScaleControllerBase):
"""
Scale parameter with a fixed value.
"""
def __init__(self, normalizer: 'ScaleControllerBase'=None, scale_rate:
'float'=50):
super(FixedScaleController, self).__init__()
self.scale_rate = scale_rate
self.normalizer = normalizer
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
x = x * self.scale_rate
if self.normalizer:
x = self.normalizer(x, dim=dim, p=p)
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
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_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 = 50.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ScaleControllerBase(torch.nn.Module):
"""
The base class for ScaleController.
ScaleController is a callable class that re-scale input tensor's value.
Traditional scale method may include:
soft-max, L2 normalize, relu and so on.
Advanced method:
Learnable scale parameter
"""
def __init__(self):
super(ScaleControllerBase, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
"""
Re-scale the input x into proper value scale.
:param x: the input tensor
:param dim: axis to scale(mostly used in traditional method)
:param p: p parameter used in traditional methods
:return: rescaled x
"""
raise NotImplementedError
class FixedScaleControllerNew(ScaleControllerBase):
"""
Scale parameter with a fixed value.
"""
def __init__(self, normalizer: 'ScaleControllerBase'=None, scale_rate:
'float'=50):
super(FixedScaleControllerNew, self).__init__()
self.scale_rate = scale_rate
self.normalizer = normalizer
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
niloofar17/MetaDialog
|
FixedScaleController
| false
| 16,186
|
[
"Apache-2.0"
] | 204
|
d75b84a02807d53d9596e72c2f698e5a4f180369
|
https://github.com/niloofar17/MetaDialog/tree/d75b84a02807d53d9596e72c2f698e5a4f180369
|
UpsampleNet
|
import torch
import numpy as np
import torch.nn as nn
class SqueezeLayer(nn.Module):
def __init__(self, factor):
super(SqueezeLayer, self).__init__()
self.factor = factor
def forward(self, input, logdet=None, reverse=False, **kwargs):
if not reverse:
assert input.size(-1) % self.factor == 0
output = input.view(input.size(0), input.size(1), -1, self.factor)
output = output.permute(0, 1, 3, 2).contiguous()
output = output.view(input.size(0), -1, input.size(-1) // self.
factor)
return output, logdet
else:
assert input.size(1) % self.factor == 0
output = input.view(input.size(0), -1, self.factor, input.size(-1))
output = output.permute(0, 1, 3, 2).contiguous()
output = output.view(input.size(0), input.size(1) // self.
factor, -1)
return output, logdet
class UpsampleNet(nn.Module):
def __init__(self, upsample_factor, upsample_method='duplicate',
squeeze_factor=8):
super(UpsampleNet, self).__init__()
self.upsample_factor = upsample_factor
self.upsample_method = upsample_method
self.squeeze_factor = squeeze_factor
if upsample_method == 'duplicate':
upsample_factor = int(np.prod(upsample_factor))
self.upsample = nn.Upsample(scale_factor=upsample_factor, mode=
'nearest')
elif upsample_method == 'transposed_conv2d':
if not isinstance(upsample_factor, list):
raise ValueError(
'You must specify upsample_factor as a list when used with transposed_conv2d'
)
freq_axis_kernel_size = 3
self.upsample_conv = nn.ModuleList()
for s in upsample_factor:
freq_axis_padding = (freq_axis_kernel_size - 1) // 2
conv = nn.ConvTranspose2d(1, 1, (freq_axis_kernel_size, 2 *
s), padding=(freq_axis_padding, s // 2), dilation=1,
stride=(1, s))
self.upsample_conv.append(conv)
self.upsample_conv.append(nn.LeakyReLU(negative_slope=0.4,
inplace=True))
else:
raise ValueError('{} upsampling is not supported'.format(self.
_upsample_method))
self.squeeze_layer = SqueezeLayer(squeeze_factor)
def forward(self, input):
if self.upsample_method == 'duplicate':
output = self.upsample(input)
elif self.upsample_method == 'transposed_conv2d':
output = input.unsqueeze(1)
for layer in self.upsample_conv:
output = layer(output)
output = output.squeeze(1)
output = self.squeeze_layer(output)[0]
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'upsample_factor': 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 numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_view_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)
x0 = xindex % 32
x1 = xindex // 32 % 8
x2 = xindex // 256 % 4
x3 = xindex // 1024
x6 = xindex
tmp0 = (x1 + 8 * x0) // 16
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.25
tmp3 = tmp1 * tmp2
tmp4 = tmp3.to(tl.int32)
tmp5 = (x1 + 8 * x0) % 16
tmp6 = tmp5.to(tl.float32)
tmp7 = tmp6 * tmp2
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.load(in_ptr0 + (tmp8 + 4 * tmp4 + 16 * x2 + 16 * ((x1 + 8 *
x0) // 256) + 64 * x3 + 64 * ((x1 + 8 * x0 + 256 * x2) // 1024)),
None, eviction_policy='evict_last')
tl.store(in_out_ptr0 + x6, tmp9, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 8, 32), (1024, 256, 32, 1), torch.
float32)
buf1 = reinterpret_tensor(buf0, (4, 512, 2), (1024, 2, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_clone_view_0[grid(4096)](buf1, arg0_1, 4096,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf1,
class SqueezeLayer(nn.Module):
def __init__(self, factor):
super(SqueezeLayer, self).__init__()
self.factor = factor
def forward(self, input, logdet=None, reverse=False, **kwargs):
if not reverse:
assert input.size(-1) % self.factor == 0
output = input.view(input.size(0), input.size(1), -1, self.factor)
output = output.permute(0, 1, 3, 2).contiguous()
output = output.view(input.size(0), -1, input.size(-1) // self.
factor)
return output, logdet
else:
assert input.size(1) % self.factor == 0
output = input.view(input.size(0), -1, self.factor, input.size(-1))
output = output.permute(0, 1, 3, 2).contiguous()
output = output.view(input.size(0), input.size(1) // self.
factor, -1)
return output, logdet
class UpsampleNetNew(nn.Module):
def __init__(self, upsample_factor, upsample_method='duplicate',
squeeze_factor=8):
super(UpsampleNetNew, self).__init__()
self.upsample_factor = upsample_factor
self.upsample_method = upsample_method
self.squeeze_factor = squeeze_factor
if upsample_method == 'duplicate':
upsample_factor = int(np.prod(upsample_factor))
self.upsample = nn.Upsample(scale_factor=upsample_factor, mode=
'nearest')
elif upsample_method == 'transposed_conv2d':
if not isinstance(upsample_factor, list):
raise ValueError(
'You must specify upsample_factor as a list when used with transposed_conv2d'
)
freq_axis_kernel_size = 3
self.upsample_conv = nn.ModuleList()
for s in upsample_factor:
freq_axis_padding = (freq_axis_kernel_size - 1) // 2
conv = nn.ConvTranspose2d(1, 1, (freq_axis_kernel_size, 2 *
s), padding=(freq_axis_padding, s // 2), dilation=1,
stride=(1, s))
self.upsample_conv.append(conv)
self.upsample_conv.append(nn.LeakyReLU(negative_slope=0.4,
inplace=True))
else:
raise ValueError('{} upsampling is not supported'.format(self.
_upsample_method))
self.squeeze_layer = SqueezeLayer(squeeze_factor)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
npuichigo/waveglow
|
UpsampleNet
| false
| 16,187
|
[
"Apache-2.0"
] | 214
|
44e5cae59842ddb5f692085472b5e09fa18cce42
|
https://github.com/npuichigo/waveglow/tree/44e5cae59842ddb5f692085472b5e09fa18cce42
|
encoder_block
|
import torch
import torch.nn as nn
class encoder_block(nn.Module):
def __init__(self, input_feature, output_feature, use_dropout):
super(encoder_block, self).__init__()
self.conv_input = nn.Conv3d(input_feature, output_feature, 3, 1, 1, 1)
self.conv_inblock1 = nn.Conv3d(output_feature, output_feature, 3, 1,
1, 1)
self.conv_inblock2 = nn.Conv3d(output_feature, output_feature, 3, 1,
1, 1)
self.conv_pooling = nn.Conv3d(output_feature, output_feature, 2, 2,
1, 1)
self.prelu1 = nn.PReLU()
self.prelu2 = nn.PReLU()
self.prelu3 = nn.PReLU()
self.prelu4 = nn.PReLU()
self.use_dropout = use_dropout
self.dropout = nn.Dropout(0.2)
def apply_dropout(self, input):
if self.use_dropout:
return self.dropout(input)
else:
return input
def forward(self, x):
output = self.conv_input(x)
output = self.apply_dropout(self.prelu1(output))
output = self.apply_dropout(self.prelu2(self.conv_inblock1(output)))
output = self.apply_dropout(self.prelu3(self.conv_inblock2(output)))
return self.prelu4(self.conv_pooling(output))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_feature': 4, 'output_feature': 4, 'use_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
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__prelu_kernel_convolution_0(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp7 = tmp6 * tmp2
tmp8 = tl.where(tmp4, tmp2, tmp7)
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__prelu_kernel_convolution_1(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 108
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 27
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp7 = tmp6 * tmp2
tmp8 = tl.where(tmp4, tmp2, tmp7)
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (1,), (1,))
assert_size_stride(primals_8, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (1,), (1,))
assert_size_stride(primals_11, (4, 4, 2, 2, 2), (32, 8, 4, 2, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (1,), (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=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf1,
primals_2, primals_4, buf2, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(reinterpret_tensor(buf2, (1, 4, 4,
4, 4), (0, 64, 16, 4, 1), 0), primals_5, stride=(1, 1, 1),
padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf3, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf4,
primals_6, primals_7, buf5, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_6
buf6 = extern_kernels.convolution(reinterpret_tensor(buf5, (1, 4, 4,
4, 4), (0, 64, 16, 4, 1), 0), primals_8, stride=(1, 1, 1),
padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf6, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf7 = buf6
del buf6
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf7,
primals_9, primals_10, buf8, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_9
buf9 = extern_kernels.convolution(reinterpret_tensor(buf8, (1, 4, 4,
4, 4), (0, 64, 16, 4, 1), 0), primals_11, stride=(2, 2, 2),
padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf9, (1, 4, 3, 3, 3), (108, 27, 9, 3, 1))
buf10 = buf9
del buf9
buf11 = empty_strided_cuda((4, 3, 3, 3), (27, 9, 3, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_1[grid(108)](buf10,
primals_12, primals_13, buf11, 108, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_12
return (buf11, primals_1, primals_4, primals_5, primals_7, primals_8,
primals_10, primals_11, primals_13, reinterpret_tensor(primals_3, (
1, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0), buf1, reinterpret_tensor(
buf2, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0), buf4,
reinterpret_tensor(buf5, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0),
buf7, reinterpret_tensor(buf8, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1),
0), buf10)
class encoder_blockNew(nn.Module):
def __init__(self, input_feature, output_feature, use_dropout):
super(encoder_blockNew, self).__init__()
self.conv_input = nn.Conv3d(input_feature, output_feature, 3, 1, 1, 1)
self.conv_inblock1 = nn.Conv3d(output_feature, output_feature, 3, 1,
1, 1)
self.conv_inblock2 = nn.Conv3d(output_feature, output_feature, 3, 1,
1, 1)
self.conv_pooling = nn.Conv3d(output_feature, output_feature, 2, 2,
1, 1)
self.prelu1 = nn.PReLU()
self.prelu2 = nn.PReLU()
self.prelu3 = nn.PReLU()
self.prelu4 = nn.PReLU()
self.use_dropout = use_dropout
self.dropout = nn.Dropout(0.2)
def apply_dropout(self, input):
if self.use_dropout:
return self.dropout(input)
else:
return input
def forward(self, input_0):
primals_1 = self.conv_input.weight
primals_2 = self.conv_input.bias
primals_5 = self.conv_inblock1.weight
primals_6 = self.conv_inblock1.bias
primals_8 = self.conv_inblock2.weight
primals_9 = self.conv_inblock2.bias
primals_11 = self.conv_pooling.weight
primals_12 = self.conv_pooling.bias
primals_4 = self.prelu1.weight
primals_7 = self.prelu2.weight
primals_10 = self.prelu3.weight
primals_13 = self.prelu4.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])
return output[0]
|
ninamiolane/quicksilver
|
encoder_block
| false
| 16,188
|
[
"Apache-2.0"
] | 126
|
1baf251360dadea0afa3daaa09942d9d2d7c71fb
|
https://github.com/ninamiolane/quicksilver/tree/1baf251360dadea0afa3daaa09942d9d2d7c71fb
|
MultiHeadAttention
|
import torch
import numpy as np
import torch.nn as nn
import torch.distributions
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads, kq_same=False, bias=True):
super().__init__()
"""
It has projection layer for getting keys, queries and values. Followed by attention.
"""
self.d_model = d_model
self.h = n_heads
self.d_k = self.d_model // self.h
self.kq_same = kq_same
if not kq_same:
self.q_linear = nn.Linear(d_model, d_model, bias=bias)
self.k_linear = nn.Linear(d_model, d_model, bias=bias)
self.v_linear = nn.Linear(d_model, d_model, bias=bias)
def head_split(self, x):
new_x_shape = x.size()[:-1] + (self.h, self.d_k)
return x.view(*new_x_shape).transpose(-2, -3)
def forward(self, q, k, v, mask=None):
origin_shape = q.size()
if not self.kq_same:
q = self.head_split(self.q_linear(q))
else:
q = self.head_split(self.k_linear(q))
k = self.head_split(self.k_linear(k))
v = self.head_split(self.v_linear(v))
output = self.scaled_dot_product_attention(q, k, v, self.d_k, mask)
output = output.transpose(-2, -3).reshape(origin_shape)
return output
@staticmethod
def scaled_dot_product_attention(q, k, v, d_k, mask=None):
"""
This is called by Multi-head attention object to find the values.
"""
scores = torch.matmul(q, k.transpose(-2, -1)) / d_k ** 0.5
if mask is not None:
scores = scores.masked_fill(mask == 0, -np.inf)
scores = (scores - scores.max()).softmax(dim=-1)
scores = scores.masked_fill(torch.isnan(scores), 0)
output = torch.matmul(scores, v)
return output
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 [[], {'d_model': 4, 'n_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 numpy as np
import torch.nn as nn
import torch.distributions
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_per_fused_div_max_1(in_ptr0, out_ptr0, 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 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp3, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp5, None)
@triton.jit
def triton_poi_fused__softmax_div_sub_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp5 = tmp2 - tmp4
tmp7 = tmp6 * tmp1
tmp8 = tmp7 - tmp4
tmp9 = triton_helpers.maximum(tmp5, tmp8)
tmp11 = tmp10 * tmp1
tmp12 = tmp11 - tmp4
tmp13 = triton_helpers.maximum(tmp9, tmp12)
tmp15 = tmp14 * tmp1
tmp16 = tmp15 - tmp4
tmp17 = triton_helpers.maximum(tmp13, tmp16)
tmp18 = tmp5 - tmp17
tmp19 = tl_math.exp(tmp18)
tmp20 = tmp8 - tmp17
tmp21 = tl_math.exp(tmp20)
tmp22 = tmp19 + tmp21
tmp23 = tmp12 - tmp17
tmp24 = tl_math.exp(tmp23)
tmp25 = tmp22 + tmp24
tmp26 = tmp16 - tmp17
tmp27 = tl_math.exp(tmp26)
tmp28 = tmp25 + tmp27
tl.store(out_ptr0 + x0, tmp17, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused__softmax_div_isnan_masked_fill_sub_3(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr1 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp6 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp5 = tmp2 - tmp4
tmp7 = tmp5 - tmp6
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 / tmp9
tmp11 = libdevice.isnan(tmp10).to(tl.int1)
tmp12 = 0.0
tmp13 = tl.where(tmp11, tmp12, tmp10)
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4, 4, 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_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](buf0, primals_3, buf3, 64, 4,
XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1, 4), (64, 16, 4, 4, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(64, 4)](buf1, primals_5, buf4, 64, 4,
XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((64, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (64, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (64, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_div_max_1[grid(1)](buf5, buf6, 1, 1024, num_warps=
8, num_stages=1)
buf7 = reinterpret_tensor(buf1, (4, 4, 4, 4, 1), (64, 16, 4, 1, 256), 0
)
del buf1
buf8 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 256),
torch.float32)
triton_poi_fused__softmax_div_sub_2[grid(256)](buf5, buf6, buf7,
buf8, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused__softmax_div_isnan_masked_fill_sub_3[grid(1024)](buf5,
buf6, buf7, buf8, buf9, 1024, XBLOCK=128, num_warps=4, num_stages=1
)
del buf7
buf10 = reinterpret_tensor(buf8, (4, 4, 4, 4, 1), (64, 16, 4, 1, 1), 0)
del buf8
triton_poi_fused_clone_0[grid(64, 4)](buf2, primals_8, buf10, 64, 4,
XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf11 = reinterpret_tensor(buf2, (64, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf9, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf10, (64, 4, 1), (4, 1, 0), 0), out=buf11)
return reinterpret_tensor(buf11, (4, 4, 4, 4), (64, 16, 1, 4), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (64, 4), (4, 1), 0
), buf5, buf6, reinterpret_tensor(buf9, (64, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf10, (64, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (64, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (64, 4, 1), (4, 1, 4), 0)
class MultiHeadAttentionNew(nn.Module):
def __init__(self, d_model, n_heads, kq_same=False, bias=True):
super().__init__()
"""
It has projection layer for getting keys, queries and values. Followed by attention.
"""
self.d_model = d_model
self.h = n_heads
self.d_k = self.d_model // self.h
self.kq_same = kq_same
if not kq_same:
self.q_linear = nn.Linear(d_model, d_model, bias=bias)
self.k_linear = nn.Linear(d_model, d_model, bias=bias)
self.v_linear = nn.Linear(d_model, d_model, bias=bias)
def head_split(self, x):
new_x_shape = x.size()[:-1] + (self.h, self.d_k)
return x.view(*new_x_shape).transpose(-2, -3)
@staticmethod
def scaled_dot_product_attention(q, k, v, d_k, mask=None):
"""
This is called by Multi-head attention object to find the values.
"""
scores = torch.matmul(q, k.transpose(-2, -1)) / d_k ** 0.5
if mask is not None:
scores = scores.masked_fill(mask == 0, -np.inf)
scores = (scores - scores.max()).softmax(dim=-1)
scores = scores.masked_fill(torch.isnan(scores), 0)
output = torch.matmul(scores, v)
return output
def forward(self, input_0, input_1, input_2):
primals_2 = self.q_linear.weight
primals_3 = self.q_linear.bias
primals_4 = self.k_linear.weight
primals_5 = self.k_linear.bias
primals_7 = self.v_linear.weight
primals_8 = self.v_linear.bias
primals_1 = input_0
primals_6 = input_1
primals_9 = 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]
|
nmrenyi/ReChorus
|
MultiHeadAttention
| false
| 16,189
|
[
"MIT"
] | 314
|
9ab632579d0464b0aaf365539f87b04866920b66
|
https://github.com/nmrenyi/ReChorus/tree/9ab632579d0464b0aaf365539f87b04866920b66
|
ViTStemPatchify
|
from torch.nn import Module
import torch
import torch.utils.data
import torch.nn as nn
def patchify2d(w_in, w_out, k, *, bias=True):
"""Helper for building a patchify layer as used by ViT models."""
return nn.Conv2d(w_in, w_out, k, stride=k, padding=0, bias=bias)
def patchify2d_cx(cx, w_in, w_out, k, *, bias=True):
"""Accumulates complexity of patchify2d into cx = (h, w, flops, params, acts)."""
err_str = 'Only kernel sizes divisible by the input size are supported.'
assert cx['h'] % k == 0 and cx['w'] % k == 0, err_str
h, w, flops, params, acts = cx['h'], cx['w'], cx['flops'], cx['params'
], cx['acts']
h, w = h // k, w // k
flops += k * k * w_in * w_out * h * w + (w_out * h * w if bias else 0)
params += k * k * w_in * w_out + (w_out if bias else 0)
acts += w_out * h * w
return {'h': h, 'w': w, 'flops': flops, 'params': params, 'acts': acts}
class ViTStemPatchify(Module):
"""The patchify vision transformer stem as per https://arxiv.org/abs/2010.11929."""
def __init__(self, w_in, w_out, k):
super(ViTStemPatchify, self).__init__()
self.patchify = patchify2d(w_in, w_out, k, bias=True)
def forward(self, x):
return self.patchify(x)
@staticmethod
def complexity(cx, w_in, w_out, k):
return patchify2d_cx(cx, w_in, w_out, k, bias=True)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'w_in': 4, 'w_out': 4, 'k': 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.nn import Module
import torch.utils.data
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 = 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)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(4,
4), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 1, 1), (4, 1, 1, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16)](buf1, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
def patchify2d(w_in, w_out, k, *, bias=True):
"""Helper for building a patchify layer as used by ViT models."""
return nn.Conv2d(w_in, w_out, k, stride=k, padding=0, bias=bias)
def patchify2d_cx(cx, w_in, w_out, k, *, bias=True):
"""Accumulates complexity of patchify2d into cx = (h, w, flops, params, acts)."""
err_str = 'Only kernel sizes divisible by the input size are supported.'
assert cx['h'] % k == 0 and cx['w'] % k == 0, err_str
h, w, flops, params, acts = cx['h'], cx['w'], cx['flops'], cx['params'
], cx['acts']
h, w = h // k, w // k
flops += k * k * w_in * w_out * h * w + (w_out * h * w if bias else 0)
params += k * k * w_in * w_out + (w_out if bias else 0)
acts += w_out * h * w
return {'h': h, 'w': w, 'flops': flops, 'params': params, 'acts': acts}
class ViTStemPatchifyNew(Module):
"""The patchify vision transformer stem as per https://arxiv.org/abs/2010.11929."""
def __init__(self, w_in, w_out, k):
super(ViTStemPatchifyNew, self).__init__()
self.patchify = patchify2d(w_in, w_out, k, bias=True)
@staticmethod
def complexity(cx, w_in, w_out, k):
return patchify2d_cx(cx, w_in, w_out, k, bias=True)
def forward(self, input_0):
primals_1 = self.patchify.weight
primals_2 = self.patchify.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
om00839/pycls
|
ViTStemPatchify
| false
| 16,190
|
[
"MIT"
] | 1,975
|
8c79a8e2adfffa7cae3a88aace28ef45e52aa7e5
|
https://github.com/om00839/pycls/tree/8c79a8e2adfffa7cae3a88aace28ef45e52aa7e5
|
GAT
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class GraphAttention(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttention, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
self.W = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
in_features, out_features).type(torch.FloatTensor if torch.cuda
.is_available() else torch.FloatTensor), gain=np.sqrt(2.0)),
requires_grad=True)
self.a1 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(torch.FloatTensor if torch.cuda.
is_available() else torch.FloatTensor), gain=np.sqrt(2.0)),
requires_grad=True)
self.a2 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(torch.FloatTensor if torch.cuda.
is_available() else torch.FloatTensor), gain=np.sqrt(2.0)),
requires_grad=True)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, input, adj):
h = torch.mm(input, self.W)
h.size()[0]
f_1 = torch.matmul(h, self.a1)
f_2 = torch.matmul(h, self.a2)
e = self.leakyrelu(f_1 + f_2.transpose(0, 1))
zero_vec = -9000000000000000.0 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, h)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GAT(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttention(nfeat, nhid, dropout=dropout,
alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
self.out_att = GraphAttention(nhid * nheads, nclass, dropout=
dropout, alpha=alpha, concat=False)
def forward(self, x, adj):
x = F.dropout(x, self.dropout, training=self.training)
x = torch.cat([att(x, adj) for att in self.attentions], dim=1)
x = F.dropout(x, self.dropout, training=self.training)
x = F.elu(self.out_att(x, adj))
return F.log_softmax(x, dim=1)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'nfeat': 4, 'nhid': 4, 'nclass': 4, 'dropout': 0.5,
'alpha': 4, 'nheads': 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 numpy as np
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_leaky_relu_0(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.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_gt_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9,
in_ptr10, in_ptr11, in_ptr12, out_ptr0, out_ptr1, out_ptr2, out_ptr3,
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').to(tl
.int1)
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp2 = tl.load(in_ptr2 + x0, xmask)
tmp3 = tl.load(in_ptr3 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp12 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp13 = tl.load(in_ptr3 + 1)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp20 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp21 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp22 = tl.load(in_ptr3 + 2)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp29 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp30 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp31 = tl.load(in_ptr3 + 3)
tmp32 = tl.broadcast_to(tmp31, [XBLOCK])
tmp38 = tl.load(in_ptr4 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp39 = tl.load(in_ptr5 + x0, xmask)
tmp40 = tl.load(in_ptr6 + 0)
tmp41 = tl.broadcast_to(tmp40, [XBLOCK])
tmp46 = tl.load(in_ptr4 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp47 = tl.load(in_ptr6 + 1)
tmp48 = tl.broadcast_to(tmp47, [XBLOCK])
tmp54 = tl.load(in_ptr4 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp55 = tl.load(in_ptr6 + 2)
tmp56 = tl.broadcast_to(tmp55, [XBLOCK])
tmp62 = tl.load(in_ptr4 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp63 = tl.load(in_ptr6 + 3)
tmp64 = tl.broadcast_to(tmp63, [XBLOCK])
tmp70 = tl.load(in_ptr7 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp71 = tl.load(in_ptr8 + x0, xmask)
tmp72 = tl.load(in_ptr9 + 0)
tmp73 = tl.broadcast_to(tmp72, [XBLOCK])
tmp78 = tl.load(in_ptr7 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp79 = tl.load(in_ptr9 + 1)
tmp80 = tl.broadcast_to(tmp79, [XBLOCK])
tmp86 = tl.load(in_ptr7 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp87 = tl.load(in_ptr9 + 2)
tmp88 = tl.broadcast_to(tmp87, [XBLOCK])
tmp94 = tl.load(in_ptr7 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp95 = tl.load(in_ptr9 + 3)
tmp96 = tl.broadcast_to(tmp95, [XBLOCK])
tmp102 = tl.load(in_ptr10 + 4 * x0, xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp103 = tl.load(in_ptr11 + x0, xmask)
tmp104 = tl.load(in_ptr12 + 0)
tmp105 = tl.broadcast_to(tmp104, [XBLOCK])
tmp110 = tl.load(in_ptr10 + (1 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp111 = tl.load(in_ptr12 + 1)
tmp112 = tl.broadcast_to(tmp111, [XBLOCK])
tmp118 = tl.load(in_ptr10 + (2 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp119 = tl.load(in_ptr12 + 2)
tmp120 = tl.broadcast_to(tmp119, [XBLOCK])
tmp126 = tl.load(in_ptr10 + (3 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp127 = tl.load(in_ptr12 + 3)
tmp128 = tl.broadcast_to(tmp127, [XBLOCK])
tmp5 = tmp2 + tmp4
tmp6 = 4.0
tmp7 = tmp5 * tmp6
tmp8 = tl.where(tmp1, tmp5, tmp7)
tmp9 = -8999999815811072.0
tmp10 = tl.where(tmp0, tmp8, tmp9)
tmp15 = tmp2 + tmp14
tmp16 = tmp15 * tmp6
tmp17 = tl.where(tmp12, tmp15, tmp16)
tmp18 = tl.where(tmp11, tmp17, tmp9)
tmp19 = triton_helpers.maximum(tmp10, tmp18)
tmp24 = tmp2 + tmp23
tmp25 = tmp24 * tmp6
tmp26 = tl.where(tmp21, tmp24, tmp25)
tmp27 = tl.where(tmp20, tmp26, tmp9)
tmp28 = triton_helpers.maximum(tmp19, tmp27)
tmp33 = tmp2 + tmp32
tmp34 = tmp33 * tmp6
tmp35 = tl.where(tmp30, tmp33, tmp34)
tmp36 = tl.where(tmp29, tmp35, tmp9)
tmp37 = triton_helpers.maximum(tmp28, tmp36)
tmp42 = tmp39 + tmp41
tmp43 = tmp42 * tmp6
tmp44 = tl.where(tmp38, tmp42, tmp43)
tmp45 = tl.where(tmp0, tmp44, tmp9)
tmp49 = tmp39 + tmp48
tmp50 = tmp49 * tmp6
tmp51 = tl.where(tmp46, tmp49, tmp50)
tmp52 = tl.where(tmp11, tmp51, tmp9)
tmp53 = triton_helpers.maximum(tmp45, tmp52)
tmp57 = tmp39 + tmp56
tmp58 = tmp57 * tmp6
tmp59 = tl.where(tmp54, tmp57, tmp58)
tmp60 = tl.where(tmp20, tmp59, tmp9)
tmp61 = triton_helpers.maximum(tmp53, tmp60)
tmp65 = tmp39 + tmp64
tmp66 = tmp65 * tmp6
tmp67 = tl.where(tmp62, tmp65, tmp66)
tmp68 = tl.where(tmp29, tmp67, tmp9)
tmp69 = triton_helpers.maximum(tmp61, tmp68)
tmp74 = tmp71 + tmp73
tmp75 = tmp74 * tmp6
tmp76 = tl.where(tmp70, tmp74, tmp75)
tmp77 = tl.where(tmp0, tmp76, tmp9)
tmp81 = tmp71 + tmp80
tmp82 = tmp81 * tmp6
tmp83 = tl.where(tmp78, tmp81, tmp82)
tmp84 = tl.where(tmp11, tmp83, tmp9)
tmp85 = triton_helpers.maximum(tmp77, tmp84)
tmp89 = tmp71 + tmp88
tmp90 = tmp89 * tmp6
tmp91 = tl.where(tmp86, tmp89, tmp90)
tmp92 = tl.where(tmp20, tmp91, tmp9)
tmp93 = triton_helpers.maximum(tmp85, tmp92)
tmp97 = tmp71 + tmp96
tmp98 = tmp97 * tmp6
tmp99 = tl.where(tmp94, tmp97, tmp98)
tmp100 = tl.where(tmp29, tmp99, tmp9)
tmp101 = triton_helpers.maximum(tmp93, tmp100)
tmp106 = tmp103 + tmp105
tmp107 = tmp106 * tmp6
tmp108 = tl.where(tmp102, tmp106, tmp107)
tmp109 = tl.where(tmp0, tmp108, tmp9)
tmp113 = tmp103 + tmp112
tmp114 = tmp113 * tmp6
tmp115 = tl.where(tmp110, tmp113, tmp114)
tmp116 = tl.where(tmp11, tmp115, tmp9)
tmp117 = triton_helpers.maximum(tmp109, tmp116)
tmp121 = tmp103 + tmp120
tmp122 = tmp121 * tmp6
tmp123 = tl.where(tmp118, tmp121, tmp122)
tmp124 = tl.where(tmp20, tmp123, tmp9)
tmp125 = triton_helpers.maximum(tmp117, tmp124)
tmp129 = tmp103 + tmp128
tmp130 = tmp129 * tmp6
tmp131 = tl.where(tmp126, tmp129, tmp130)
tmp132 = tl.where(tmp29, tmp131, tmp9)
tmp133 = triton_helpers.maximum(tmp125, tmp132)
tl.store(out_ptr0 + x0, tmp37, xmask)
tl.store(out_ptr1 + x0, tmp69, xmask)
tl.store(out_ptr2 + x0, tmp101, xmask)
tl.store(out_ptr3 + x0, tmp133, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_3(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9,
in_ptr10, in_ptr11, in_ptr12, in_ptr13, in_ptr14, in_ptr15, in_ptr16,
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
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + x2, xmask).to(tl.int1)
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr5 + x2, xmask).to(tl.int1)
tmp14 = tl.load(in_ptr6 + x1, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr7 + x0, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr9 + x2, xmask).to(tl.int1)
tmp24 = tl.load(in_ptr10 + x1, xmask, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr11 + x0, xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr12 + x1, xmask, eviction_policy='evict_last')
tmp33 = tl.load(in_ptr13 + x2, xmask).to(tl.int1)
tmp34 = tl.load(in_ptr14 + x1, xmask, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr15 + x0, xmask, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr16 + x1, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp5 = 4.0
tmp6 = tmp4 * tmp5
tmp7 = tl.where(tmp1, tmp4, tmp6)
tmp8 = -8999999815811072.0
tmp9 = tl.where(tmp0, tmp7, tmp8)
tmp11 = tmp9 - tmp10
tmp12 = tl_math.exp(tmp11)
tmp16 = tmp14 + tmp15
tmp17 = tmp16 * tmp5
tmp18 = tl.where(tmp13, tmp16, tmp17)
tmp19 = tl.where(tmp0, tmp18, tmp8)
tmp21 = tmp19 - tmp20
tmp22 = tl_math.exp(tmp21)
tmp26 = tmp24 + tmp25
tmp27 = tmp26 * tmp5
tmp28 = tl.where(tmp23, tmp26, tmp27)
tmp29 = tl.where(tmp0, tmp28, tmp8)
tmp31 = tmp29 - tmp30
tmp32 = tl_math.exp(tmp31)
tmp36 = tmp34 + tmp35
tmp37 = tmp36 * tmp5
tmp38 = tl.where(tmp33, tmp36, tmp37)
tmp39 = tl.where(tmp0, tmp38, tmp8)
tmp41 = tmp39 - tmp40
tmp42 = tl_math.exp(tmp41)
tl.store(out_ptr0 + x2, tmp12, xmask)
tl.store(out_ptr1 + x2, tmp22, xmask)
tl.store(out_ptr2 + x2, tmp32, xmask)
tl.store(out_ptr3 + x2, tmp42, 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)
@triton.jit
def triton_poi_fused_cat_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = 0.0
tmp7 = tmp5 > tmp6
tmp8 = 1.0
tmp9 = tmp5 * tmp8
tmp10 = libdevice.expm1(tmp9)
tmp11 = tmp10 * tmp8
tmp12 = tl.where(tmp7, tmp9, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tmp16 = tl.full([1], 8, tl.int64)
tmp17 = tmp0 < tmp16
tmp18 = tmp15 & tmp17
tmp19 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp18 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tmp19 > tmp6
tmp21 = tmp19 * tmp8
tmp22 = libdevice.expm1(tmp21)
tmp23 = tmp22 * tmp8
tmp24 = tl.where(tmp20, tmp21, tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp18, tmp24, tmp25)
tmp27 = tmp0 >= tmp16
tmp28 = tl.full([1], 12, tl.int64)
tmp29 = tmp0 < tmp28
tmp30 = tmp27 & tmp29
tmp31 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp32 = tmp31 > tmp6
tmp33 = tmp31 * tmp8
tmp34 = libdevice.expm1(tmp33)
tmp35 = tmp34 * tmp8
tmp36 = tl.where(tmp32, tmp33, tmp35)
tmp37 = tl.full(tmp36.shape, 0.0, tmp36.dtype)
tmp38 = tl.where(tmp30, tmp36, tmp37)
tmp39 = tmp0 >= tmp28
tl.full([1], 16, tl.int64)
tmp42 = tl.load(in_ptr3 + (4 * x1 + (-12 + x0)), tmp39 & xmask,
eviction_policy='evict_last', other=0.0)
tmp43 = tmp42 > tmp6
tmp44 = tmp42 * tmp8
tmp45 = libdevice.expm1(tmp44)
tmp46 = tmp45 * tmp8
tmp47 = tl.where(tmp43, tmp44, tmp46)
tmp48 = tl.full(tmp47.shape, 0.0, tmp47.dtype)
tmp49 = tl.where(tmp39, tmp47, tmp48)
tmp50 = tl.where(tmp30, tmp38, tmp49)
tmp51 = tl.where(tmp18, tmp26, tmp50)
tmp52 = tl.where(tmp4, tmp14, tmp51)
tl.store(out_ptr0 + x2, tmp52, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_6(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, 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').to(tl
.int1)
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp2 = tl.load(in_ptr2 + x0, xmask)
tmp3 = tl.load(in_ptr3 + 0)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp12 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp13 = tl.load(in_ptr3 + 1)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp20 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp21 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp22 = tl.load(in_ptr3 + 2)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp29 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp30 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp31 = tl.load(in_ptr3 + 3)
tmp32 = tl.broadcast_to(tmp31, [XBLOCK])
tmp5 = tmp2 + tmp4
tmp6 = 4.0
tmp7 = tmp5 * tmp6
tmp8 = tl.where(tmp1, tmp5, tmp7)
tmp9 = -8999999815811072.0
tmp10 = tl.where(tmp0, tmp8, tmp9)
tmp15 = tmp2 + tmp14
tmp16 = tmp15 * tmp6
tmp17 = tl.where(tmp12, tmp15, tmp16)
tmp18 = tl.where(tmp11, tmp17, tmp9)
tmp19 = triton_helpers.maximum(tmp10, tmp18)
tmp24 = tmp2 + tmp23
tmp25 = tmp24 * tmp6
tmp26 = tl.where(tmp21, tmp24, tmp25)
tmp27 = tl.where(tmp20, tmp26, tmp9)
tmp28 = triton_helpers.maximum(tmp19, tmp27)
tmp33 = tmp2 + tmp32
tmp34 = tmp33 * tmp6
tmp35 = tl.where(tmp30, tmp33, tmp34)
tmp36 = tl.where(tmp29, tmp35, tmp9)
tmp37 = triton_helpers.maximum(tmp28, tmp36)
tl.store(out_ptr0 + x0, tmp37, xmask)
@triton.jit
def triton_poi_fused__softmax_add_leaky_relu_mul_where_7(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + x2, xmask).to(tl.int1)
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp5 = 4.0
tmp6 = tmp4 * tmp5
tmp7 = tl.where(tmp1, tmp4, tmp6)
tmp8 = -8999999815811072.0
tmp9 = tl.where(tmp0, tmp7, tmp8)
tmp11 = tmp9 - tmp10
tmp12 = tl_math.exp(tmp11)
tl.store(out_ptr0 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused__log_softmax_elu_8(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp8 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp28 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 1.0
tmp4 = tmp0 * tmp3
tmp5 = libdevice.expm1(tmp4)
tmp6 = tmp5 * tmp3
tmp7 = tl.where(tmp2, tmp4, tmp6)
tmp9 = tmp8 > tmp1
tmp10 = tmp8 * tmp3
tmp11 = libdevice.expm1(tmp10)
tmp12 = tmp11 * tmp3
tmp13 = tl.where(tmp9, tmp10, tmp12)
tmp15 = tmp14 > tmp1
tmp16 = tmp14 * tmp3
tmp17 = libdevice.expm1(tmp16)
tmp18 = tmp17 * tmp3
tmp19 = tl.where(tmp15, tmp16, tmp18)
tmp20 = triton_helpers.maximum(tmp13, tmp19)
tmp22 = tmp21 > tmp1
tmp23 = tmp21 * tmp3
tmp24 = libdevice.expm1(tmp23)
tmp25 = tmp24 * tmp3
tmp26 = tl.where(tmp22, tmp23, tmp25)
tmp27 = triton_helpers.maximum(tmp20, tmp26)
tmp29 = tmp28 > tmp1
tmp30 = tmp28 * tmp3
tmp31 = libdevice.expm1(tmp30)
tmp32 = tmp31 * tmp3
tmp33 = tl.where(tmp29, tmp30, tmp32)
tmp34 = triton_helpers.maximum(tmp27, tmp33)
tmp35 = tmp7 - tmp34
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused__log_softmax_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, 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), (1, 1))
assert_size_stride(primals_4, (4, 1), (1, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4, 1), (1, 1))
assert_size_stride(primals_8, (4, 1), (1, 1))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4, 1), (1, 1))
assert_size_stride(primals_11, (4, 1), (1, 1))
assert_size_stride(primals_12, (4, 4), (4, 1))
assert_size_stride(primals_13, (4, 1), (1, 1))
assert_size_stride(primals_14, (4, 1), (1, 1))
assert_size_stride(primals_15, (16, 4), (4, 1))
assert_size_stride(primals_16, (4, 1), (1, 1))
assert_size_stride(primals_17, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf0, primals_3, out=buf1)
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf0, primals_4, out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf1, buf2, buf3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_gt_1[grid(16)](primals_5, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_6, out=buf9)
del primals_6
buf10 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf9, primals_7, out=buf10)
buf11 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf9, primals_8, out=buf11)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf10, buf11, buf12, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_9, out=buf17)
del primals_9
buf18 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf17, primals_10, out=buf18)
buf19 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf17, primals_11, out=buf19)
buf20 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf18, buf19, buf20, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf25 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_12, out=buf25)
del primals_12
buf26 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf25, primals_13, out=buf26)
buf27 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf25, primals_14, out=buf27)
buf28 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf26, buf27, buf28, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf13 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf21 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf29 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
triton_poi_fused__softmax_add_leaky_relu_mul_where_2[grid(4)](buf4,
buf3, buf1, buf2, buf12, buf10, buf11, buf20, buf18, buf19,
buf28, buf26, buf27, buf5, buf13, buf21, buf29, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf22 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf30 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_add_leaky_relu_mul_where_3[grid(16)](buf4,
buf3, buf1, buf2, buf5, buf12, buf10, buf11, buf13, buf20,
buf18, buf19, buf21, buf28, buf26, buf27, buf29, buf6, buf14,
buf22, buf30, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf1
del buf10
del buf11
del buf13
del buf18
del buf19
del buf2
del buf21
del buf26
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf6, buf7, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf8 = buf6
del buf6
extern_kernels.mm(buf7, buf0, out=buf8)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf14, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf16 = buf14
del buf14
extern_kernels.mm(buf15, buf9, out=buf16)
buf23 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf22, buf23, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf24 = buf22
del buf22
extern_kernels.mm(buf23, buf17, out=buf24)
buf31 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf30, buf31, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf32 = buf30
del buf30
extern_kernels.mm(buf31, buf25, out=buf32)
buf33 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_poi_fused_cat_5[grid(64)](buf8, buf16, buf24, buf32, buf33,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf34 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf33, primals_15, out=buf34)
buf35 = reinterpret_tensor(buf5, (4, 1), (1, 1), 0)
del buf5
extern_kernels.mm(buf34, primals_16, out=buf35)
buf36 = reinterpret_tensor(buf29, (4, 1), (1, 1), 0)
del buf29
extern_kernels.mm(buf34, primals_17, out=buf36)
buf37 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf35, buf36, buf37, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf38 = reinterpret_tensor(buf27, (4, 1), (1, 4), 0)
del buf27
triton_poi_fused__softmax_add_leaky_relu_mul_where_6[grid(4)](buf4,
buf37, buf35, buf36, buf38, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf39 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_add_leaky_relu_mul_where_7[grid(16)](buf4,
buf37, buf35, buf36, buf38, buf39, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf35
del buf36
del buf38
buf40 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(16)](buf39, buf40, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf41 = buf39
del buf39
extern_kernels.mm(buf40, buf34, out=buf41)
buf42 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_elu_8[grid(16)](buf41, buf42, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf43 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__log_softmax_9[grid(16)](buf42, buf43, 16, XBLOCK=
16, num_warps=1, num_stages=1)
del buf42
return (buf43, buf3, buf4, buf7, buf8, buf12, buf15, buf16, buf20,
buf23, buf24, buf28, buf31, buf32, buf37, buf40, buf41, buf43,
reinterpret_tensor(buf34, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_17, (1, 4), (1, 1), 0), reinterpret_tensor(primals_16, (1,
4), (1, 1), 0), reinterpret_tensor(buf33, (16, 4), (1, 16), 0),
reinterpret_tensor(primals_15, (4, 16), (1, 4), 0),
reinterpret_tensor(buf25, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_14, (1, 4), (1, 1), 0), reinterpret_tensor(primals_13, (1,
4), (1, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0),
reinterpret_tensor(buf17, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_11, (1, 4), (1, 1), 0), reinterpret_tensor(primals_10, (1,
4), (1, 1), 0), reinterpret_tensor(buf9, (4, 4), (1, 4), 0),
reinterpret_tensor(primals_8, (1, 4), (1, 1), 0),
reinterpret_tensor(primals_7, (1, 4), (1, 1), 0),
reinterpret_tensor(buf0, (4, 4), (1, 4), 0), reinterpret_tensor(
primals_4, (1, 4), (1, 1), 0), reinterpret_tensor(primals_3, (1, 4),
(1, 1), 0))
class GraphAttention(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttention, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
self.W = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
in_features, out_features).type(torch.FloatTensor if torch.cuda
.is_available() else torch.FloatTensor), gain=np.sqrt(2.0)),
requires_grad=True)
self.a1 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(torch.FloatTensor if torch.cuda.
is_available() else torch.FloatTensor), gain=np.sqrt(2.0)),
requires_grad=True)
self.a2 = nn.Parameter(nn.init.xavier_normal_(torch.Tensor(
out_features, 1).type(torch.FloatTensor if torch.cuda.
is_available() else torch.FloatTensor), gain=np.sqrt(2.0)),
requires_grad=True)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, input, adj):
h = torch.mm(input, self.W)
h.size()[0]
f_1 = torch.matmul(h, self.a1)
f_2 = torch.matmul(h, self.a2)
e = self.leakyrelu(f_1 + f_2.transpose(0, 1))
zero_vec = -9000000000000000.0 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, h)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GATNew(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
super(GATNew, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttention(nfeat, nhid, dropout=dropout,
alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
self.out_att = GraphAttention(nhid * nheads, nclass, dropout=
dropout, alpha=alpha, concat=False)
def forward(self, input_0, input_1):
primals_1 = self.attention_0.W
primals_3 = self.attention_0.a1
primals_4 = self.attention_0.a2
primals_2 = self.attention_1.W
primals_7 = self.attention_1.a1
primals_8 = self.attention_1.a2
primals_5 = self.attention_2.W
primals_10 = self.attention_2.a1
primals_11 = self.attention_2.a2
primals_6 = self.attention_3.W
primals_13 = self.attention_3.a1
primals_14 = self.attention_3.a2
primals_15 = self.out_att.W
primals_16 = self.out_att.a1
primals_17 = self.out_att.a2
primals_9 = input_0
primals_12 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17])
return output[0]
|
new2scala/graph-cnn.pytorch
|
GAT
| false
| 16,191
|
[
"MIT"
] | 330
|
8bee0c2ed687dcfdb277c71b70c8ea747b6ca9c7
|
https://github.com/new2scala/graph-cnn.pytorch/tree/8bee0c2ed687dcfdb277c71b70c8ea747b6ca9c7
|
SpatialAttention2d
|
import torch
import torch.nn
import torch.nn as nn
import torch.nn.parallel
class SpatialAttention2d(nn.Module):
"""
SpatialAttention2d
2-layer 1x1 conv network with softplus activation.
<!!!> attention score normalization will be added for experiment.
"""
def __init__(self, in_c, act_fn='relu'):
super(SpatialAttention2d, self).__init__()
self.conv1 = nn.Conv2d(in_c, 512, 1, 1)
if act_fn.lower() in ['relu']:
self.act1 = nn.ReLU()
elif act_fn.lower() in ['leakyrelu', 'leaky', 'leaky_relu']:
self.act1 = nn.LeakyReLU()
self.conv2 = nn.Conv2d(512, 1, 1, 1)
self.softplus = nn.Softplus(beta=1, threshold=20)
def forward(self, x):
"""
x : spatial feature map. (b x c x w x h)
s : softplus attention score
"""
x = self.conv1(x)
x = self.act1(x)
x = self.conv2(x)
x = self.softplus(x)
return x
def __repr__(self):
return self.__class__.__name__
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_c': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_softplus_2(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 = 20.0
tmp5 = tmp3 > tmp4
tmp6 = tl_math.exp(tmp3)
tmp7 = libdevice.log1p(tmp6)
tmp8 = tl.where(tmp5, tmp3, tmp7)
tl.store(in_out_ptr0 + x0, tmp3, xmask)
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (512, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (512,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 16)](primals_3, buf0, 16, 16, XBLOCK=16,
YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 512, 4, 4), (8192, 1, 2048, 512))
buf2 = buf1
del buf1
triton_poi_fused_convolution_relu_1[grid(32768)](buf2, primals_2,
32768, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 1, 4, 4), (16, 1, 4, 1))
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32)
triton_poi_fused_convolution_softplus_2[grid(64)](buf4, primals_5,
buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
return buf5, primals_1, buf0, primals_4, buf2, buf4
class SpatialAttention2dNew(nn.Module):
"""
SpatialAttention2d
2-layer 1x1 conv network with softplus activation.
<!!!> attention score normalization will be added for experiment.
"""
def __init__(self, in_c, act_fn='relu'):
super(SpatialAttention2dNew, self).__init__()
self.conv1 = nn.Conv2d(in_c, 512, 1, 1)
if act_fn.lower() in ['relu']:
self.act1 = nn.ReLU()
elif act_fn.lower() in ['leakyrelu', 'leaky', 'leaky_relu']:
self.act1 = nn.LeakyReLU()
self.conv2 = nn.Conv2d(512, 1, 1, 1)
self.softplus = nn.Softplus(beta=1, threshold=20)
def __repr__(self):
return self.__class__.__name__
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
nhonth/DeLF-pytorch
|
SpatialAttention2d
| false
| 16,192
|
[
"MIT"
] | 315
|
5577a447a0330b9e976cff56a10fc91669216b8c
|
https://github.com/nhonth/DeLF-pytorch/tree/5577a447a0330b9e976cff56a10fc91669216b8c
|
Discriminator
|
import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, state_dim, action_dim):
super(Discriminator, self).__init__()
self.l1 = nn.Linear(state_dim + action_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, 1)
def forward(self, state, action):
state_action = torch.cat([state, action], 1)
x = torch.tanh(self.l1(state_action))
x = torch.tanh(self.l2(x))
x = torch.sigmoid(self.l3(x))
return x
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4, 'action_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 400
tmp0 = tl.load(in_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_tanh_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 300
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_sigmoid_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (400, 8), (8, 1))
assert_size_stride(primals_4, (400,), (1,))
assert_size_stride(primals_5, (300, 400), (400, 1))
assert_size_stride(primals_6, (300,), (1,))
assert_size_stride(primals_7, (1, 300), (300, 1))
assert_size_stride(primals_8, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 400), (400, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 400), (1,
8), 0), out=buf1)
del primals_3
buf2 = buf1
del buf1
triton_poi_fused_tanh_1[grid(1600)](buf2, primals_4, 1600, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 300), (300, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (400, 300), (
1, 400), 0), out=buf3)
buf4 = buf3
del buf3
triton_poi_fused_tanh_2[grid(1200)](buf4, primals_6, 1200, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_7, (300, 1), (1,
300), 0), out=buf5)
buf6 = buf5
del buf5
triton_poi_fused_sigmoid_3[grid(4)](buf6, primals_8, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_8
return buf6, buf0, buf2, buf4, buf6, primals_7, primals_5
class DiscriminatorNew(nn.Module):
def __init__(self, state_dim, action_dim):
super(DiscriminatorNew, self).__init__()
self.l1 = nn.Linear(state_dim + action_dim, 400)
self.l2 = nn.Linear(400, 300)
self.l3 = nn.Linear(300, 1)
def forward(self, input_0, input_1):
primals_3 = self.l1.weight
primals_4 = self.l1.bias
primals_5 = self.l2.weight
primals_6 = self.l2.bias
primals_7 = self.l3.weight
primals_8 = self.l3.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
nikhilbarhate99/Deterministic-GAIL-PyTorch
|
Discriminator
| false
| 16,193
|
[
"MIT"
] | 64
|
36843739dd7b0ca58e9fcaf923cc6735a5d7ffef
|
https://github.com/nikhilbarhate99/Deterministic-GAIL-PyTorch/tree/36843739dd7b0ca58e9fcaf923cc6735a5d7ffef
|
MLP
|
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import *
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.fc2 = nn.Linear(512, 128)
self.fc3 = nn.Linear(128, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
output = F.log_softmax(self.fc3(x), dim=1)
return output
def get_inputs():
return [torch.rand([4, 784])]
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
from torch import nn
from torch.utils.data import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused__log_softmax_2(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 10
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 10 * x0), rmask & xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask & xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask & xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 - tmp11
tl.store(out_ptr2 + (r1 + 10 * x0), tmp12, rmask & xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 784), (784, 1))
assert_size_stride(primals_2, (512, 784), (784, 1))
assert_size_stride(primals_3, (512,), (1,))
assert_size_stride(primals_4, (128, 512), (512, 1))
assert_size_stride(primals_5, (128,), (1,))
assert_size_stride(primals_6, (10, 128), (128, 1))
assert_size_stride(primals_7, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (784,
512), (1, 784), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(2048)](buf1, primals_3, 2048, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (512, 128), (
1, 512), 0), out=buf2)
buf3 = buf2
del buf2
triton_poi_fused_relu_1[grid(512)](buf3, primals_5, 512, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_7, buf3, reinterpret_tensor(primals_6,
(128, 10), (1, 128), 0), alpha=1, beta=1, out=buf4)
del primals_7
buf7 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
triton_per_fused__log_softmax_2[grid(4)](buf4, buf7, 4, 10, XBLOCK=
1, num_warps=2, num_stages=1)
del buf4
return buf7, primals_1, buf1, buf3, buf7, primals_6, primals_4
class MLPNew(nn.Module):
def __init__(self):
super(MLPNew, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.fc2 = nn.Linear(512, 128)
self.fc3 = nn.Linear(128, 10)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
nox-410/nnfusion
|
MLP
| false
| 16,194
|
[
"MIT"
] | 639
|
0777e297299c4e7a5071dc2ee97b87adcd22840e
|
https://github.com/nox-410/nnfusion/tree/0777e297299c4e7a5071dc2ee97b87adcd22840e
|
TrTimeInvFIRFilter
|
import torch
from torch import nn
from torch.nn import functional as F
class TrTimeInvFIRFilter(nn.Conv1d):
"""Trainable Time-invatiant FIR filter implementation
H(z) = \\sigma_{k=0}^{filt_dim} b_{k}z_{-k}
Note that b_{0} is fixed to 1 if fixed_0th is True.
Args:
channels (int): input channels
filt_dim (int): FIR filter dimension
causal (bool): causal
tanh (bool): apply tanh to filter coef or not.
fixed_0th (bool): fix the first filt coef to 1 or not.
"""
def __init__(self, channels, filt_dim, causal=True, tanh=True,
fixed_0th=True):
init_filt_coef = torch.randn(filt_dim) * (1 / filt_dim)
kernel_size = len(init_filt_coef)
self.causal = causal
if causal:
padding = (kernel_size - 1) * 1
else:
padding = (kernel_size - 1) // 2 * 1
super(TrTimeInvFIRFilter, self).__init__(channels, channels,
kernel_size, padding=padding, groups=channels, bias=None)
self.weight.data[:, :, :] = init_filt_coef.flip(-1)
self.weight.requires_grad = True
self.tanh = tanh
self.fixed_0th = fixed_0th
def get_filt_coefs(self):
b = torch.tanh(self.weight) if self.tanh else self.weight
b = b.clone()
if self.fixed_0th:
b[:, :, -1] = 1
return b
def forward(self, x):
b = self.get_filt_coefs()
out = F.conv1d(x, b, self.bias, self.stride, self.padding, self.
dilation, self.groups)
if self.padding[0] > 0:
out = out[:, :, :-self.padding[0]] if self.causal else out
return out
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'channels': 4, 'filt_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_fill_lift_fresh_tanh_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
x1 = xindex % 4
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp2 = x1
tmp3 = tl.full([1], 3, tl.int32)
tmp4 = tmp2 == tmp3
tmp5 = 1.0
tmp6 = tl.where(tmp4, tmp5, tmp1)
tl.store(out_ptr0 + x0, tmp1, xmask)
tl.store(out_ptr1 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 4), (4, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_fill_lift_fresh_tanh_0[grid(16)](primals_1, buf0,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_1
buf2 = extern_kernels.convolution(primals_2, buf1, stride=(1,),
padding=(3,), dilation=(1,), transposed=False, output_padding=(
0,), groups=4, bias=None)
assert_size_stride(buf2, (4, 4, 7), (28, 7, 1))
return reinterpret_tensor(buf2, (4, 4, 4), (28, 7, 1), 0
), primals_2, buf0, buf1
class TrTimeInvFIRFilterNew(nn.Conv1d):
"""Trainable Time-invatiant FIR filter implementation
H(z) = \\sigma_{k=0}^{filt_dim} b_{k}z_{-k}
Note that b_{0} is fixed to 1 if fixed_0th is True.
Args:
channels (int): input channels
filt_dim (int): FIR filter dimension
causal (bool): causal
tanh (bool): apply tanh to filter coef or not.
fixed_0th (bool): fix the first filt coef to 1 or not.
"""
def __init__(self, channels, filt_dim, causal=True, tanh=True,
fixed_0th=True):
init_filt_coef = torch.randn(filt_dim) * (1 / filt_dim)
kernel_size = len(init_filt_coef)
self.causal = causal
if causal:
padding = (kernel_size - 1) * 1
else:
padding = (kernel_size - 1) // 2 * 1
super(TrTimeInvFIRFilterNew, self).__init__(channels, channels,
kernel_size, padding=padding, groups=channels, bias=None)
self.weight.data[:, :, :] = init_filt_coef.flip(-1)
self.weight.requires_grad = True
self.tanh = tanh
self.fixed_0th = fixed_0th
def get_filt_coefs(self):
b = torch.tanh(self.weight) if self.tanh else self.weight
b = b.clone()
if self.fixed_0th:
b[:, :, -1] = 1
return b
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
oatsu-gh/nnsvs
|
TrTimeInvFIRFilter
| false
| 16,195
|
[
"MIT"
] | 298
|
510f37bc1d1f15282646e4d34435b5d63686cf40
|
https://github.com/oatsu-gh/nnsvs/tree/510f37bc1d1f15282646e4d34435b5d63686cf40
|
SoftmaxScaleController
|
import torch
class ScaleControllerBase(torch.nn.Module):
"""
The base class for ScaleController.
ScaleController is a callable class that re-scale input tensor's value.
Traditional scale method may include:
soft-max, L2 normalize, relu and so on.
Advanced method:
Learnable scale parameter
"""
def __init__(self):
super(ScaleControllerBase, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
"""
Re-scale the input x into proper value scale.
:param x: the input tensor
:param dim: axis to scale(mostly used in traditional method)
:param p: p parameter used in traditional methods
:return: rescaled x
"""
raise NotImplementedError
class SoftmaxScaleController(ScaleControllerBase):
def __init__(self):
super(SoftmaxScaleController, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=2):
return torch.nn.functional.softmax(x, dim=dim)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf0, buf1, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf0
return buf1,
class ScaleControllerBase(torch.nn.Module):
"""
The base class for ScaleController.
ScaleController is a callable class that re-scale input tensor's value.
Traditional scale method may include:
soft-max, L2 normalize, relu and so on.
Advanced method:
Learnable scale parameter
"""
def __init__(self):
super(ScaleControllerBase, self).__init__()
def forward(self, x: 'torch.Tensor', dim: 'int'=0, p: 'int'=1):
"""
Re-scale the input x into proper value scale.
:param x: the input tensor
:param dim: axis to scale(mostly used in traditional method)
:param p: p parameter used in traditional methods
:return: rescaled x
"""
raise NotImplementedError
class SoftmaxScaleControllerNew(ScaleControllerBase):
def __init__(self):
super(SoftmaxScaleControllerNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
niloofar17/MetaDialog
|
SoftmaxScaleController
| false
| 16,196
|
[
"Apache-2.0"
] | 204
|
d75b84a02807d53d9596e72c2f698e5a4f180369
|
https://github.com/niloofar17/MetaDialog/tree/d75b84a02807d53d9596e72c2f698e5a4f180369
|
TimeIntervalMultiHeadAttention
|
import torch
import numpy as np
import torch.nn as nn
import torch.distributions
class TimeIntervalMultiHeadAttention(nn.Module):
def __init__(self, d_model, n_heads, kq_same=False, bias=True):
super().__init__()
"""
It also needs position and interaction (time interval) key/value input.
"""
self.d_model = d_model
self.h = n_heads
self.d_k = self.d_model // self.h
self.kq_same = kq_same
self.v_linear = nn.Linear(d_model, d_model, bias=bias)
self.k_linear = nn.Linear(d_model, d_model, bias=bias)
if not kq_same:
self.q_linear = nn.Linear(d_model, d_model, bias=bias)
def forward(self, q, k, v, pos_k, pos_v, inter_k, inter_v, mask):
bs, seq_len = k.size(0), k.size(1)
k = (self.k_linear(k) + pos_k).view(bs, seq_len, self.h, self.d_k)
if not self.kq_same:
q = self.q_linear(q).view(bs, seq_len, self.h, self.d_k)
else:
q = self.k_linear(q).view(bs, seq_len, self.h, self.d_k)
v = (self.v_linear(v) + pos_v).view(bs, seq_len, self.h, self.d_k)
k = k.transpose(1, 2)
q = q.transpose(1, 2)
v = v.transpose(1, 2)
inter_k = inter_k.view(bs, seq_len, seq_len, self.h, self.d_k)
inter_v = inter_v.view(bs, seq_len, seq_len, self.h, self.d_k)
inter_k = inter_k.transpose(2, 3).transpose(1, 2)
inter_v = inter_v.transpose(2, 3).transpose(1, 2)
output = self.scaled_dot_product_attention(q, k, v, inter_k,
inter_v, self.d_k, mask)
output = output.transpose(1, 2).reshape(bs, -1, self.d_model)
return output
@staticmethod
def scaled_dot_product_attention(q, k, v, inter_k, inter_v, d_k, mask):
"""
Involve pair interaction embeddings when calculating attention scores and output
"""
scores = torch.matmul(q, k.transpose(-2, -1))
scores += (q[:, :, :, None, :] * inter_k).sum(-1)
scores = scores / d_k ** 0.5
scores.masked_fill_(mask == 0, -np.inf)
scores = (scores - scores.max()).softmax(dim=-1)
output = torch.matmul(scores, v)
output += (scores[:, :, :, :, None] * inter_v).sum(-2)
return output
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4, 4, 1]), torch.rand([4, 4, 4, 4, 1]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'n_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 numpy as np
import torch.nn as nn
import torch.distributions
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, in_ptr2, 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
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + (y0 + 4 * x2 + 16 * y1), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_eq_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 == tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_div_masked_fill_3(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, 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
x4 = xindex
y0 = yindex % 4
y5 = yindex
x3 = xindex // 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x4 + 16 * y0), xmask & ymask, eviction_policy
='evict_last').to(tl.int1)
tmp1 = tl.load(in_out_ptr0 + (x4 + 16 * y5), xmask & ymask)
tmp2 = tl.load(in_ptr1 + (y0 + 4 * x3 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + y0, ymask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + (y0 + 4 * x4 + 64 * y1), xmask & ymask)
tmp4 = tmp2 + tmp3
tmp6 = tmp4 * tmp5
tmp7 = tmp1 + tmp6
tmp8 = 1.0
tmp9 = tmp7 * tmp8
tmp10 = float('-inf')
tmp11 = tl.where(tmp0, tmp10, tmp9)
tl.store(in_out_ptr0 + (x4 + 16 * y5), tmp11, xmask & ymask)
@triton.jit
def triton_per_fused_max_4(in_ptr0, out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp1, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp3, None)
@triton.jit
def triton_poi_fused__softmax_sub_5(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 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tmp0 - tmp2
tmp5 = tmp4 - tmp2
tmp6 = triton_helpers.maximum(tmp3, tmp5)
tmp8 = tmp7 - tmp2
tmp9 = triton_helpers.maximum(tmp6, tmp8)
tmp11 = tmp10 - tmp2
tmp12 = triton_helpers.maximum(tmp9, tmp11)
tmp13 = tmp3 - tmp12
tmp14 = tl_math.exp(tmp13)
tmp15 = tmp5 - tmp12
tmp16 = tl_math.exp(tmp15)
tmp17 = tmp14 + tmp16
tmp18 = tmp8 - tmp12
tmp19 = tl_math.exp(tmp18)
tmp20 = tmp17 + tmp19
tmp21 = tmp11 - tmp12
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp20 + tmp22
tl.store(out_ptr0 + x0, tmp12, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused__softmax_eq_isnan_logical_and_logical_or_sub_6(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp0 - tmp2
tmp5 = tmp3 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 / tmp7
tmp9 = tmp0 == tmp2
tmp10 = libdevice.isnan(tmp0).to(tl.int1)
tmp11 = libdevice.isnan(tmp2).to(tl.int1)
tmp12 = tmp10 & tmp11
tmp13 = tmp9 | tmp12
tl.store(out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr1 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_add_mul_sum_7(in_out_ptr0, in_ptr0, in_ptr1, 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
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_out_ptr0 + (x2 + 4 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (1 + 4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (4 + y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (8 + y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (3 + 4 * x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + (12 + y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tmp1 * tmp2
tmp6 = tmp4 * tmp5
tmp7 = tmp3 + tmp6
tmp10 = tmp8 * tmp9
tmp11 = tmp7 + tmp10
tmp14 = tmp12 * tmp13
tmp15 = tmp11 + tmp14
tmp16 = tmp0 + tmp15
tl.debug_barrier()
tl.store(in_out_ptr0 + (x2 + 4 * y3), tmp16, xmask & 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) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4), (16, 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), (16, 4, 1))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_11, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_12, (4, 4, 4, 4, 1), (64, 16, 4, 1, 1))
assert_size_stride(primals_13, (4, 4, 4, 4, 1), (64, 16, 4, 1, 1))
assert_size_stride(primals_14, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_7, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_10, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf2)
del primals_8
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_6, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(16, 4)](buf0, primals_3, primals_4,
buf4, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_3
del primals_4
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_eq_2[grid(64)](primals_14, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_14
buf7 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused_div_masked_fill_3[grid(16, 16)](buf7, buf6, buf1,
primals_6, primals_12, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=
4, num_stages=1)
del primals_6
buf8 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_max_4[grid(1)](buf7, buf8, 1, 256, num_warps=2,
num_stages=1)
buf9 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf1
buf10 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf0
triton_poi_fused__softmax_sub_5[grid(64)](buf7, buf8, buf9, buf10,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused__softmax_eq_isnan_logical_and_logical_or_sub_6[grid
(256)](buf7, buf8, buf9, buf10, buf11, buf15, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf10
del buf7
del buf8
buf12 = reinterpret_tensor(buf9, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf9
triton_poi_fused_clone_1[grid(16, 4)](buf2, primals_9, primals_11,
buf12, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
del primals_11
del primals_9
buf13 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf11, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf12, (16, 4, 1), (4, 1, 0), 0), out=buf13)
buf14 = reinterpret_tensor(buf13, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf13
triton_poi_fused_add_mul_sum_7[grid(16, 4)](buf14, buf11,
primals_13, 16, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
return reinterpret_tensor(buf14, (4, 4, 4), (16, 1, 4), 0
), primals_12, primals_13, reinterpret_tensor(primals_1, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_7, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_10, (16, 4), (4, 1), 0
), buf6, buf11, reinterpret_tensor(buf12, (16, 1, 4), (4, 1, 1), 0
), buf15, reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
class TimeIntervalMultiHeadAttentionNew(nn.Module):
def __init__(self, d_model, n_heads, kq_same=False, bias=True):
super().__init__()
"""
It also needs position and interaction (time interval) key/value input.
"""
self.d_model = d_model
self.h = n_heads
self.d_k = self.d_model // self.h
self.kq_same = kq_same
self.v_linear = nn.Linear(d_model, d_model, bias=bias)
self.k_linear = nn.Linear(d_model, d_model, bias=bias)
if not kq_same:
self.q_linear = nn.Linear(d_model, d_model, bias=bias)
@staticmethod
def scaled_dot_product_attention(q, k, v, inter_k, inter_v, d_k, mask):
"""
Involve pair interaction embeddings when calculating attention scores and output
"""
scores = torch.matmul(q, k.transpose(-2, -1))
scores += (q[:, :, :, None, :] * inter_k).sum(-1)
scores = scores / d_k ** 0.5
scores.masked_fill_(mask == 0, -np.inf)
scores = (scores - scores.max()).softmax(dim=-1)
output = torch.matmul(scores, v)
output += (scores[:, :, :, :, None] * inter_v).sum(-2)
return output
def forward(self, input_0, input_1, input_2, input_3, input_4, input_5,
input_6, input_7):
primals_2 = self.v_linear.weight
primals_3 = self.v_linear.bias
primals_5 = self.k_linear.weight
primals_6 = self.k_linear.bias
primals_8 = self.q_linear.weight
primals_9 = self.q_linear.bias
primals_1 = input_0
primals_4 = input_1
primals_7 = input_2
primals_10 = input_3
primals_11 = input_4
primals_12 = input_5
primals_13 = input_6
primals_14 = input_7
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]
|
nmrenyi/ReChorus
|
TimeIntervalMultiHeadAttention
| false
| 16,197
|
[
"MIT"
] | 314
|
9ab632579d0464b0aaf365539f87b04866920b66
|
https://github.com/nmrenyi/ReChorus/tree/9ab632579d0464b0aaf365539f87b04866920b66
|
MaxPooling
|
import torch
import torch.utils.data
import torch.nn as nn
import torch as torch
class MaxPooling(nn.Module):
def __init__(self):
super(MaxPooling, self).__init__()
def forward(self, input):
_b, _c, h, _w = input.size()
f_pool = nn.MaxPool2d((h, 1), (1, 1))
conv = f_pool(input)
_b, _c, h, _w = conv.size()
assert h == 1, 'the height of conv must be 1'
conv = conv.squeeze(2)
conv = conv.permute(2, 0, 1)
return conv
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
import torch as torch
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_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
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(64)](arg0_1, buf0,
64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 4, 4), (1, 16, 4), 0),
class MaxPoolingNew(nn.Module):
def __init__(self):
super(MaxPoolingNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
olivernina/nephi
|
MaxPooling
| false
| 16,198
|
[
"MIT"
] | 50
|
a25e74e58c24edb7dc051b79d106b3bc51c7a998
|
https://github.com/olivernina/nephi/tree/a25e74e58c24edb7dc051b79d106b3bc51c7a998
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.