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
|
|---|---|---|---|---|---|---|---|---|---|---|
cnn_7layer_alt
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class cnn_7layer_alt(nn.Module):
def __init__(self, in_ch, in_dim, width=2, linear_size=128):
super(cnn_7layer_alt, self).__init__()
self.conv1 = nn.Conv2d(in_ch, 4 * width, 3, stride=1, padding=1)
self.conv2 = nn.Conv2d(4 * width, 4 * width, 4, stride=2, padding=1)
self.conv3 = nn.Conv2d(4 * width, 8 * width, 3, stride=1, padding=1)
self.conv4 = nn.Conv2d(8 * width, 8 * width, 4, stride=2, padding=1)
self.fc1 = nn.Linear(8 * width * (in_dim // 4) * (in_dim // 4),
linear_size)
self.fc2 = nn.Linear(linear_size, linear_size)
self.fc3 = nn.Linear(linear_size, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
x = F.relu(self.conv4(x))
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_ch': 4, 'in_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 8
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 8
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_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
x3 = xindex
x1 = xindex // 4 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_3(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 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)
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, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (8, 8, 4, 4), (128, 16, 4, 1))
assert_size_stride(primals_5, (8,), (1,))
assert_size_stride(primals_6, (16, 8, 3, 3), (72, 9, 3, 1))
assert_size_stride(primals_7, (16,), (1,))
assert_size_stride(primals_8, (16, 16, 4, 4), (256, 16, 4, 1))
assert_size_stride(primals_9, (16,), (1,))
assert_size_stride(primals_10, (128, 16), (16, 1))
assert_size_stride(primals_11, (128,), (1,))
assert_size_stride(primals_12, (128, 128), (128, 1))
assert_size_stride(primals_13, (128,), (1,))
assert_size_stride(primals_14, (10, 128), (128, 1))
assert_size_stride(primals_15, (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, 8, 4, 4), (128, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(512)](buf1, primals_2, 512,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 8, 2, 2), (32, 4, 2, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(128)](buf3, primals_5, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 16, 2, 2), (64, 4, 2, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(256)](buf5, primals_7, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 16, 1, 1), (16, 1, 1, 1))
buf7 = reinterpret_tensor(buf6, (4, 16, 1, 1), (16, 1, 64, 64), 0)
del buf6
buf13 = empty_strided_cuda((4, 16, 1, 1), (16, 1, 1, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(64)](buf7,
primals_9, buf13, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (4, 16), (16, 1), 0),
reinterpret_tensor(primals_10, (16, 128), (1, 16), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(512)](buf9, primals_11, 512, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_11
buf10 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_12, (128, 128),
(1, 128), 0), out=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_4[grid(512)](buf11, primals_13, 512, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_13
buf12 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_15, buf11, reinterpret_tensor(
primals_14, (128, 10), (1, 128), 0), alpha=1, beta=1, out=buf12)
del primals_15
return (buf12, primals_1, primals_3, primals_4, primals_6, primals_8,
buf1, buf3, buf5, reinterpret_tensor(buf7, (4, 16), (16, 1), 0),
buf9, buf11, primals_14, primals_12, primals_10, buf13)
class cnn_7layer_altNew(nn.Module):
def __init__(self, in_ch, in_dim, width=2, linear_size=128):
super(cnn_7layer_altNew, self).__init__()
self.conv1 = nn.Conv2d(in_ch, 4 * width, 3, stride=1, padding=1)
self.conv2 = nn.Conv2d(4 * width, 4 * width, 4, stride=2, padding=1)
self.conv3 = nn.Conv2d(4 * width, 8 * width, 3, stride=1, padding=1)
self.conv4 = nn.Conv2d(8 * width, 8 * width, 4, stride=2, padding=1)
self.fc1 = nn.Linear(8 * width * (in_dim // 4) * (in_dim // 4),
linear_size)
self.fc2 = nn.Linear(linear_size, linear_size)
self.fc3 = nn.Linear(linear_size, 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.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.fc1.weight
primals_11 = self.fc1.bias
primals_12 = self.fc2.weight
primals_13 = self.fc2.bias
primals_14 = self.fc3.weight
primals_15 = 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, primals_14,
primals_15])
return output[0]
|
mnmueller/auto_LiRPA
|
cnn_7layer_alt
| false
| 7,278
|
[
"BSD-3-Clause"
] | 1
|
55cb270b0b99f07b74541d55706c69fbb9daff66
|
https://github.com/mnmueller/auto_LiRPA/tree/55cb270b0b99f07b74541d55706c69fbb9daff66
|
Inception
|
import torch
import torch.nn as nn
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1,
padding=0, output_relu=True):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=
kernel_size, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(out_planes)
self.relu = nn.ReLU() if output_relu else None
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
if self.relu:
x = self.relu(x)
return x
class Inception(nn.Module):
def __init__(self, channel, batch_norm=False):
super(Inception, self).__init__()
if batch_norm is False:
self.branch1x1 = nn.Conv2d(channel[0], channel[1], kernel_size=
(1, 1), stride=1)
self.branch3x3_1 = nn.Conv2d(channel[0], channel[2],
kernel_size=(1, 1), stride=1)
self.branch3x3_2 = nn.Conv2d(channel[2], channel[3],
kernel_size=(3, 3), stride=1, padding=1)
self.branch5x5_1 = nn.Conv2d(channel[0], channel[4],
kernel_size=(1, 1), stride=1)
self.branch5x5_2 = nn.Conv2d(channel[4], channel[5],
kernel_size=(5, 5), stride=1, padding=2)
self.branchM_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.branchM_2 = nn.Conv2d(channel[0], channel[6], kernel_size=
(1, 1), stride=1)
else:
self.branch1x1 = BasicConv2d(channel[0], channel[1],
kernel_size=(1, 1), stride=1)
self.branch3x3_1 = BasicConv2d(channel[0], channel[2],
kernel_size=(1, 1), stride=1)
self.branch3x3_2 = BasicConv2d(channel[2], channel[3],
kernel_size=(3, 3), stride=1, padding=1)
self.branch5x5_1 = BasicConv2d(channel[0], channel[4],
kernel_size=(1, 1), stride=1)
self.branch5x5_2 = BasicConv2d(channel[4], channel[5],
kernel_size=(5, 5), stride=1, padding=2)
self.branchM_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.branchM_2 = BasicConv2d(channel[0], channel[6],
kernel_size=(1, 1), stride=1)
self.relu = nn.ReLU(True)
def forward(self, x):
branch1x1 = self.relu(self.branch1x1(x))
branch3x3_1 = self.relu(self.branch3x3_1(x))
branch3x3_2 = self.relu(self.branch3x3_2(branch3x3_1))
branch5x5_1 = self.relu(self.branch5x5_1(x))
branch5x5_2 = self.relu(self.branch5x5_2(branch5x5_1))
branchM_1 = self.relu(self.branchM_1(x))
branchM_2 = self.relu(self.branchM_2(branchM_1))
outputs = [branch1x1, branch3x3_2, branch5x5_2, branchM_2]
return torch.cat(outputs, 1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channel': [4, 4, 4, 4, 4, 4, 4]}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_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
x1 = xindex // 4 % 4
x0 = xindex % 4
x3 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-5 + x3), tmp10 & xmask, other=float('-inf'))
tmp12 = x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-4 + x3), tmp16 & xmask, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-3 + x3), tmp23 & xmask, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = x1
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (-1 + x3), tmp30 & xmask, other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + x3, tmp33 & xmask, other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (1 + x3), tmp36 & xmask, other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = 1 + x1
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (3 + x3), tmp43 & xmask, other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp38)
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (4 + x3), tmp46 & xmask, other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (5 + x3), tmp49 & xmask, other=float('-inf'))
tmp51 = triton_helpers.maximum(tmp50, tmp48)
tmp52 = tl.full([1], 0, tl.int32)
tmp53 = triton_helpers.maximum(tmp52, tmp51)
tl.store(in_out_ptr0 + x3, tmp53, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, in_ptr6, in_ptr7, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 16
x0 = xindex % 16
x2 = xindex // 256
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tl.load(in_ptr1 + x1, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tmp13 = tl.full([1], 8, tl.int64)
tmp14 = tmp0 < tmp13
tmp15 = tmp12 & tmp14
tmp16 = tl.load(in_ptr2 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp15 &
xmask, other=0.0)
tmp17 = tl.load(in_ptr3 + (-4 + x1), tmp15 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp18 = tmp16 + tmp17
tmp19 = triton_helpers.maximum(tmp8, tmp18)
tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype)
tmp21 = tl.where(tmp15, tmp19, tmp20)
tmp22 = tmp0 >= tmp13
tmp23 = tl.full([1], 12, tl.int64)
tmp24 = tmp0 < tmp23
tmp25 = tmp22 & tmp24
tmp26 = tl.load(in_ptr4 + (x0 + 16 * (-8 + x1) + 64 * x2), tmp25 &
xmask, other=0.0)
tmp27 = tl.load(in_ptr5 + (-8 + x1), tmp25 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp28 = tmp26 + tmp27
tmp29 = triton_helpers.maximum(tmp8, tmp28)
tmp30 = tl.full(tmp29.shape, 0.0, tmp29.dtype)
tmp31 = tl.where(tmp25, tmp29, tmp30)
tmp32 = tmp0 >= tmp23
tl.full([1], 16, tl.int64)
tmp35 = tl.load(in_ptr6 + (x0 + 16 * (-12 + x1) + 64 * x2), tmp32 &
xmask, other=0.0)
tmp36 = tl.load(in_ptr7 + (-12 + x1), tmp32 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp37 = tmp35 + tmp36
tmp38 = triton_helpers.maximum(tmp8, tmp37)
tmp39 = tl.full(tmp38.shape, 0.0, tmp38.dtype)
tmp40 = tl.where(tmp32, tmp38, tmp39)
tmp41 = tl.where(tmp25, tmp31, tmp40)
tmp42 = tl.where(tmp15, tmp21, tmp41)
tmp43 = tl.where(tmp4, tmp11, tmp42)
tl.store(out_ptr0 + x3, tmp43, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_3(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_7, (4,), (1,))
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, (4, 4, 5, 5), (100, 25, 5, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(256)](buf2, primals_5, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf3 = extern_kernels.convolution(buf2, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = extern_kernels.convolution(primals_3, primals_8, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_0[grid(256)](buf5, primals_9, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf6 = extern_kernels.convolution(buf5, primals_10, stride=(1, 1),
padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1))
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf8 = buf7
del buf7
triton_poi_fused_max_pool2d_with_indices_relu_1[grid(256)](buf8,
primals_3, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf9 = extern_kernels.convolution(buf8, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 4, 4), (64, 16, 4, 1))
buf10 = empty_strided_cuda((4, 16, 4, 4), (256, 16, 4, 1), torch.
float32)
triton_poi_fused_cat_2[grid(1024)](buf0, primals_2, buf3, primals_7,
buf6, primals_11, buf9, primals_13, buf10, 1024, XBLOCK=256,
num_warps=4, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(256)](buf9,
primals_13, buf11, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf9
del primals_13
buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(256)](buf6,
primals_11, buf12, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf6
del primals_11
buf13 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(256)](buf3,
primals_7, buf13, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf3
del primals_7
buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_3[grid(256)](buf0,
primals_2, buf14, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
return (buf10, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, primals_12, buf2, buf5, buf8, buf11, buf12, buf13, buf14)
class BasicConv2d(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1,
padding=0, output_relu=True):
super(BasicConv2d, self).__init__()
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=
kernel_size, stride=stride, padding=padding, bias=False)
self.bn = nn.BatchNorm2d(out_planes)
self.relu = nn.ReLU() if output_relu else None
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
if self.relu:
x = self.relu(x)
return x
class InceptionNew(nn.Module):
def __init__(self, channel, batch_norm=False):
super(InceptionNew, self).__init__()
if batch_norm is False:
self.branch1x1 = nn.Conv2d(channel[0], channel[1], kernel_size=
(1, 1), stride=1)
self.branch3x3_1 = nn.Conv2d(channel[0], channel[2],
kernel_size=(1, 1), stride=1)
self.branch3x3_2 = nn.Conv2d(channel[2], channel[3],
kernel_size=(3, 3), stride=1, padding=1)
self.branch5x5_1 = nn.Conv2d(channel[0], channel[4],
kernel_size=(1, 1), stride=1)
self.branch5x5_2 = nn.Conv2d(channel[4], channel[5],
kernel_size=(5, 5), stride=1, padding=2)
self.branchM_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.branchM_2 = nn.Conv2d(channel[0], channel[6], kernel_size=
(1, 1), stride=1)
else:
self.branch1x1 = BasicConv2d(channel[0], channel[1],
kernel_size=(1, 1), stride=1)
self.branch3x3_1 = BasicConv2d(channel[0], channel[2],
kernel_size=(1, 1), stride=1)
self.branch3x3_2 = BasicConv2d(channel[2], channel[3],
kernel_size=(3, 3), stride=1, padding=1)
self.branch5x5_1 = BasicConv2d(channel[0], channel[4],
kernel_size=(1, 1), stride=1)
self.branch5x5_2 = BasicConv2d(channel[4], channel[5],
kernel_size=(5, 5), stride=1, padding=2)
self.branchM_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.branchM_2 = BasicConv2d(channel[0], channel[6],
kernel_size=(1, 1), stride=1)
self.relu = nn.ReLU(True)
def forward(self, input_0):
primals_1 = self.branch1x1.weight
primals_2 = self.branch1x1.bias
primals_4 = self.branch3x3_1.weight
primals_5 = self.branch3x3_1.bias
primals_6 = self.branch3x3_2.weight
primals_7 = self.branch3x3_2.bias
primals_8 = self.branch5x5_1.weight
primals_9 = self.branch5x5_1.bias
primals_10 = self.branch5x5_2.weight
primals_11 = self.branch5x5_2.bias
primals_12 = self.branchM_2.weight
primals_13 = self.branchM_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
moh2236945/pytorch_classification
|
Inception
| false
| 7,279
|
[
"MIT"
] | 1
|
8816f08af327e06208b348a78d9c63c133b6a628
|
https://github.com/moh2236945/pytorch_classification/tree/8816f08af327e06208b348a78d9c63c133b6a628
|
SharedAgent
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SharedAgent(torch.nn.Module):
"""
A simple two headed / chimera Actor Critic agent.
The actor and critic share the body of the network.
It is argued that this is because "good" actions
correlate to visiting states with "large" values, and
so there should exist some form of shared information
between these two functions, thus motivating the shared
body. However, I haven't seen a rigorous proof of this,
and training an AC model with a shared body usually just
leads to added complications in my experience. If you
know a good reference for a mathematical proof on why
this should be done please let me know!
"""
def __init__(self, numObs, numActions, numHidden):
super(SharedAgent, self).__init__()
self.shared_input = nn.Linear(numObs, numHidden)
self.shared_fc1 = nn.Linear(numHidden, numHidden)
self.shared_fc2 = nn.Linear(numHidden, 2 * numHidden)
self.actor_output = nn.Linear(2 * numHidden, numActions)
self.critic_output = nn.Linear(2 * numHidden, 1)
def forward(self, x):
x = F.relu(self.shared_input(x))
x = F.relu(self.shared_fc1(x))
x = F.relu(self.shared_fc2(x))
logits = self.actor_output(x)
value = self.critic_output(x)
return logits, value
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'numObs': 4, 'numActions': 4, 'numHidden': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 8
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
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, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (8, 4), (4, 1))
assert_size_stride(primals_7, (8,), (1,))
assert_size_stride(primals_8, (4, 8), (8, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (1, 8), (8, 1))
assert_size_stride(primals_11, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf11, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3,
primals_5, buf10, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 8), (8, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 8), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 8), (128, 32, 8, 1), 0)
del buf4
buf9 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(512)](buf5,
primals_7, buf9, 512, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 8), (
8, 1), 0), reinterpret_tensor(primals_8, (8, 4), (1, 8), 0),
alpha=1, beta=1, out=buf6)
del primals_9
buf8 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf5, (64, 8),
(8, 1), 0), reinterpret_tensor(primals_10, (8, 1), (1, 8), 0),
alpha=1, beta=1, out=buf8)
del primals_11
return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf8, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(
buf3, (64, 4), (4, 1), 0), reinterpret_tensor(buf5, (64, 8), (8, 1), 0
), primals_10, primals_8, buf9, primals_6, buf10, primals_4, buf11
class SharedAgentNew(torch.nn.Module):
"""
A simple two headed / chimera Actor Critic agent.
The actor and critic share the body of the network.
It is argued that this is because "good" actions
correlate to visiting states with "large" values, and
so there should exist some form of shared information
between these two functions, thus motivating the shared
body. However, I haven't seen a rigorous proof of this,
and training an AC model with a shared body usually just
leads to added complications in my experience. If you
know a good reference for a mathematical proof on why
this should be done please let me know!
"""
def __init__(self, numObs, numActions, numHidden):
super(SharedAgentNew, self).__init__()
self.shared_input = nn.Linear(numObs, numHidden)
self.shared_fc1 = nn.Linear(numHidden, numHidden)
self.shared_fc2 = nn.Linear(numHidden, 2 * numHidden)
self.actor_output = nn.Linear(2 * numHidden, numActions)
self.critic_output = nn.Linear(2 * numHidden, 1)
def forward(self, input_0):
primals_1 = self.shared_input.weight
primals_2 = self.shared_input.bias
primals_4 = self.shared_fc1.weight
primals_5 = self.shared_fc1.bias
primals_6 = self.shared_fc2.weight
primals_7 = self.shared_fc2.bias
primals_8 = self.actor_output.weight
primals_9 = self.actor_output.bias
primals_10 = self.critic_output.weight
primals_11 = self.critic_output.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]
|
mpgussert/fundamentalRL
|
SharedAgent
| false
| 7,280
|
[
"MIT"
] | 1
|
4f45436226e0823c21cac316dec8bbf1df697467
|
https://github.com/mpgussert/fundamentalRL/tree/4f45436226e0823c21cac316dec8bbf1df697467
|
BoundNot
|
from _paritybench_helpers import _mock_config
import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import MSELoss
def isnan(x):
if isinstance(x, Patches):
return False
return torch.isnan(x).any()
class Perturbation:
def __init__(self):
pass
def set_eps(self, eps):
self.eps = eps
def concretize(self, x, A, sign=-1, aux=None):
raise NotImplementedError
def init(self, x, aux=None, forward=False):
raise NotImplementedError
class PerturbationL0Norm(Perturbation):
def __init__(self, eps, x_L=None, x_U=None, ratio=1.0):
self.eps = eps
self.x_U = x_U
self.x_L = x_L
self.ratio = ratio
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
eps = math.ceil(self.eps)
x = x.reshape(x.shape[0], -1, 1)
center = A.matmul(x)
x = x.reshape(x.shape[0], 1, -1)
original = A * x.expand(x.shape[0], A.shape[-2], x.shape[2])
neg_mask = A < 0
pos_mask = A >= 0
if sign == 1:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = A[pos_mask] - original[pos_mask]
A_diff[neg_mask] = -original[neg_mask]
else:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = original[pos_mask]
A_diff[neg_mask] = original[neg_mask] - A[neg_mask]
A_diff, _ = torch.sort(A_diff, dim=2, descending=True)
bound = center + sign * A_diff[:, :, :eps].sum(dim=2).unsqueeze(2
) * self.ratio
return bound.squeeze(2)
def init(self, x, aux=None, forward=False):
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
return 'PerturbationLpNorm(norm=0, eps={})'.format(self.eps)
class PerturbationLpNorm(Perturbation):
def __init__(self, eps, norm=np.inf, x_L=None, x_U=None):
self.eps = eps
self.norm = norm
self.dual_norm = 1 if norm == np.inf else np.float64(1.0) / (1 -
1.0 / self.norm)
self.x_L = x_L
self.x_U = x_U
"""Given an variable x and its bound matrix A, compute worst case bound according to Lp norm."""
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
def concretize_matrix(A):
nonlocal x
if not isinstance(A, eyeC):
A = A.reshape(A.shape[0], A.shape[1], -1)
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
x_ub = x_U.reshape(x_U.shape[0], -1, 1)
x_lb = x_L.reshape(x_L.shape[0], -1, 1)
center = (x_ub + x_lb) / 2.0
diff = (x_ub - x_lb) / 2.0
if not isinstance(A, eyeC):
bound = A.matmul(center) + sign * A.abs().matmul(diff)
else:
bound = center + sign * diff
else:
x = x.reshape(x.shape[0], -1, 1)
if not isinstance(A, eyeC):
deviation = A.norm(self.dual_norm, -1) * self.eps
bound = A.matmul(x) + sign * deviation.unsqueeze(-1)
else:
bound = x + sign * self.eps
bound = bound.squeeze(-1)
return bound
def concretize_patches(A):
nonlocal x
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
center = (x_U + x_L) / 2.0
diff = (x_U - x_L) / 2.0
if not A.identity == 1:
unfold_input = F.unfold(center, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound = prod.view(prod.size(0), prod.size(1), int(math.
sqrt(prod.size(2))), int(math.sqrt(prod.size(2))))
unfold_input = F.unfold(diff, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches.abs()
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound += sign * prod.view(prod.size(0), prod.size(1),
int(math.sqrt(prod.size(2))), int(math.sqrt(prod.
size(2))))
else:
bound = center + sign * diff
return bound
else:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
raise NotImplementedError()
if isinstance(A, eyeC) or isinstance(A, torch.Tensor):
return concretize_matrix(A)
elif isinstance(A, Patches):
return concretize_patches(A)
elif isinstance(A, BoundList):
for b in A.bound_list:
if isinstance(b, eyeC) or isinstance(b, torch.Tensor):
pass
else:
raise NotImplementedError()
def init(self, x, aux=None, forward=False):
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
else:
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
if self.norm == np.inf:
if self.x_L is None and self.x_U is None:
return 'PerturbationLpNorm(norm=inf, eps={})'.format(self.eps)
else:
return ('PerturbationLpNorm(norm=inf, eps={}, x_L={}, x_U={})'
.format(self.eps, self.x_L, self.x_U))
else:
return 'PerturbationLpNorm(norm={}, eps={})'.format(self.norm,
self.eps)
class PerturbationSynonym(Perturbation):
def __init__(self, budget, eps=1.0, use_simple=False):
super(PerturbationSynonym, self).__init__()
self._load_synonyms()
self.budget = budget
self.eps = eps
self.use_simple = use_simple
self.model = None
self.train = False
def __repr__(self):
return (
'perturbation(Synonym-based word substitution budget={}, eps={})'
.format(self.budget, self.eps))
def _load_synonyms(self, path='data/synonyms.json'):
with open(path) as file:
self.synonym = json.loads(file.read())
logger.info('Synonym list loaded for {} words'.format(len(self.
synonym)))
def set_train(self, train):
self.train = train
def concretize(self, x, A, sign, aux):
assert self.model is not None
x_rep, mask, can_be_replaced = aux
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
dim_out = A.shape[1]
max_num_cand = x_rep.shape[2]
mask_rep = torch.tensor(can_be_replaced, dtype=torch.float32,
device=A.device)
num_pos = int(np.max(np.sum(can_be_replaced, axis=-1)))
update_A = A.shape[-1] > num_pos * dim_word
if update_A:
bias = torch.bmm(A, (x * (1 - mask_rep).unsqueeze(-1)).reshape(
batch_size, -1, 1)).squeeze(-1)
else:
bias = 0.0
A = A.reshape(batch_size, dim_out, -1, dim_word)
A_new, x_new, x_rep_new, mask_new = [], [], [], []
zeros_A = torch.zeros(dim_out, dim_word, device=A.device)
zeros_w = torch.zeros(dim_word, device=A.device)
zeros_rep = torch.zeros(max_num_cand, dim_word, device=A.device)
zeros_mask = torch.zeros(max_num_cand, device=A.device)
for t in range(batch_size):
cnt = 0
for i in range(0, length):
if can_be_replaced[t][i]:
if update_A:
A_new.append(A[t, :, i, :])
x_new.append(x[t][i])
x_rep_new.append(x_rep[t][i])
mask_new.append(mask[t][i])
cnt += 1
if update_A:
A_new += [zeros_A] * (num_pos - cnt)
x_new += [zeros_w] * (num_pos - cnt)
x_rep_new += [zeros_rep] * (num_pos - cnt)
mask_new += [zeros_mask] * (num_pos - cnt)
if update_A:
A = torch.cat(A_new).reshape(batch_size, num_pos, dim_out, dim_word
).transpose(1, 2)
x = torch.cat(x_new).reshape(batch_size, num_pos, dim_word)
x_rep = torch.cat(x_rep_new).reshape(batch_size, num_pos,
max_num_cand, dim_word)
mask = torch.cat(mask_new).reshape(batch_size, num_pos, max_num_cand)
length = num_pos
A = A.reshape(batch_size, A.shape[1], length, -1).transpose(1, 2)
x = x.reshape(batch_size, length, -1, 1)
if sign == 1:
cmp, init = torch.max, -1e+30
else:
cmp, init = torch.min, 1e+30
init_tensor = torch.ones(batch_size, dim_out) * init
dp = [([init_tensor] * (self.budget + 1)) for i in range(0, length + 1)
]
dp[0][0] = torch.zeros(batch_size, dim_out)
A = A.reshape(batch_size * length, A.shape[2], A.shape[3])
Ax = torch.bmm(A, x.reshape(batch_size * length, x.shape[2], x.
shape[3])).reshape(batch_size, length, A.shape[1])
Ax_rep = torch.bmm(A, x_rep.reshape(batch_size * length,
max_num_cand, x.shape[2]).transpose(-1, -2)).reshape(batch_size,
length, A.shape[1], max_num_cand)
Ax_rep = Ax_rep * mask.unsqueeze(2) + init * (1 - mask).unsqueeze(2)
Ax_rep_bound = cmp(Ax_rep, dim=-1).values
if self.use_simple and self.train:
return torch.sum(cmp(Ax, Ax_rep_bound), dim=1) + bias
for i in range(1, length + 1):
dp[i][0] = dp[i - 1][0] + Ax[:, i - 1]
for j in range(1, self.budget + 1):
dp[i][j] = cmp(dp[i - 1][j] + Ax[:, i - 1], dp[i - 1][j - 1
] + Ax_rep_bound[:, i - 1])
dp = torch.cat(dp[length], dim=0).reshape(self.budget + 1,
batch_size, dim_out)
return cmp(dp, dim=0).values + bias
def init(self, x, aux=None, forward=False):
tokens, batch = aux
self.tokens = tokens
assert len(x.shape) == 3
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
max_pos = 1
can_be_replaced = np.zeros((batch_size, length), dtype=np.bool)
self._build_substitution(batch)
for t in range(batch_size):
cnt = 0
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
for i in range(len(tokens[t])):
if tokens[t][i] == '[UNK]' or len(candidates[i]
) == 0 or tokens[t][i] != candidates[i][0]:
continue
for w in candidates[i][1:]:
if w in self.model.vocab:
can_be_replaced[t][i] = True
cnt += 1
break
max_pos = max(max_pos, cnt)
dim = max_pos * dim_word
if forward:
eye = torch.eye(dim_word)
lw = torch.zeros(batch_size, dim, length, dim_word)
lb = torch.zeros_like(x)
word_embeddings = self.model.word_embeddings.weight
vocab = self.model.vocab
x_rep = [[[] for i in range(length)] for t in range(batch_size)]
max_num_cand = 1
for t in range(batch_size):
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
cnt = 0
for i in range(length):
if can_be_replaced[t][i]:
word_embed = word_embeddings[vocab[tokens[t][i]]]
other_embed = x[t, i] - word_embed
if forward:
lw[t, cnt * dim_word:(cnt + 1) * dim_word, i, :] = eye
lb[t, i, :] = torch.zeros_like(word_embed)
for w in candidates[i][1:]:
if w in self.model.vocab:
x_rep[t][i].append(word_embeddings[self.model.
vocab[w]] + other_embed)
max_num_cand = max(max_num_cand, len(x_rep[t][i]))
cnt += 1
elif forward:
lb[t, i, :] = x[t, i, :]
if forward:
uw, ub = lw, lb
else:
lw = lb = uw = ub = None
zeros = torch.zeros(dim_word, device=x.device)
x_rep_, mask = [], []
for t in range(batch_size):
for i in range(length):
x_rep_ += x_rep[t][i] + [zeros] * (max_num_cand - len(x_rep
[t][i]))
mask += [1] * len(x_rep[t][i]) + [0] * (max_num_cand - len(
x_rep[t][i]))
x_rep_ = torch.cat(x_rep_).reshape(batch_size, length, max_num_cand,
dim_word)
mask = torch.tensor(mask, dtype=torch.float32, device=x.device
).reshape(batch_size, length, max_num_cand)
x_rep_ = x_rep_ * self.eps + x.unsqueeze(2) * (1 - self.eps)
inf = 1e+20
lower = torch.min(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * inf, dim=2).values
upper = torch.max(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * -inf, dim=2).values
lower = torch.min(lower, x)
upper = torch.max(upper, x)
return LinearBound(lw, lb, uw, ub, lower, upper), x, (x_rep_, mask,
can_be_replaced)
def _build_substitution(self, batch):
for t, example in enumerate(batch):
if 'candidates' not in example or example['candidates'] is None:
candidates = []
tokens = example['sentence'].strip().lower().split(' ')
for i in range(len(tokens)):
_cand = []
if tokens[i] in self.synonym:
for w in self.synonym[tokens[i]]:
if w in self.model.vocab:
_cand.append(w)
if len(_cand) > 0:
_cand = [tokens[i]] + _cand
candidates.append(_cand)
example['candidates'] = candidates
class Interval(tuple):
def __new__(self, lb=None, ub=None, ptb=None):
if ub is None:
assert isinstance(lb, tuple)
lb, ub = lb
return tuple.__new__(Interval, (lb, ub))
def __init__(self, lb, ub, ptb=None):
if ptb is None:
self.ptb = None
assert lb is ub
elif not isinstance(ptb, Perturbation):
raise ValueError(
'ptb must be a Perturbation object or None. Got type {}'.
format(type(ptb)))
else:
self.ptb = ptb
def __str__(self):
return '({}, {}) with ptb={}'.format(self[0], self[1], self.ptb)
def __repr__(self):
return 'Interval(lb={}, ub={}, ptb={})'.format(self[0], self[1],
self.ptb)
"""Checking if the other interval is tuple, keep the perturbation."""
@staticmethod
def make_interval(lb, ub, other):
if isinstance(other, Interval):
return Interval(lb, ub, other.ptb)
else:
return lb, ub
"""Given a tuple or Interval object, returns the norm and eps."""
@staticmethod
def get_perturbation(interval):
if isinstance(interval, Interval):
if isinstance(interval.ptb, PerturbationLpNorm):
return interval.ptb.norm, interval.ptb.eps
elif isinstance(interval.ptb, PerturbationSynonym):
return np.inf, 1.0
elif isinstance(interval.ptb, PerturbationL0Norm):
return 0, interval.ptb.eps, interval.ptb.ratio
elif interval.ptb is None:
raise RuntimeError(
'get_perturbation() encountered an interval that is not perturbed.'
)
else:
raise RuntimeError(
'get_perturbation() does not know how to handle {}'.
format(type(interval.ptb)))
else:
return np.inf, np.nan
"""Checking if a Interval or tuple object has perturbation enabled."""
@staticmethod
def is_perturbed(interval):
if isinstance(interval, Interval) and interval.ptb is None:
return False
else:
return True
class Bound(nn.Module):
def __init__(self, input_name, name, ori_name, attr={}, inputs=[],
output_index=0, options={}, device=None):
super().__init__()
self.output_name = []
(self.input_name, self.name, self.ori_name, self.attr, self.inputs,
self.output_index, self.options, self.device) = (input_name,
name, ori_name, attr, inputs, output_index, options, device)
self.fv = None
self.from_input = False
self.bounded = False
self.IBP_rets = None
self.perturbed = False
if options is not None and 'loss_fusion' in options:
self.loss_fusion = options['loss_fusion']
else:
self.loss_fusion = False
"""Check if the i-th input is with perturbation or not."""
def is_input_perturbed(self, i=0):
return self.inputs[i].perturbed
def forward(self, *x):
raise NotImplementedError
def interval_propagate(self, *v):
assert len(v) == 1
h_L, h_U = v[0]
return Interval.make_interval(self.forward(h_L), self.forward(h_U),
v[0])
def bound_forward(self, dim_in, last):
raise NotImplementedError
def bound_backward(self, last_lA, last_uA):
raise NotImplementedError
def infer_batch_dim(self, batch_size, *x):
None
raise NotImplementedError
def broadcast_backward(self, A, x):
shape = x.default_shape
batch_dim = max(self.batch_dim, 0)
if isinstance(A, torch.Tensor):
if x.batch_dim == -1:
shape = torch.Size([A.shape[batch_dim + 1]] + list(shape))
dims = []
cnt_sum = A.ndim - len(shape) - 1
for i in range(1, A.ndim):
if i != self.batch_dim + 1 and cnt_sum > 0:
dims.append(i)
cnt_sum -= 1
if dims:
A = torch.sum(A, dim=dims)
else:
dims = list(range(1, 1 + A.ndim - 1 - len(shape)))
if dims:
A = torch.sum(A, dim=dims)
dims = []
for i in range(len(shape)):
if shape[i] == 1 and A.shape[i + 1] != 1:
dims.append(i + 1)
if dims:
A = torch.sum(A, dim=dims, keepdim=True)
assert A.shape[1:] == shape
elif type(A) == Patches:
pass
return A
@staticmethod
def broadcast_forward(dim_in, x, shape_res):
lw, lb, uw, ub = x.lw, x.lb, x.uw, x.ub
shape_x, shape_res = list(x.lb.shape), list(shape_res)
if lw is None:
lw = uw = torch.zeros(dim_in, *shape_x, device=lb.device)
has_batch_size = False
else:
has_batch_size = True
while len(shape_x) < len(shape_res):
if not has_batch_size:
lw, uw = lw.unsqueeze(0), uw.unsqueeze(0)
lb, ub = lb.unsqueeze(0), ub.unsqueeze(0)
shape_x = [1] + shape_x
has_batch_size = True
else:
lw, uw = lw.unsqueeze(2), uw.unsqueeze(2)
lb, ub = lb.unsqueeze(1), ub.unsqueeze(1)
shape_x = [shape_x[0], 1] + shape_x[1:]
repeat = [(shape_res[i] // shape_x[i]) for i in range(len(shape_x))]
lb, ub = lb.repeat(*repeat), ub.repeat(*repeat)
repeat = repeat[:1] + [1] + repeat[1:]
lw, uw = lw.repeat(*repeat), uw.repeat(*repeat)
return lw, lb, uw, ub
def get_bias(self, A, bias):
if A is None:
return 0
assert not isnan(A)
assert not isnan(bias)
if isinstance(A, torch.Tensor):
if torch.norm(A, p=1) < epsilon:
return 0
output_dim = A.shape[0]
if self.batch_dim != -1:
batch_size = A.shape[self.batch_dim + 1]
A_shape = [A.shape[0], np.prod(A.shape[1:self.batch_dim + 1
]).astype(np.int32), batch_size, np.prod(A.shape[self.
batch_dim + 2:]).astype(np.int32)]
A = A.reshape(*A_shape).permute(2, 0, 1, 3).reshape(batch_size,
output_dim, -1)
bias = bias.reshape(*A_shape[1:]).transpose(0, 1).reshape(
batch_size, -1, 1)
bias_new = A.matmul(bias).squeeze(-1).transpose(0, 1)
else:
batch_size = A.shape[1]
A = A.view(output_dim, batch_size, -1)
bias_new = A.matmul(bias.view(-1))
if isnan(bias_new):
return 0
else:
return bias_new
elif type(A) == Patches:
if torch.norm(A.patches, p=1) < epsilon:
return 0
if self.batch_dim != -1:
batch_size = bias.shape[0]
bias = F.unfold(bias, kernel_size=A.patches.size(-1),
stride=A.stride, padding=A.padding).transpose(-2, -1
).unsqueeze(-2)
bias.size(1)
patches = A.patches.view(A.patches.size(0), A.patches.size(
1), A.patches.size(-4), A.patches.size(-1) * A.patches.
size(-2) * A.patches.size(-3))
prod = bias * patches
bias_new = prod.sum(-1).transpose(-2, -1)
bias_new = bias_new.view(batch_size, bias_new.size(-2), int
(math.sqrt(bias_new.size(-1))), int(math.sqrt(bias_new.
size(-1))))
else:
patches = A.patches
patches_reshape = torch.sum(patches, dim=(-1, -2, -3)) * bias
patches_reshape = patches_reshape.transpose(-1, -2)
return patches_reshape.view(patches_reshape.size(0),
patches_reshape.size(1), int(math.sqrt(patches_reshape.
size(2))), -1).transpose(0, 1)
return bias_new
else:
return NotImplementedError()
class BoundNot(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs,
output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs,
output_index, options, device)
def forward(self, x):
return x.logical_not()
def infer_batch_dim(self, batch_size, *x):
return x[0]
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_name': 4, 'name': 4, 'ori_name': 4, 'attr': 4,
'inputs': 4, 'output_index': 4, 'options': _mock_config(loss_fusion
=MSELoss()), '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 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
@triton.jit
def triton_poi_fused_logical_not_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0 != 0
tmp2 = tmp1 == 0
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.bool)
get_raw_stream(0)
triton_poi_fused_logical_not_0[grid(256)](arg0_1, buf0, 256, XBLOCK
=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def isnan(x):
if isinstance(x, Patches):
return False
return torch.isnan(x).any()
class Perturbation:
def __init__(self):
pass
def set_eps(self, eps):
self.eps = eps
def concretize(self, x, A, sign=-1, aux=None):
raise NotImplementedError
def init(self, x, aux=None, forward=False):
raise NotImplementedError
class PerturbationL0Norm(Perturbation):
def __init__(self, eps, x_L=None, x_U=None, ratio=1.0):
self.eps = eps
self.x_U = x_U
self.x_L = x_L
self.ratio = ratio
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
eps = math.ceil(self.eps)
x = x.reshape(x.shape[0], -1, 1)
center = A.matmul(x)
x = x.reshape(x.shape[0], 1, -1)
original = A * x.expand(x.shape[0], A.shape[-2], x.shape[2])
neg_mask = A < 0
pos_mask = A >= 0
if sign == 1:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = A[pos_mask] - original[pos_mask]
A_diff[neg_mask] = -original[neg_mask]
else:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = original[pos_mask]
A_diff[neg_mask] = original[neg_mask] - A[neg_mask]
A_diff, _ = torch.sort(A_diff, dim=2, descending=True)
bound = center + sign * A_diff[:, :, :eps].sum(dim=2).unsqueeze(2
) * self.ratio
return bound.squeeze(2)
def init(self, x, aux=None, forward=False):
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
return 'PerturbationLpNorm(norm=0, eps={})'.format(self.eps)
class PerturbationLpNorm(Perturbation):
def __init__(self, eps, norm=np.inf, x_L=None, x_U=None):
self.eps = eps
self.norm = norm
self.dual_norm = 1 if norm == np.inf else np.float64(1.0) / (1 -
1.0 / self.norm)
self.x_L = x_L
self.x_U = x_U
"""Given an variable x and its bound matrix A, compute worst case bound according to Lp norm."""
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
def concretize_matrix(A):
nonlocal x
if not isinstance(A, eyeC):
A = A.reshape(A.shape[0], A.shape[1], -1)
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
x_ub = x_U.reshape(x_U.shape[0], -1, 1)
x_lb = x_L.reshape(x_L.shape[0], -1, 1)
center = (x_ub + x_lb) / 2.0
diff = (x_ub - x_lb) / 2.0
if not isinstance(A, eyeC):
bound = A.matmul(center) + sign * A.abs().matmul(diff)
else:
bound = center + sign * diff
else:
x = x.reshape(x.shape[0], -1, 1)
if not isinstance(A, eyeC):
deviation = A.norm(self.dual_norm, -1) * self.eps
bound = A.matmul(x) + sign * deviation.unsqueeze(-1)
else:
bound = x + sign * self.eps
bound = bound.squeeze(-1)
return bound
def concretize_patches(A):
nonlocal x
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
center = (x_U + x_L) / 2.0
diff = (x_U - x_L) / 2.0
if not A.identity == 1:
unfold_input = F.unfold(center, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound = prod.view(prod.size(0), prod.size(1), int(math.
sqrt(prod.size(2))), int(math.sqrt(prod.size(2))))
unfold_input = F.unfold(diff, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches.abs()
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound += sign * prod.view(prod.size(0), prod.size(1),
int(math.sqrt(prod.size(2))), int(math.sqrt(prod.
size(2))))
else:
bound = center + sign * diff
return bound
else:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
raise NotImplementedError()
if isinstance(A, eyeC) or isinstance(A, torch.Tensor):
return concretize_matrix(A)
elif isinstance(A, Patches):
return concretize_patches(A)
elif isinstance(A, BoundList):
for b in A.bound_list:
if isinstance(b, eyeC) or isinstance(b, torch.Tensor):
pass
else:
raise NotImplementedError()
def init(self, x, aux=None, forward=False):
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
else:
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
if self.norm == np.inf:
if self.x_L is None and self.x_U is None:
return 'PerturbationLpNorm(norm=inf, eps={})'.format(self.eps)
else:
return ('PerturbationLpNorm(norm=inf, eps={}, x_L={}, x_U={})'
.format(self.eps, self.x_L, self.x_U))
else:
return 'PerturbationLpNorm(norm={}, eps={})'.format(self.norm,
self.eps)
class PerturbationSynonym(Perturbation):
def __init__(self, budget, eps=1.0, use_simple=False):
super(PerturbationSynonym, self).__init__()
self._load_synonyms()
self.budget = budget
self.eps = eps
self.use_simple = use_simple
self.model = None
self.train = False
def __repr__(self):
return (
'perturbation(Synonym-based word substitution budget={}, eps={})'
.format(self.budget, self.eps))
def _load_synonyms(self, path='data/synonyms.json'):
with open(path) as file:
self.synonym = json.loads(file.read())
logger.info('Synonym list loaded for {} words'.format(len(self.
synonym)))
def set_train(self, train):
self.train = train
def concretize(self, x, A, sign, aux):
assert self.model is not None
x_rep, mask, can_be_replaced = aux
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
dim_out = A.shape[1]
max_num_cand = x_rep.shape[2]
mask_rep = torch.tensor(can_be_replaced, dtype=torch.float32,
device=A.device)
num_pos = int(np.max(np.sum(can_be_replaced, axis=-1)))
update_A = A.shape[-1] > num_pos * dim_word
if update_A:
bias = torch.bmm(A, (x * (1 - mask_rep).unsqueeze(-1)).reshape(
batch_size, -1, 1)).squeeze(-1)
else:
bias = 0.0
A = A.reshape(batch_size, dim_out, -1, dim_word)
A_new, x_new, x_rep_new, mask_new = [], [], [], []
zeros_A = torch.zeros(dim_out, dim_word, device=A.device)
zeros_w = torch.zeros(dim_word, device=A.device)
zeros_rep = torch.zeros(max_num_cand, dim_word, device=A.device)
zeros_mask = torch.zeros(max_num_cand, device=A.device)
for t in range(batch_size):
cnt = 0
for i in range(0, length):
if can_be_replaced[t][i]:
if update_A:
A_new.append(A[t, :, i, :])
x_new.append(x[t][i])
x_rep_new.append(x_rep[t][i])
mask_new.append(mask[t][i])
cnt += 1
if update_A:
A_new += [zeros_A] * (num_pos - cnt)
x_new += [zeros_w] * (num_pos - cnt)
x_rep_new += [zeros_rep] * (num_pos - cnt)
mask_new += [zeros_mask] * (num_pos - cnt)
if update_A:
A = torch.cat(A_new).reshape(batch_size, num_pos, dim_out, dim_word
).transpose(1, 2)
x = torch.cat(x_new).reshape(batch_size, num_pos, dim_word)
x_rep = torch.cat(x_rep_new).reshape(batch_size, num_pos,
max_num_cand, dim_word)
mask = torch.cat(mask_new).reshape(batch_size, num_pos, max_num_cand)
length = num_pos
A = A.reshape(batch_size, A.shape[1], length, -1).transpose(1, 2)
x = x.reshape(batch_size, length, -1, 1)
if sign == 1:
cmp, init = torch.max, -1e+30
else:
cmp, init = torch.min, 1e+30
init_tensor = torch.ones(batch_size, dim_out) * init
dp = [([init_tensor] * (self.budget + 1)) for i in range(0, length + 1)
]
dp[0][0] = torch.zeros(batch_size, dim_out)
A = A.reshape(batch_size * length, A.shape[2], A.shape[3])
Ax = torch.bmm(A, x.reshape(batch_size * length, x.shape[2], x.
shape[3])).reshape(batch_size, length, A.shape[1])
Ax_rep = torch.bmm(A, x_rep.reshape(batch_size * length,
max_num_cand, x.shape[2]).transpose(-1, -2)).reshape(batch_size,
length, A.shape[1], max_num_cand)
Ax_rep = Ax_rep * mask.unsqueeze(2) + init * (1 - mask).unsqueeze(2)
Ax_rep_bound = cmp(Ax_rep, dim=-1).values
if self.use_simple and self.train:
return torch.sum(cmp(Ax, Ax_rep_bound), dim=1) + bias
for i in range(1, length + 1):
dp[i][0] = dp[i - 1][0] + Ax[:, i - 1]
for j in range(1, self.budget + 1):
dp[i][j] = cmp(dp[i - 1][j] + Ax[:, i - 1], dp[i - 1][j - 1
] + Ax_rep_bound[:, i - 1])
dp = torch.cat(dp[length], dim=0).reshape(self.budget + 1,
batch_size, dim_out)
return cmp(dp, dim=0).values + bias
def init(self, x, aux=None, forward=False):
tokens, batch = aux
self.tokens = tokens
assert len(x.shape) == 3
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
max_pos = 1
can_be_replaced = np.zeros((batch_size, length), dtype=np.bool)
self._build_substitution(batch)
for t in range(batch_size):
cnt = 0
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
for i in range(len(tokens[t])):
if tokens[t][i] == '[UNK]' or len(candidates[i]
) == 0 or tokens[t][i] != candidates[i][0]:
continue
for w in candidates[i][1:]:
if w in self.model.vocab:
can_be_replaced[t][i] = True
cnt += 1
break
max_pos = max(max_pos, cnt)
dim = max_pos * dim_word
if forward:
eye = torch.eye(dim_word)
lw = torch.zeros(batch_size, dim, length, dim_word)
lb = torch.zeros_like(x)
word_embeddings = self.model.word_embeddings.weight
vocab = self.model.vocab
x_rep = [[[] for i in range(length)] for t in range(batch_size)]
max_num_cand = 1
for t in range(batch_size):
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
cnt = 0
for i in range(length):
if can_be_replaced[t][i]:
word_embed = word_embeddings[vocab[tokens[t][i]]]
other_embed = x[t, i] - word_embed
if forward:
lw[t, cnt * dim_word:(cnt + 1) * dim_word, i, :] = eye
lb[t, i, :] = torch.zeros_like(word_embed)
for w in candidates[i][1:]:
if w in self.model.vocab:
x_rep[t][i].append(word_embeddings[self.model.
vocab[w]] + other_embed)
max_num_cand = max(max_num_cand, len(x_rep[t][i]))
cnt += 1
elif forward:
lb[t, i, :] = x[t, i, :]
if forward:
uw, ub = lw, lb
else:
lw = lb = uw = ub = None
zeros = torch.zeros(dim_word, device=x.device)
x_rep_, mask = [], []
for t in range(batch_size):
for i in range(length):
x_rep_ += x_rep[t][i] + [zeros] * (max_num_cand - len(x_rep
[t][i]))
mask += [1] * len(x_rep[t][i]) + [0] * (max_num_cand - len(
x_rep[t][i]))
x_rep_ = torch.cat(x_rep_).reshape(batch_size, length, max_num_cand,
dim_word)
mask = torch.tensor(mask, dtype=torch.float32, device=x.device
).reshape(batch_size, length, max_num_cand)
x_rep_ = x_rep_ * self.eps + x.unsqueeze(2) * (1 - self.eps)
inf = 1e+20
lower = torch.min(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * inf, dim=2).values
upper = torch.max(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * -inf, dim=2).values
lower = torch.min(lower, x)
upper = torch.max(upper, x)
return LinearBound(lw, lb, uw, ub, lower, upper), x, (x_rep_, mask,
can_be_replaced)
def _build_substitution(self, batch):
for t, example in enumerate(batch):
if 'candidates' not in example or example['candidates'] is None:
candidates = []
tokens = example['sentence'].strip().lower().split(' ')
for i in range(len(tokens)):
_cand = []
if tokens[i] in self.synonym:
for w in self.synonym[tokens[i]]:
if w in self.model.vocab:
_cand.append(w)
if len(_cand) > 0:
_cand = [tokens[i]] + _cand
candidates.append(_cand)
example['candidates'] = candidates
class Interval(tuple):
def __new__(self, lb=None, ub=None, ptb=None):
if ub is None:
assert isinstance(lb, tuple)
lb, ub = lb
return tuple.__new__(Interval, (lb, ub))
def __init__(self, lb, ub, ptb=None):
if ptb is None:
self.ptb = None
assert lb is ub
elif not isinstance(ptb, Perturbation):
raise ValueError(
'ptb must be a Perturbation object or None. Got type {}'.
format(type(ptb)))
else:
self.ptb = ptb
def __str__(self):
return '({}, {}) with ptb={}'.format(self[0], self[1], self.ptb)
def __repr__(self):
return 'Interval(lb={}, ub={}, ptb={})'.format(self[0], self[1],
self.ptb)
"""Checking if the other interval is tuple, keep the perturbation."""
@staticmethod
def make_interval(lb, ub, other):
if isinstance(other, Interval):
return Interval(lb, ub, other.ptb)
else:
return lb, ub
"""Given a tuple or Interval object, returns the norm and eps."""
@staticmethod
def get_perturbation(interval):
if isinstance(interval, Interval):
if isinstance(interval.ptb, PerturbationLpNorm):
return interval.ptb.norm, interval.ptb.eps
elif isinstance(interval.ptb, PerturbationSynonym):
return np.inf, 1.0
elif isinstance(interval.ptb, PerturbationL0Norm):
return 0, interval.ptb.eps, interval.ptb.ratio
elif interval.ptb is None:
raise RuntimeError(
'get_perturbation() encountered an interval that is not perturbed.'
)
else:
raise RuntimeError(
'get_perturbation() does not know how to handle {}'.
format(type(interval.ptb)))
else:
return np.inf, np.nan
"""Checking if a Interval or tuple object has perturbation enabled."""
@staticmethod
def is_perturbed(interval):
if isinstance(interval, Interval) and interval.ptb is None:
return False
else:
return True
class Bound(nn.Module):
def __init__(self, input_name, name, ori_name, attr={}, inputs=[],
output_index=0, options={}, device=None):
super().__init__()
self.output_name = []
(self.input_name, self.name, self.ori_name, self.attr, self.inputs,
self.output_index, self.options, self.device) = (input_name,
name, ori_name, attr, inputs, output_index, options, device)
self.fv = None
self.from_input = False
self.bounded = False
self.IBP_rets = None
self.perturbed = False
if options is not None and 'loss_fusion' in options:
self.loss_fusion = options['loss_fusion']
else:
self.loss_fusion = False
"""Check if the i-th input is with perturbation or not."""
def is_input_perturbed(self, i=0):
return self.inputs[i].perturbed
def forward(self, *x):
raise NotImplementedError
def interval_propagate(self, *v):
assert len(v) == 1
h_L, h_U = v[0]
return Interval.make_interval(self.forward(h_L), self.forward(h_U),
v[0])
def bound_forward(self, dim_in, last):
raise NotImplementedError
def bound_backward(self, last_lA, last_uA):
raise NotImplementedError
def infer_batch_dim(self, batch_size, *x):
None
raise NotImplementedError
def broadcast_backward(self, A, x):
shape = x.default_shape
batch_dim = max(self.batch_dim, 0)
if isinstance(A, torch.Tensor):
if x.batch_dim == -1:
shape = torch.Size([A.shape[batch_dim + 1]] + list(shape))
dims = []
cnt_sum = A.ndim - len(shape) - 1
for i in range(1, A.ndim):
if i != self.batch_dim + 1 and cnt_sum > 0:
dims.append(i)
cnt_sum -= 1
if dims:
A = torch.sum(A, dim=dims)
else:
dims = list(range(1, 1 + A.ndim - 1 - len(shape)))
if dims:
A = torch.sum(A, dim=dims)
dims = []
for i in range(len(shape)):
if shape[i] == 1 and A.shape[i + 1] != 1:
dims.append(i + 1)
if dims:
A = torch.sum(A, dim=dims, keepdim=True)
assert A.shape[1:] == shape
elif type(A) == Patches:
pass
return A
@staticmethod
def broadcast_forward(dim_in, x, shape_res):
lw, lb, uw, ub = x.lw, x.lb, x.uw, x.ub
shape_x, shape_res = list(x.lb.shape), list(shape_res)
if lw is None:
lw = uw = torch.zeros(dim_in, *shape_x, device=lb.device)
has_batch_size = False
else:
has_batch_size = True
while len(shape_x) < len(shape_res):
if not has_batch_size:
lw, uw = lw.unsqueeze(0), uw.unsqueeze(0)
lb, ub = lb.unsqueeze(0), ub.unsqueeze(0)
shape_x = [1] + shape_x
has_batch_size = True
else:
lw, uw = lw.unsqueeze(2), uw.unsqueeze(2)
lb, ub = lb.unsqueeze(1), ub.unsqueeze(1)
shape_x = [shape_x[0], 1] + shape_x[1:]
repeat = [(shape_res[i] // shape_x[i]) for i in range(len(shape_x))]
lb, ub = lb.repeat(*repeat), ub.repeat(*repeat)
repeat = repeat[:1] + [1] + repeat[1:]
lw, uw = lw.repeat(*repeat), uw.repeat(*repeat)
return lw, lb, uw, ub
def get_bias(self, A, bias):
if A is None:
return 0
assert not isnan(A)
assert not isnan(bias)
if isinstance(A, torch.Tensor):
if torch.norm(A, p=1) < epsilon:
return 0
output_dim = A.shape[0]
if self.batch_dim != -1:
batch_size = A.shape[self.batch_dim + 1]
A_shape = [A.shape[0], np.prod(A.shape[1:self.batch_dim + 1
]).astype(np.int32), batch_size, np.prod(A.shape[self.
batch_dim + 2:]).astype(np.int32)]
A = A.reshape(*A_shape).permute(2, 0, 1, 3).reshape(batch_size,
output_dim, -1)
bias = bias.reshape(*A_shape[1:]).transpose(0, 1).reshape(
batch_size, -1, 1)
bias_new = A.matmul(bias).squeeze(-1).transpose(0, 1)
else:
batch_size = A.shape[1]
A = A.view(output_dim, batch_size, -1)
bias_new = A.matmul(bias.view(-1))
if isnan(bias_new):
return 0
else:
return bias_new
elif type(A) == Patches:
if torch.norm(A.patches, p=1) < epsilon:
return 0
if self.batch_dim != -1:
batch_size = bias.shape[0]
bias = F.unfold(bias, kernel_size=A.patches.size(-1),
stride=A.stride, padding=A.padding).transpose(-2, -1
).unsqueeze(-2)
bias.size(1)
patches = A.patches.view(A.patches.size(0), A.patches.size(
1), A.patches.size(-4), A.patches.size(-1) * A.patches.
size(-2) * A.patches.size(-3))
prod = bias * patches
bias_new = prod.sum(-1).transpose(-2, -1)
bias_new = bias_new.view(batch_size, bias_new.size(-2), int
(math.sqrt(bias_new.size(-1))), int(math.sqrt(bias_new.
size(-1))))
else:
patches = A.patches
patches_reshape = torch.sum(patches, dim=(-1, -2, -3)) * bias
patches_reshape = patches_reshape.transpose(-1, -2)
return patches_reshape.view(patches_reshape.size(0),
patches_reshape.size(1), int(math.sqrt(patches_reshape.
size(2))), -1).transpose(0, 1)
return bias_new
else:
return NotImplementedError()
class BoundNotNew(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs,
output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs,
output_index, options, device)
def infer_batch_dim(self, batch_size, *x):
return x[0]
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
mnmueller/auto_LiRPA
|
BoundNot
| false
| 7,281
|
[
"BSD-3-Clause"
] | 1
|
55cb270b0b99f07b74541d55706c69fbb9daff66
|
https://github.com/mnmueller/auto_LiRPA/tree/55cb270b0b99f07b74541d55706c69fbb9daff66
|
Net5
|
import torch
from torch import nn
from torch.nn.init import kaiming_normal
from torch.nn.init import normal
def weights_init(m):
if isinstance(m, (nn.Conv1d, nn.Linear)):
kaiming_normal(m.weight.data)
try:
kaiming_normal(m.bias.data)
except ValueError:
normal(m.bias.data)
class Net5(nn.Module):
"""
Net5 is a neural network consisting of five hidden layers with sizes 400,
300, 200, 100 and 60
Furthermore there are three dropout layers
"""
hidden1 = 400
hidden2 = 300
hidden3 = 200
hidden4 = 100
hidden5 = 60
def __init__(self, input_size):
super(Net5, self).__init__()
self.fc1 = nn.Linear(input_size, self.hidden1)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(self.hidden1, self.hidden2)
self.relu2 = nn.ReLU()
self.drop1 = nn.Dropout(0.2)
self.fc3 = nn.Linear(self.hidden2, self.hidden3)
self.relu3 = nn.ReLU()
self.drop2 = nn.Dropout(0.15)
self.fc4 = nn.Linear(self.hidden3, self.hidden4)
self.relu4 = nn.ReLU()
self.drop3 = nn.Dropout(0.15)
self.fc5 = nn.Linear(self.hidden4, self.hidden5)
self.relu5 = nn.ReLU()
self.fc6 = nn.Linear(self.hidden5, 1)
self.apply(weights_init)
def forward(self, x):
out = self.fc1(x)
out = self.relu1(out)
out = self.fc2(out)
out = self.relu2(out)
out = self.drop1(out)
out = self.fc3(out)
out = self.relu3(out)
out = self.drop2(out)
out = self.fc4(out)
out = self.relu4(out)
out = self.drop3(out)
out = self.fc5(out)
out = self.relu5(out)
out = self.fc6(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
from torch.nn.init import kaiming_normal
from torch.nn.init import normal
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 25600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 400
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 300
x2 = xindex // 1200
x3 = xindex % 1200
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x3 + 1216 * x2), tmp4, xmask)
tl.store(out_ptr1 + (x3 + 1280 * x2), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_view_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 300
x1 = xindex // 300
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 300 * (x1 % 4) + 1216 * (x1 // 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 12800
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 200
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_4(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 100
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_5(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 3840
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 60
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, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (400, 4), (4, 1))
assert_size_stride(primals_2, (400,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (300, 400), (400, 1))
assert_size_stride(primals_5, (300,), (1,))
assert_size_stride(primals_6, (200, 300), (300, 1))
assert_size_stride(primals_7, (200,), (1,))
assert_size_stride(primals_8, (100, 200), (200, 1))
assert_size_stride(primals_9, (100,), (1,))
assert_size_stride(primals_10, (60, 100), (100, 1))
assert_size_stride(primals_11, (60,), (1,))
assert_size_stride(primals_12, (1, 60), (60, 1))
assert_size_stride(primals_13, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 400), (400, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 400), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 400), (6400, 1600, 400, 1), 0
)
del buf0
buf17 = empty_strided_cuda((4, 4, 4, 400), (6656, 1664, 400, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(25600)](buf1,
primals_2, buf17, 25600, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 400), (400, 1), 0),
reinterpret_tensor(primals_4, (400, 300), (1, 400), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 300), (4864, 1216, 300, 1),
torch.float32)
buf16 = empty_strided_cuda((4, 4, 4, 300), (5120, 1280, 300, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(19200)](buf2,
primals_5, buf3, buf16, 19200, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_5
buf4 = buf2
del buf2
triton_poi_fused_relu_view_2[grid(19200)](buf3, buf4, 19200, XBLOCK
=128, num_warps=4, num_stages=1)
del buf3
buf5 = empty_strided_cuda((64, 200), (200, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_6, (300, 200), (
1, 300), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 200), (3200, 800, 200, 1), 0)
del buf5
buf15 = empty_strided_cuda((4, 4, 4, 200), (3200, 800, 200, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(12800)](buf6,
primals_7, buf15, 12800, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf7 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 200), (200, 1), 0),
reinterpret_tensor(primals_8, (200, 100), (1, 200), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf7
buf14 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_4[grid(6400)](buf8,
primals_9, buf14, 6400, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf9 = empty_strided_cuda((64, 60), (60, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf8, (64, 100), (100, 1), 0),
reinterpret_tensor(primals_10, (100, 60), (1, 100), 0), out=buf9)
buf10 = reinterpret_tensor(buf9, (4, 4, 4, 60), (960, 240, 60, 1), 0)
del buf9
buf13 = empty_strided_cuda((4, 4, 4, 60), (960, 240, 60, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_5[grid(3840)](buf10,
primals_11, buf13, 3840, XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf12 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf10, (64, 60),
(60, 1), 0), reinterpret_tensor(primals_12, (60, 1), (1, 60), 0
), alpha=1, beta=1, out=buf12)
del primals_13
return (reinterpret_tensor(buf12, (4, 4, 4, 1), (16, 4, 1, 1), 0),
reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (64, 400), (400, 1), 0), buf4,
reinterpret_tensor(buf6, (64, 200), (200, 1), 0),
reinterpret_tensor(buf8, (64, 100), (100, 1), 0),
reinterpret_tensor(buf10, (64, 60), (60, 1), 0), primals_12, buf13,
primals_10, buf14, primals_8, buf15, primals_6, buf16, primals_4, buf17
)
def weights_init(m):
if isinstance(m, (nn.Conv1d, nn.Linear)):
kaiming_normal(m.weight.data)
try:
kaiming_normal(m.bias.data)
except ValueError:
normal(m.bias.data)
class Net5New(nn.Module):
"""
Net5 is a neural network consisting of five hidden layers with sizes 400,
300, 200, 100 and 60
Furthermore there are three dropout layers
"""
hidden1 = 400
hidden2 = 300
hidden3 = 200
hidden4 = 100
hidden5 = 60
def __init__(self, input_size):
super(Net5New, self).__init__()
self.fc1 = nn.Linear(input_size, self.hidden1)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(self.hidden1, self.hidden2)
self.relu2 = nn.ReLU()
self.drop1 = nn.Dropout(0.2)
self.fc3 = nn.Linear(self.hidden2, self.hidden3)
self.relu3 = nn.ReLU()
self.drop2 = nn.Dropout(0.15)
self.fc4 = nn.Linear(self.hidden3, self.hidden4)
self.relu4 = nn.ReLU()
self.drop3 = nn.Dropout(0.15)
self.fc5 = nn.Linear(self.hidden4, self.hidden5)
self.relu5 = nn.ReLU()
self.fc6 = nn.Linear(self.hidden5, 1)
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_8 = self.fc4.weight
primals_9 = self.fc4.bias
primals_10 = self.fc5.weight
primals_11 = self.fc5.bias
primals_12 = self.fc6.weight
primals_13 = self.fc6.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]
|
moritzschaefer/pavooc
|
Net5
| false
| 7,282
|
[
"MIT"
] | 1
|
735f5455f9a95a5734436a24e2aa92cf600c91af
|
https://github.com/moritzschaefer/pavooc/tree/735f5455f9a95a5734436a24e2aa92cf600c91af
|
Net4
|
import torch
from torch import nn
from torch.nn.init import kaiming_normal
from torch.nn.init import normal
def weights_init(m):
if isinstance(m, (nn.Conv1d, nn.Linear)):
kaiming_normal(m.weight.data)
try:
kaiming_normal(m.bias.data)
except ValueError:
normal(m.bias.data)
class Net4(nn.Module):
"""
Net4 is a neural network consisting of five hidden layers with sizes 400,
300, 200, 100 and 60
"""
hidden1 = 400
hidden2 = 300
hidden3 = 200
hidden4 = 100
hidden5 = 60
def __init__(self, input_size):
super(Net4, self).__init__()
self.fc1 = nn.Linear(input_size, self.hidden1)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(self.hidden1, self.hidden2)
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(self.hidden2, self.hidden3)
self.relu3 = nn.ReLU()
self.fc4 = nn.Linear(self.hidden3, self.hidden4)
self.relu4 = nn.ReLU()
self.fc5 = nn.Linear(self.hidden4, self.hidden5)
self.relu5 = nn.ReLU()
self.fc6 = nn.Linear(self.hidden5, 1)
self.apply(weights_init)
def forward(self, x):
out = self.fc1(x)
out = self.relu1(out)
out = self.fc2(out)
out = self.relu2(out)
out = self.fc3(out)
out = self.relu3(out)
out = self.fc4(out)
out = self.relu4(out)
out = self.fc5(out)
out = self.relu5(out)
out = self.fc6(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
from torch.nn.init import kaiming_normal
from torch.nn.init import normal
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 25600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 400
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 300
x2 = xindex // 1200
x3 = xindex % 1200
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x3 + 1216 * x2), tmp4, xmask)
tl.store(out_ptr1 + (x3 + 1280 * x2), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_view_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 19200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 300
x1 = xindex // 300
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 300 * (x1 % 4) + 1216 * (x1 // 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_3(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 12800
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 200
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_4(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 100
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_5(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 3840
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 60
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, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (400, 4), (4, 1))
assert_size_stride(primals_2, (400,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (300, 400), (400, 1))
assert_size_stride(primals_5, (300,), (1,))
assert_size_stride(primals_6, (200, 300), (300, 1))
assert_size_stride(primals_7, (200,), (1,))
assert_size_stride(primals_8, (100, 200), (200, 1))
assert_size_stride(primals_9, (100,), (1,))
assert_size_stride(primals_10, (60, 100), (100, 1))
assert_size_stride(primals_11, (60,), (1,))
assert_size_stride(primals_12, (1, 60), (60, 1))
assert_size_stride(primals_13, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 400), (400, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 400), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 400), (6400, 1600, 400, 1), 0
)
del buf0
buf17 = empty_strided_cuda((4, 4, 4, 400), (6656, 1664, 400, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(25600)](buf1,
primals_2, buf17, 25600, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 300), (300, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 400), (400, 1), 0),
reinterpret_tensor(primals_4, (400, 300), (1, 400), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 300), (4864, 1216, 300, 1),
torch.float32)
buf16 = empty_strided_cuda((4, 4, 4, 300), (5120, 1280, 300, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(19200)](buf2,
primals_5, buf3, buf16, 19200, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_5
buf4 = buf2
del buf2
triton_poi_fused_relu_view_2[grid(19200)](buf3, buf4, 19200, XBLOCK
=128, num_warps=4, num_stages=1)
del buf3
buf5 = empty_strided_cuda((64, 200), (200, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_6, (300, 200), (
1, 300), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 200), (3200, 800, 200, 1), 0)
del buf5
buf15 = empty_strided_cuda((4, 4, 4, 200), (3200, 800, 200, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_3[grid(12800)](buf6,
primals_7, buf15, 12800, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf7 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 200), (200, 1), 0),
reinterpret_tensor(primals_8, (200, 100), (1, 200), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf7
buf14 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_4[grid(6400)](buf8,
primals_9, buf14, 6400, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf9 = empty_strided_cuda((64, 60), (60, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf8, (64, 100), (100, 1), 0),
reinterpret_tensor(primals_10, (100, 60), (1, 100), 0), out=buf9)
buf10 = reinterpret_tensor(buf9, (4, 4, 4, 60), (960, 240, 60, 1), 0)
del buf9
buf13 = empty_strided_cuda((4, 4, 4, 60), (960, 240, 60, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_5[grid(3840)](buf10,
primals_11, buf13, 3840, XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf12 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf10, (64, 60),
(60, 1), 0), reinterpret_tensor(primals_12, (60, 1), (1, 60), 0
), alpha=1, beta=1, out=buf12)
del primals_13
return (reinterpret_tensor(buf12, (4, 4, 4, 1), (16, 4, 1, 1), 0),
reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (64, 400), (400, 1), 0), buf4,
reinterpret_tensor(buf6, (64, 200), (200, 1), 0),
reinterpret_tensor(buf8, (64, 100), (100, 1), 0),
reinterpret_tensor(buf10, (64, 60), (60, 1), 0), primals_12, buf13,
primals_10, buf14, primals_8, buf15, primals_6, buf16, primals_4, buf17
)
def weights_init(m):
if isinstance(m, (nn.Conv1d, nn.Linear)):
kaiming_normal(m.weight.data)
try:
kaiming_normal(m.bias.data)
except ValueError:
normal(m.bias.data)
class Net4New(nn.Module):
"""
Net4 is a neural network consisting of five hidden layers with sizes 400,
300, 200, 100 and 60
"""
hidden1 = 400
hidden2 = 300
hidden3 = 200
hidden4 = 100
hidden5 = 60
def __init__(self, input_size):
super(Net4New, self).__init__()
self.fc1 = nn.Linear(input_size, self.hidden1)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(self.hidden1, self.hidden2)
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(self.hidden2, self.hidden3)
self.relu3 = nn.ReLU()
self.fc4 = nn.Linear(self.hidden3, self.hidden4)
self.relu4 = nn.ReLU()
self.fc5 = nn.Linear(self.hidden4, self.hidden5)
self.relu5 = nn.ReLU()
self.fc6 = nn.Linear(self.hidden5, 1)
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_8 = self.fc4.weight
primals_9 = self.fc4.bias
primals_10 = self.fc5.weight
primals_11 = self.fc5.bias
primals_12 = self.fc6.weight
primals_13 = self.fc6.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]
|
moritzschaefer/pavooc
|
Net4
| false
| 7,283
|
[
"MIT"
] | 1
|
735f5455f9a95a5734436a24e2aa92cf600c91af
|
https://github.com/moritzschaefer/pavooc/tree/735f5455f9a95a5734436a24e2aa92cf600c91af
|
NeuralNetMultiplePositionalArgumentsMultiOutputsWithoutDependency
|
import torch
import torch.nn
import torch.onnx
class NeuralNetMultiplePositionalArgumentsMultiOutputsWithoutDependency(torch
.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNetMultiplePositionalArgumentsMultiOutputsWithoutDependency
, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.fc2 = torch.nn.Linear(input_size, hidden_size)
self.relu1 = torch.nn.ReLU()
self.relu2 = torch.nn.ReLU()
def forward(self, input1, input2):
model_input = input1 + input2
out1 = self.fc1(model_input)
out2 = self.fc2(model_input)
out1 = self.relu1(out1)
out2 = self.relu2(out2)
return out1, out2
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn
import torch.onnx
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](primals_1, primals_2, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf2)
del primals_5
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256)](buf3,
primals_4, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_4
buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256)](buf4,
primals_6, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_6
return buf3, buf4, reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf5, buf6
class NeuralNetMultiplePositionalArgumentsMultiOutputsWithoutDependencyNew(
torch.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(
NeuralNetMultiplePositionalArgumentsMultiOutputsWithoutDependencyNew
, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.fc2 = torch.nn.Linear(input_size, hidden_size)
self.relu1 = torch.nn.ReLU()
self.relu2 = torch.nn.ReLU()
def forward(self, input_0, input_1):
primals_3 = self.fc1.weight
primals_4 = self.fc1.bias
primals_5 = self.fc2.weight
primals_6 = self.fc2.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0], output[1]
|
mrshu/onnxruntime
|
NeuralNetMultiplePositionalArgumentsMultiOutputsWithoutDependency
| false
| 7,284
|
[
"MIT"
] | 1
|
335edaa2c485ba0dec877bf4cdbd652e2d5d105c
|
https://github.com/mrshu/onnxruntime/tree/335edaa2c485ba0dec877bf4cdbd652e2d5d105c
|
NIN
|
import string
import torch
import numpy as np
import torch.utils.data
import torch
import torch.nn as nn
def _einsum(a, b, c, x, y):
einsum_str = '{},{}->{}'.format(''.join(a), ''.join(b), ''.join(c))
return torch.einsum(einsum_str, x, y)
def contract_inner(x, y):
"""tensordot(x, y, 1)."""
x_chars = list(string.ascii_lowercase[:len(x.shape)])
y_chars = list(string.ascii_lowercase[len(x.shape):len(y.shape) + len(x
.shape)])
y_chars[0] = x_chars[-1]
out_chars = x_chars[:-1] + y_chars[1:]
return _einsum(x_chars, y_chars, out_chars, x, y)
def variance_scaling(scale, mode, distribution, in_axis=1, out_axis=0,
dtype=torch.float32, device='cpu'):
def _compute_fans(shape, in_axis=1, out_axis=0):
receptive_field_size = np.prod(shape) / shape[in_axis] / shape[out_axis
]
fan_in = shape[in_axis] * receptive_field_size
fan_out = shape[out_axis] * receptive_field_size
return fan_in, fan_out
def init(shape, dtype=dtype, device=device):
fan_in, fan_out = _compute_fans(shape, in_axis, out_axis)
if mode == 'fan_in':
denominator = fan_in
elif mode == 'fan_out':
denominator = fan_out
elif mode == 'fan_avg':
denominator = (fan_in + fan_out) / 2
else:
raise ValueError(
'invalid mode for variance scaling initializer: {}'.format(
mode))
variance = scale / denominator
if distribution == 'normal':
return torch.randn(*shape, dtype=dtype, device=device) * np.sqrt(
variance)
elif distribution == 'uniform':
return (torch.rand(*shape, dtype=dtype, device=device) * 2.0 - 1.0
) * np.sqrt(3 * variance)
else:
raise ValueError(
'invalid distribution for variance scaling initializer')
return init
def default_init(scale=1.0):
"""The same initialization used in DDPM."""
scale = 1e-10 if scale == 0 else scale
return variance_scaling(scale, 'fan_avg', 'uniform')
class NIN(nn.Module):
def __init__(self, in_dim, num_units, init_scale=0.1):
super().__init__()
self.W = nn.Parameter(default_init(scale=init_scale)((in_dim,
num_units)), requires_grad=True)
self.b = nn.Parameter(torch.zeros(num_units), requires_grad=True)
def forward(self, x):
x = x.permute(0, 2, 3, 1)
y = contract_inner(x, self.W) + self.b
return y.permute(0, 3, 1, 2)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'num_units': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import string
import numpy as np
import torch.utils.data
import torch
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 1), (64, 16, 4, 1, 1), torch
.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((1, 64, 4), (256, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (1, 64, 4), (0, 4, 1),
0), reinterpret_tensor(primals_2, (1, 4, 4), (16, 4, 1), 0),
out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused_add_1[grid(256)](buf2, primals_3, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_3
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 1, 16, 4), 0
), reinterpret_tensor(buf0, (1, 4, 64), (256, 1, 4), 0)
def _einsum(a, b, c, x, y):
einsum_str = '{},{}->{}'.format(''.join(a), ''.join(b), ''.join(c))
return torch.einsum(einsum_str, x, y)
def contract_inner(x, y):
"""tensordot(x, y, 1)."""
x_chars = list(string.ascii_lowercase[:len(x.shape)])
y_chars = list(string.ascii_lowercase[len(x.shape):len(y.shape) + len(x
.shape)])
y_chars[0] = x_chars[-1]
out_chars = x_chars[:-1] + y_chars[1:]
return _einsum(x_chars, y_chars, out_chars, x, y)
def variance_scaling(scale, mode, distribution, in_axis=1, out_axis=0,
dtype=torch.float32, device='cpu'):
def _compute_fans(shape, in_axis=1, out_axis=0):
receptive_field_size = np.prod(shape) / shape[in_axis] / shape[out_axis
]
fan_in = shape[in_axis] * receptive_field_size
fan_out = shape[out_axis] * receptive_field_size
return fan_in, fan_out
def init(shape, dtype=dtype, device=device):
fan_in, fan_out = _compute_fans(shape, in_axis, out_axis)
if mode == 'fan_in':
denominator = fan_in
elif mode == 'fan_out':
denominator = fan_out
elif mode == 'fan_avg':
denominator = (fan_in + fan_out) / 2
else:
raise ValueError(
'invalid mode for variance scaling initializer: {}'.format(
mode))
variance = scale / denominator
if distribution == 'normal':
return torch.randn(*shape, dtype=dtype, device=device) * np.sqrt(
variance)
elif distribution == 'uniform':
return (torch.rand(*shape, dtype=dtype, device=device) * 2.0 - 1.0
) * np.sqrt(3 * variance)
else:
raise ValueError(
'invalid distribution for variance scaling initializer')
return init
def default_init(scale=1.0):
"""The same initialization used in DDPM."""
scale = 1e-10 if scale == 0 else scale
return variance_scaling(scale, 'fan_avg', 'uniform')
class NINNew(nn.Module):
def __init__(self, in_dim, num_units, init_scale=0.1):
super().__init__()
self.W = nn.Parameter(default_init(scale=init_scale)((in_dim,
num_units)), requires_grad=True)
self.b = nn.Parameter(torch.zeros(num_units), requires_grad=True)
def forward(self, input_0):
primals_2 = self.W
primals_3 = self.b
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
mrjavoman/Image-Super-Resolution-via-Iterative-Refinement
|
NIN
| false
| 7,285
|
[
"Apache-2.0"
] | 1
|
2eb11d972e8e024c3b1d7a84f90895e329b5b408
|
https://github.com/mrjavoman/Image-Super-Resolution-via-Iterative-Refinement/tree/2eb11d972e8e024c3b1d7a84f90895e329b5b408
|
NeuralNetMultiplePositionalArgumentsMultiOutputsWithDependency
|
import torch
import torch.nn
import torch.onnx
class NeuralNetMultiplePositionalArgumentsMultiOutputsWithDependency(torch.
nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNetMultiplePositionalArgumentsMultiOutputsWithDependency,
self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, input1, input2):
model_input = input1 + input2
out1 = self.fc1(model_input)
out1 = self.relu(out1)
out2 = self.fc2(out1)
return out1, out2
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn
import torch.onnx
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](primals_1, primals_2, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused_relu_1[grid(256)](buf2, primals_4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf2, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_6
return buf2, reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf2, primals_5
class NeuralNetMultiplePositionalArgumentsMultiOutputsWithDependencyNew(torch
.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNetMultiplePositionalArgumentsMultiOutputsWithDependencyNew
, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, input_0, input_1):
primals_3 = self.fc1.weight
primals_4 = self.fc1.bias
primals_5 = self.fc2.weight
primals_6 = self.fc2.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0], output[1]
|
mrshu/onnxruntime
|
NeuralNetMultiplePositionalArgumentsMultiOutputsWithDependency
| false
| 7,286
|
[
"MIT"
] | 1
|
335edaa2c485ba0dec877bf4cdbd652e2d5d105c
|
https://github.com/mrshu/onnxruntime/tree/335edaa2c485ba0dec877bf4cdbd652e2d5d105c
|
BoundReciprocal
|
from _paritybench_helpers import _mock_config
import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import MSELoss
def isnan(x):
if isinstance(x, Patches):
return False
return torch.isnan(x).any()
class Perturbation:
def __init__(self):
pass
def set_eps(self, eps):
self.eps = eps
def concretize(self, x, A, sign=-1, aux=None):
raise NotImplementedError
def init(self, x, aux=None, forward=False):
raise NotImplementedError
class PerturbationL0Norm(Perturbation):
def __init__(self, eps, x_L=None, x_U=None, ratio=1.0):
self.eps = eps
self.x_U = x_U
self.x_L = x_L
self.ratio = ratio
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
eps = math.ceil(self.eps)
x = x.reshape(x.shape[0], -1, 1)
center = A.matmul(x)
x = x.reshape(x.shape[0], 1, -1)
original = A * x.expand(x.shape[0], A.shape[-2], x.shape[2])
neg_mask = A < 0
pos_mask = A >= 0
if sign == 1:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = A[pos_mask] - original[pos_mask]
A_diff[neg_mask] = -original[neg_mask]
else:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = original[pos_mask]
A_diff[neg_mask] = original[neg_mask] - A[neg_mask]
A_diff, _ = torch.sort(A_diff, dim=2, descending=True)
bound = center + sign * A_diff[:, :, :eps].sum(dim=2).unsqueeze(2
) * self.ratio
return bound.squeeze(2)
def init(self, x, aux=None, forward=False):
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
return 'PerturbationLpNorm(norm=0, eps={})'.format(self.eps)
class PerturbationLpNorm(Perturbation):
def __init__(self, eps, norm=np.inf, x_L=None, x_U=None):
self.eps = eps
self.norm = norm
self.dual_norm = 1 if norm == np.inf else np.float64(1.0) / (1 -
1.0 / self.norm)
self.x_L = x_L
self.x_U = x_U
"""Given an variable x and its bound matrix A, compute worst case bound according to Lp norm."""
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
def concretize_matrix(A):
nonlocal x
if not isinstance(A, eyeC):
A = A.reshape(A.shape[0], A.shape[1], -1)
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
x_ub = x_U.reshape(x_U.shape[0], -1, 1)
x_lb = x_L.reshape(x_L.shape[0], -1, 1)
center = (x_ub + x_lb) / 2.0
diff = (x_ub - x_lb) / 2.0
if not isinstance(A, eyeC):
bound = A.matmul(center) + sign * A.abs().matmul(diff)
else:
bound = center + sign * diff
else:
x = x.reshape(x.shape[0], -1, 1)
if not isinstance(A, eyeC):
deviation = A.norm(self.dual_norm, -1) * self.eps
bound = A.matmul(x) + sign * deviation.unsqueeze(-1)
else:
bound = x + sign * self.eps
bound = bound.squeeze(-1)
return bound
def concretize_patches(A):
nonlocal x
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
center = (x_U + x_L) / 2.0
diff = (x_U - x_L) / 2.0
if not A.identity == 1:
unfold_input = F.unfold(center, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound = prod.view(prod.size(0), prod.size(1), int(math.
sqrt(prod.size(2))), int(math.sqrt(prod.size(2))))
unfold_input = F.unfold(diff, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches.abs()
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound += sign * prod.view(prod.size(0), prod.size(1),
int(math.sqrt(prod.size(2))), int(math.sqrt(prod.
size(2))))
else:
bound = center + sign * diff
return bound
else:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
raise NotImplementedError()
if isinstance(A, eyeC) or isinstance(A, torch.Tensor):
return concretize_matrix(A)
elif isinstance(A, Patches):
return concretize_patches(A)
elif isinstance(A, BoundList):
for b in A.bound_list:
if isinstance(b, eyeC) or isinstance(b, torch.Tensor):
pass
else:
raise NotImplementedError()
def init(self, x, aux=None, forward=False):
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
else:
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
if self.norm == np.inf:
if self.x_L is None and self.x_U is None:
return 'PerturbationLpNorm(norm=inf, eps={})'.format(self.eps)
else:
return ('PerturbationLpNorm(norm=inf, eps={}, x_L={}, x_U={})'
.format(self.eps, self.x_L, self.x_U))
else:
return 'PerturbationLpNorm(norm={}, eps={})'.format(self.norm,
self.eps)
class PerturbationSynonym(Perturbation):
def __init__(self, budget, eps=1.0, use_simple=False):
super(PerturbationSynonym, self).__init__()
self._load_synonyms()
self.budget = budget
self.eps = eps
self.use_simple = use_simple
self.model = None
self.train = False
def __repr__(self):
return (
'perturbation(Synonym-based word substitution budget={}, eps={})'
.format(self.budget, self.eps))
def _load_synonyms(self, path='data/synonyms.json'):
with open(path) as file:
self.synonym = json.loads(file.read())
logger.info('Synonym list loaded for {} words'.format(len(self.
synonym)))
def set_train(self, train):
self.train = train
def concretize(self, x, A, sign, aux):
assert self.model is not None
x_rep, mask, can_be_replaced = aux
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
dim_out = A.shape[1]
max_num_cand = x_rep.shape[2]
mask_rep = torch.tensor(can_be_replaced, dtype=torch.float32,
device=A.device)
num_pos = int(np.max(np.sum(can_be_replaced, axis=-1)))
update_A = A.shape[-1] > num_pos * dim_word
if update_A:
bias = torch.bmm(A, (x * (1 - mask_rep).unsqueeze(-1)).reshape(
batch_size, -1, 1)).squeeze(-1)
else:
bias = 0.0
A = A.reshape(batch_size, dim_out, -1, dim_word)
A_new, x_new, x_rep_new, mask_new = [], [], [], []
zeros_A = torch.zeros(dim_out, dim_word, device=A.device)
zeros_w = torch.zeros(dim_word, device=A.device)
zeros_rep = torch.zeros(max_num_cand, dim_word, device=A.device)
zeros_mask = torch.zeros(max_num_cand, device=A.device)
for t in range(batch_size):
cnt = 0
for i in range(0, length):
if can_be_replaced[t][i]:
if update_A:
A_new.append(A[t, :, i, :])
x_new.append(x[t][i])
x_rep_new.append(x_rep[t][i])
mask_new.append(mask[t][i])
cnt += 1
if update_A:
A_new += [zeros_A] * (num_pos - cnt)
x_new += [zeros_w] * (num_pos - cnt)
x_rep_new += [zeros_rep] * (num_pos - cnt)
mask_new += [zeros_mask] * (num_pos - cnt)
if update_A:
A = torch.cat(A_new).reshape(batch_size, num_pos, dim_out, dim_word
).transpose(1, 2)
x = torch.cat(x_new).reshape(batch_size, num_pos, dim_word)
x_rep = torch.cat(x_rep_new).reshape(batch_size, num_pos,
max_num_cand, dim_word)
mask = torch.cat(mask_new).reshape(batch_size, num_pos, max_num_cand)
length = num_pos
A = A.reshape(batch_size, A.shape[1], length, -1).transpose(1, 2)
x = x.reshape(batch_size, length, -1, 1)
if sign == 1:
cmp, init = torch.max, -1e+30
else:
cmp, init = torch.min, 1e+30
init_tensor = torch.ones(batch_size, dim_out) * init
dp = [([init_tensor] * (self.budget + 1)) for i in range(0, length + 1)
]
dp[0][0] = torch.zeros(batch_size, dim_out)
A = A.reshape(batch_size * length, A.shape[2], A.shape[3])
Ax = torch.bmm(A, x.reshape(batch_size * length, x.shape[2], x.
shape[3])).reshape(batch_size, length, A.shape[1])
Ax_rep = torch.bmm(A, x_rep.reshape(batch_size * length,
max_num_cand, x.shape[2]).transpose(-1, -2)).reshape(batch_size,
length, A.shape[1], max_num_cand)
Ax_rep = Ax_rep * mask.unsqueeze(2) + init * (1 - mask).unsqueeze(2)
Ax_rep_bound = cmp(Ax_rep, dim=-1).values
if self.use_simple and self.train:
return torch.sum(cmp(Ax, Ax_rep_bound), dim=1) + bias
for i in range(1, length + 1):
dp[i][0] = dp[i - 1][0] + Ax[:, i - 1]
for j in range(1, self.budget + 1):
dp[i][j] = cmp(dp[i - 1][j] + Ax[:, i - 1], dp[i - 1][j - 1
] + Ax_rep_bound[:, i - 1])
dp = torch.cat(dp[length], dim=0).reshape(self.budget + 1,
batch_size, dim_out)
return cmp(dp, dim=0).values + bias
def init(self, x, aux=None, forward=False):
tokens, batch = aux
self.tokens = tokens
assert len(x.shape) == 3
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
max_pos = 1
can_be_replaced = np.zeros((batch_size, length), dtype=np.bool)
self._build_substitution(batch)
for t in range(batch_size):
cnt = 0
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
for i in range(len(tokens[t])):
if tokens[t][i] == '[UNK]' or len(candidates[i]
) == 0 or tokens[t][i] != candidates[i][0]:
continue
for w in candidates[i][1:]:
if w in self.model.vocab:
can_be_replaced[t][i] = True
cnt += 1
break
max_pos = max(max_pos, cnt)
dim = max_pos * dim_word
if forward:
eye = torch.eye(dim_word)
lw = torch.zeros(batch_size, dim, length, dim_word)
lb = torch.zeros_like(x)
word_embeddings = self.model.word_embeddings.weight
vocab = self.model.vocab
x_rep = [[[] for i in range(length)] for t in range(batch_size)]
max_num_cand = 1
for t in range(batch_size):
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
cnt = 0
for i in range(length):
if can_be_replaced[t][i]:
word_embed = word_embeddings[vocab[tokens[t][i]]]
other_embed = x[t, i] - word_embed
if forward:
lw[t, cnt * dim_word:(cnt + 1) * dim_word, i, :] = eye
lb[t, i, :] = torch.zeros_like(word_embed)
for w in candidates[i][1:]:
if w in self.model.vocab:
x_rep[t][i].append(word_embeddings[self.model.
vocab[w]] + other_embed)
max_num_cand = max(max_num_cand, len(x_rep[t][i]))
cnt += 1
elif forward:
lb[t, i, :] = x[t, i, :]
if forward:
uw, ub = lw, lb
else:
lw = lb = uw = ub = None
zeros = torch.zeros(dim_word, device=x.device)
x_rep_, mask = [], []
for t in range(batch_size):
for i in range(length):
x_rep_ += x_rep[t][i] + [zeros] * (max_num_cand - len(x_rep
[t][i]))
mask += [1] * len(x_rep[t][i]) + [0] * (max_num_cand - len(
x_rep[t][i]))
x_rep_ = torch.cat(x_rep_).reshape(batch_size, length, max_num_cand,
dim_word)
mask = torch.tensor(mask, dtype=torch.float32, device=x.device
).reshape(batch_size, length, max_num_cand)
x_rep_ = x_rep_ * self.eps + x.unsqueeze(2) * (1 - self.eps)
inf = 1e+20
lower = torch.min(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * inf, dim=2).values
upper = torch.max(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * -inf, dim=2).values
lower = torch.min(lower, x)
upper = torch.max(upper, x)
return LinearBound(lw, lb, uw, ub, lower, upper), x, (x_rep_, mask,
can_be_replaced)
def _build_substitution(self, batch):
for t, example in enumerate(batch):
if 'candidates' not in example or example['candidates'] is None:
candidates = []
tokens = example['sentence'].strip().lower().split(' ')
for i in range(len(tokens)):
_cand = []
if tokens[i] in self.synonym:
for w in self.synonym[tokens[i]]:
if w in self.model.vocab:
_cand.append(w)
if len(_cand) > 0:
_cand = [tokens[i]] + _cand
candidates.append(_cand)
example['candidates'] = candidates
class Interval(tuple):
def __new__(self, lb=None, ub=None, ptb=None):
if ub is None:
assert isinstance(lb, tuple)
lb, ub = lb
return tuple.__new__(Interval, (lb, ub))
def __init__(self, lb, ub, ptb=None):
if ptb is None:
self.ptb = None
assert lb is ub
elif not isinstance(ptb, Perturbation):
raise ValueError(
'ptb must be a Perturbation object or None. Got type {}'.
format(type(ptb)))
else:
self.ptb = ptb
def __str__(self):
return '({}, {}) with ptb={}'.format(self[0], self[1], self.ptb)
def __repr__(self):
return 'Interval(lb={}, ub={}, ptb={})'.format(self[0], self[1],
self.ptb)
"""Checking if the other interval is tuple, keep the perturbation."""
@staticmethod
def make_interval(lb, ub, other):
if isinstance(other, Interval):
return Interval(lb, ub, other.ptb)
else:
return lb, ub
"""Given a tuple or Interval object, returns the norm and eps."""
@staticmethod
def get_perturbation(interval):
if isinstance(interval, Interval):
if isinstance(interval.ptb, PerturbationLpNorm):
return interval.ptb.norm, interval.ptb.eps
elif isinstance(interval.ptb, PerturbationSynonym):
return np.inf, 1.0
elif isinstance(interval.ptb, PerturbationL0Norm):
return 0, interval.ptb.eps, interval.ptb.ratio
elif interval.ptb is None:
raise RuntimeError(
'get_perturbation() encountered an interval that is not perturbed.'
)
else:
raise RuntimeError(
'get_perturbation() does not know how to handle {}'.
format(type(interval.ptb)))
else:
return np.inf, np.nan
"""Checking if a Interval or tuple object has perturbation enabled."""
@staticmethod
def is_perturbed(interval):
if isinstance(interval, Interval) and interval.ptb is None:
return False
else:
return True
class Bound(nn.Module):
def __init__(self, input_name, name, ori_name, attr={}, inputs=[],
output_index=0, options={}, device=None):
super().__init__()
self.output_name = []
(self.input_name, self.name, self.ori_name, self.attr, self.inputs,
self.output_index, self.options, self.device) = (input_name,
name, ori_name, attr, inputs, output_index, options, device)
self.fv = None
self.from_input = False
self.bounded = False
self.IBP_rets = None
self.perturbed = False
if options is not None and 'loss_fusion' in options:
self.loss_fusion = options['loss_fusion']
else:
self.loss_fusion = False
"""Check if the i-th input is with perturbation or not."""
def is_input_perturbed(self, i=0):
return self.inputs[i].perturbed
def forward(self, *x):
raise NotImplementedError
def interval_propagate(self, *v):
assert len(v) == 1
h_L, h_U = v[0]
return Interval.make_interval(self.forward(h_L), self.forward(h_U),
v[0])
def bound_forward(self, dim_in, last):
raise NotImplementedError
def bound_backward(self, last_lA, last_uA):
raise NotImplementedError
def infer_batch_dim(self, batch_size, *x):
None
raise NotImplementedError
def broadcast_backward(self, A, x):
shape = x.default_shape
batch_dim = max(self.batch_dim, 0)
if isinstance(A, torch.Tensor):
if x.batch_dim == -1:
shape = torch.Size([A.shape[batch_dim + 1]] + list(shape))
dims = []
cnt_sum = A.ndim - len(shape) - 1
for i in range(1, A.ndim):
if i != self.batch_dim + 1 and cnt_sum > 0:
dims.append(i)
cnt_sum -= 1
if dims:
A = torch.sum(A, dim=dims)
else:
dims = list(range(1, 1 + A.ndim - 1 - len(shape)))
if dims:
A = torch.sum(A, dim=dims)
dims = []
for i in range(len(shape)):
if shape[i] == 1 and A.shape[i + 1] != 1:
dims.append(i + 1)
if dims:
A = torch.sum(A, dim=dims, keepdim=True)
assert A.shape[1:] == shape
elif type(A) == Patches:
pass
return A
@staticmethod
def broadcast_forward(dim_in, x, shape_res):
lw, lb, uw, ub = x.lw, x.lb, x.uw, x.ub
shape_x, shape_res = list(x.lb.shape), list(shape_res)
if lw is None:
lw = uw = torch.zeros(dim_in, *shape_x, device=lb.device)
has_batch_size = False
else:
has_batch_size = True
while len(shape_x) < len(shape_res):
if not has_batch_size:
lw, uw = lw.unsqueeze(0), uw.unsqueeze(0)
lb, ub = lb.unsqueeze(0), ub.unsqueeze(0)
shape_x = [1] + shape_x
has_batch_size = True
else:
lw, uw = lw.unsqueeze(2), uw.unsqueeze(2)
lb, ub = lb.unsqueeze(1), ub.unsqueeze(1)
shape_x = [shape_x[0], 1] + shape_x[1:]
repeat = [(shape_res[i] // shape_x[i]) for i in range(len(shape_x))]
lb, ub = lb.repeat(*repeat), ub.repeat(*repeat)
repeat = repeat[:1] + [1] + repeat[1:]
lw, uw = lw.repeat(*repeat), uw.repeat(*repeat)
return lw, lb, uw, ub
def get_bias(self, A, bias):
if A is None:
return 0
assert not isnan(A)
assert not isnan(bias)
if isinstance(A, torch.Tensor):
if torch.norm(A, p=1) < epsilon:
return 0
output_dim = A.shape[0]
if self.batch_dim != -1:
batch_size = A.shape[self.batch_dim + 1]
A_shape = [A.shape[0], np.prod(A.shape[1:self.batch_dim + 1
]).astype(np.int32), batch_size, np.prod(A.shape[self.
batch_dim + 2:]).astype(np.int32)]
A = A.reshape(*A_shape).permute(2, 0, 1, 3).reshape(batch_size,
output_dim, -1)
bias = bias.reshape(*A_shape[1:]).transpose(0, 1).reshape(
batch_size, -1, 1)
bias_new = A.matmul(bias).squeeze(-1).transpose(0, 1)
else:
batch_size = A.shape[1]
A = A.view(output_dim, batch_size, -1)
bias_new = A.matmul(bias.view(-1))
if isnan(bias_new):
return 0
else:
return bias_new
elif type(A) == Patches:
if torch.norm(A.patches, p=1) < epsilon:
return 0
if self.batch_dim != -1:
batch_size = bias.shape[0]
bias = F.unfold(bias, kernel_size=A.patches.size(-1),
stride=A.stride, padding=A.padding).transpose(-2, -1
).unsqueeze(-2)
bias.size(1)
patches = A.patches.view(A.patches.size(0), A.patches.size(
1), A.patches.size(-4), A.patches.size(-1) * A.patches.
size(-2) * A.patches.size(-3))
prod = bias * patches
bias_new = prod.sum(-1).transpose(-2, -1)
bias_new = bias_new.view(batch_size, bias_new.size(-2), int
(math.sqrt(bias_new.size(-1))), int(math.sqrt(bias_new.
size(-1))))
else:
patches = A.patches
patches_reshape = torch.sum(patches, dim=(-1, -2, -3)) * bias
patches_reshape = patches_reshape.transpose(-1, -2)
return patches_reshape.view(patches_reshape.size(0),
patches_reshape.size(1), int(math.sqrt(patches_reshape.
size(2))), -1).transpose(0, 1)
return bias_new
else:
return NotImplementedError()
class BoundActivation(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs,
output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs,
output_index, options, device)
self.nonlinear = True
self.relaxed = False
def _init_linear(self, x):
self.mask_pos = torch.gt(x.lower, 0)
self.mask_neg = torch.lt(x.upper, 0)
self.mask_both = 1 - self.mask_pos - self.mask_neg
self.lw = torch.zeros(x.lower.shape, device=self.device)
self.lb = self.lw.clone()
self.uw = self.lw.clone()
self.ub = self.lw.clone()
def _add_linear(self, mask, type, k, x0, y0):
if mask is None:
mask = 1
if type == 'lower':
w_out, b_out = self.lw, self.lb
else:
w_out, b_out = self.uw, self.ub
w_out += mask * k
b_out += mask * (-x0 * k + y0)
def bound_relax(self, x):
raise NotImplementedError
def bound_backward(self, last_lA, last_uA, x):
if not self.relaxed:
self._init_linear(x)
self.bound_relax(x)
def _bound_oneside(last_A, sign=-1):
if last_A is None:
return None, 0
if self.batch_dim == 0:
if sign == -1:
_A = last_A.clamp(min=0) * self.lw.unsqueeze(0
) + last_A.clamp(max=0) * self.uw.unsqueeze(0)
_bias = last_A.clamp(min=0) * self.lb.unsqueeze(0
) + last_A.clamp(max=0) * self.ub.unsqueeze(0)
elif sign == 1:
_A = last_A.clamp(min=0) * self.uw.unsqueeze(0
) + last_A.clamp(max=0) * self.lw.unsqueeze(0)
_bias = last_A.clamp(min=0) * self.ub.unsqueeze(0
) + last_A.clamp(max=0) * self.lb.unsqueeze(0)
while _bias.ndim > 2:
_bias = torch.sum(_bias, dim=-1)
elif self.batch_dim == -1:
mask = torch.gt(last_A, 0.0)
if sign == -1:
_A = last_A * (mask * self.lw.unsqueeze(0).unsqueeze(1) +
(1 - mask) * self.uw.unsqueeze(0).unsqueeze(1))
_bias = last_A * (mask * self.lb.unsqueeze(0).unsqueeze
(1) + (1 - mask) * self.ub.unsqueeze(0).unsqueeze(1))
elif sign == 1:
_A = last_A * (mask * self.uw.unsqueeze(0).unsqueeze(1) +
(1 - mask) * self.lw.unsqueeze(0).unsqueeze(1))
_bias = last_A * (mask * self.ub.unsqueeze(0).unsqueeze
(1) + (1 - mask) * self.lb.unsqueeze(0).unsqueeze(1))
while _bias.ndim > 2:
_bias = torch.sum(_bias, dim=-1)
else:
raise NotImplementedError
return _A, _bias
lA, lbias = _bound_oneside(last_lA, sign=-1)
uA, ubias = _bound_oneside(last_uA, sign=+1)
return [(lA, uA)], lbias, ubias
def bound_forward(self, dim_in, x):
if not self.relaxed:
self._init_linear(x)
self.bound_relax(x)
if self.lw.ndim > 0:
if x.lw is not None:
lw = self.lw.unsqueeze(1).clamp(min=0
) * x.lw + self.lw.unsqueeze(1).clamp(max=0) * x.uw
uw = self.uw.unsqueeze(1).clamp(max=0
) * x.lw + self.uw.unsqueeze(1).clamp(min=0) * x.uw
else:
lw = uw = None
elif x.lw is not None:
lw = self.lw.unsqueeze(0).clamp(min=0) * x.lw + self.lw.unsqueeze(0
).clamp(max=0) * x.uw
uw = self.uw.unsqueeze(0).clamp(min=0) * x.lw + self.uw.unsqueeze(0
).clamp(max=0) * x.uw
else:
lw = uw = None
lb = self.lw.clamp(min=0) * x.lb + self.lw.clamp(max=0
) * x.ub + self.lb
ub = self.uw.clamp(max=0) * x.lb + self.uw.clamp(min=0
) * x.ub + self.ub
return LinearBound(lw, lb, uw, ub)
def infer_batch_dim(self, batch_size, *x):
return x[0]
class BoundReciprocal(BoundActivation):
def __init__(self, input_name, name, ori_name, attr, inputs,
output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs,
output_index, options, device)
self.nonlinear = True
def forward(self, x):
return torch.reciprocal(x)
def bound_relax(self, x):
m = (x.lower + x.upper) / 2
kl = -1 / m.pow(2)
self._add_linear(mask=None, type='lower', k=kl, x0=m, y0=1.0 / m)
ku = -1.0 / (x.lower * x.upper)
self._add_linear(mask=None, type='upper', k=ku, x0=x.lower, y0=1.0 /
x.lower)
def interval_propagate(self, *v):
h_L, h_U = v[0]
return torch.reciprocal(h_U.float()), torch.reciprocal(h_L.float())
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_name': 4, 'name': 4, 'ori_name': 4, 'attr': 4,
'inputs': 4, 'output_index': 4, 'options': _mock_config(loss_fusion
=MSELoss()), '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 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
@triton.jit
def triton_poi_fused_reciprocal_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], 1, tl.int32)
tmp2 = tmp1 / tmp0
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_reciprocal_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def isnan(x):
if isinstance(x, Patches):
return False
return torch.isnan(x).any()
class Perturbation:
def __init__(self):
pass
def set_eps(self, eps):
self.eps = eps
def concretize(self, x, A, sign=-1, aux=None):
raise NotImplementedError
def init(self, x, aux=None, forward=False):
raise NotImplementedError
class PerturbationL0Norm(Perturbation):
def __init__(self, eps, x_L=None, x_U=None, ratio=1.0):
self.eps = eps
self.x_U = x_U
self.x_L = x_L
self.ratio = ratio
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
eps = math.ceil(self.eps)
x = x.reshape(x.shape[0], -1, 1)
center = A.matmul(x)
x = x.reshape(x.shape[0], 1, -1)
original = A * x.expand(x.shape[0], A.shape[-2], x.shape[2])
neg_mask = A < 0
pos_mask = A >= 0
if sign == 1:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = A[pos_mask] - original[pos_mask]
A_diff[neg_mask] = -original[neg_mask]
else:
A_diff = torch.zeros_like(A)
A_diff[pos_mask] = original[pos_mask]
A_diff[neg_mask] = original[neg_mask] - A[neg_mask]
A_diff, _ = torch.sort(A_diff, dim=2, descending=True)
bound = center + sign * A_diff[:, :, :eps].sum(dim=2).unsqueeze(2
) * self.ratio
return bound.squeeze(2)
def init(self, x, aux=None, forward=False):
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
return 'PerturbationLpNorm(norm=0, eps={})'.format(self.eps)
class PerturbationLpNorm(Perturbation):
def __init__(self, eps, norm=np.inf, x_L=None, x_U=None):
self.eps = eps
self.norm = norm
self.dual_norm = 1 if norm == np.inf else np.float64(1.0) / (1 -
1.0 / self.norm)
self.x_L = x_L
self.x_U = x_U
"""Given an variable x and its bound matrix A, compute worst case bound according to Lp norm."""
def concretize(self, x, A, sign=-1, aux=None):
if A is None:
return None
def concretize_matrix(A):
nonlocal x
if not isinstance(A, eyeC):
A = A.reshape(A.shape[0], A.shape[1], -1)
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
x_ub = x_U.reshape(x_U.shape[0], -1, 1)
x_lb = x_L.reshape(x_L.shape[0], -1, 1)
center = (x_ub + x_lb) / 2.0
diff = (x_ub - x_lb) / 2.0
if not isinstance(A, eyeC):
bound = A.matmul(center) + sign * A.abs().matmul(diff)
else:
bound = center + sign * diff
else:
x = x.reshape(x.shape[0], -1, 1)
if not isinstance(A, eyeC):
deviation = A.norm(self.dual_norm, -1) * self.eps
bound = A.matmul(x) + sign * deviation.unsqueeze(-1)
else:
bound = x + sign * self.eps
bound = bound.squeeze(-1)
return bound
def concretize_patches(A):
nonlocal x
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
center = (x_U + x_L) / 2.0
diff = (x_U - x_L) / 2.0
if not A.identity == 1:
unfold_input = F.unfold(center, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound = prod.view(prod.size(0), prod.size(1), int(math.
sqrt(prod.size(2))), int(math.sqrt(prod.size(2))))
unfold_input = F.unfold(diff, kernel_size=A.patches.
size(-1), padding=A.padding, stride=A.stride
).transpose(-2, -1)
unfold_input = unfold_input.view(unfold_input.size(0),
unfold_input.size(1), -1, A.patches.size(-3), A.
patches.size(-2), A.patches.size(-1))
prod = unfold_input * A.patches.abs()
prod = prod.sum((-1, -2, -3)).transpose(-2, -1)
bound += sign * prod.view(prod.size(0), prod.size(1),
int(math.sqrt(prod.size(2))), int(math.sqrt(prod.
size(2))))
else:
bound = center + sign * diff
return bound
else:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
raise NotImplementedError()
if isinstance(A, eyeC) or isinstance(A, torch.Tensor):
return concretize_matrix(A)
elif isinstance(A, Patches):
return concretize_patches(A)
elif isinstance(A, BoundList):
for b in A.bound_list:
if isinstance(b, eyeC) or isinstance(b, torch.Tensor):
pass
else:
raise NotImplementedError()
def init(self, x, aux=None, forward=False):
if self.norm == np.inf:
x_L = x - self.eps if self.x_L is None else self.x_L
x_U = x + self.eps if self.x_U is None else self.x_U
else:
x_L = x
x_U = x
if not forward:
return LinearBound(None, None, None, None, x_L, x_U), x, None
batch_size = x.shape[0]
dim = x.reshape(batch_size, -1).shape[-1]
eye = torch.eye(dim).unsqueeze(0).repeat(batch_size, 1, 1)
lw = eye.reshape(batch_size, dim, *x.shape[1:])
lb = torch.zeros_like(x)
uw, ub = lw.clone(), lb.clone()
return LinearBound(lw, lb, uw, ub, x_L, x_U), x, None
def __repr__(self):
if self.norm == np.inf:
if self.x_L is None and self.x_U is None:
return 'PerturbationLpNorm(norm=inf, eps={})'.format(self.eps)
else:
return ('PerturbationLpNorm(norm=inf, eps={}, x_L={}, x_U={})'
.format(self.eps, self.x_L, self.x_U))
else:
return 'PerturbationLpNorm(norm={}, eps={})'.format(self.norm,
self.eps)
class PerturbationSynonym(Perturbation):
def __init__(self, budget, eps=1.0, use_simple=False):
super(PerturbationSynonym, self).__init__()
self._load_synonyms()
self.budget = budget
self.eps = eps
self.use_simple = use_simple
self.model = None
self.train = False
def __repr__(self):
return (
'perturbation(Synonym-based word substitution budget={}, eps={})'
.format(self.budget, self.eps))
def _load_synonyms(self, path='data/synonyms.json'):
with open(path) as file:
self.synonym = json.loads(file.read())
logger.info('Synonym list loaded for {} words'.format(len(self.
synonym)))
def set_train(self, train):
self.train = train
def concretize(self, x, A, sign, aux):
assert self.model is not None
x_rep, mask, can_be_replaced = aux
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
dim_out = A.shape[1]
max_num_cand = x_rep.shape[2]
mask_rep = torch.tensor(can_be_replaced, dtype=torch.float32,
device=A.device)
num_pos = int(np.max(np.sum(can_be_replaced, axis=-1)))
update_A = A.shape[-1] > num_pos * dim_word
if update_A:
bias = torch.bmm(A, (x * (1 - mask_rep).unsqueeze(-1)).reshape(
batch_size, -1, 1)).squeeze(-1)
else:
bias = 0.0
A = A.reshape(batch_size, dim_out, -1, dim_word)
A_new, x_new, x_rep_new, mask_new = [], [], [], []
zeros_A = torch.zeros(dim_out, dim_word, device=A.device)
zeros_w = torch.zeros(dim_word, device=A.device)
zeros_rep = torch.zeros(max_num_cand, dim_word, device=A.device)
zeros_mask = torch.zeros(max_num_cand, device=A.device)
for t in range(batch_size):
cnt = 0
for i in range(0, length):
if can_be_replaced[t][i]:
if update_A:
A_new.append(A[t, :, i, :])
x_new.append(x[t][i])
x_rep_new.append(x_rep[t][i])
mask_new.append(mask[t][i])
cnt += 1
if update_A:
A_new += [zeros_A] * (num_pos - cnt)
x_new += [zeros_w] * (num_pos - cnt)
x_rep_new += [zeros_rep] * (num_pos - cnt)
mask_new += [zeros_mask] * (num_pos - cnt)
if update_A:
A = torch.cat(A_new).reshape(batch_size, num_pos, dim_out, dim_word
).transpose(1, 2)
x = torch.cat(x_new).reshape(batch_size, num_pos, dim_word)
x_rep = torch.cat(x_rep_new).reshape(batch_size, num_pos,
max_num_cand, dim_word)
mask = torch.cat(mask_new).reshape(batch_size, num_pos, max_num_cand)
length = num_pos
A = A.reshape(batch_size, A.shape[1], length, -1).transpose(1, 2)
x = x.reshape(batch_size, length, -1, 1)
if sign == 1:
cmp, init = torch.max, -1e+30
else:
cmp, init = torch.min, 1e+30
init_tensor = torch.ones(batch_size, dim_out) * init
dp = [([init_tensor] * (self.budget + 1)) for i in range(0, length + 1)
]
dp[0][0] = torch.zeros(batch_size, dim_out)
A = A.reshape(batch_size * length, A.shape[2], A.shape[3])
Ax = torch.bmm(A, x.reshape(batch_size * length, x.shape[2], x.
shape[3])).reshape(batch_size, length, A.shape[1])
Ax_rep = torch.bmm(A, x_rep.reshape(batch_size * length,
max_num_cand, x.shape[2]).transpose(-1, -2)).reshape(batch_size,
length, A.shape[1], max_num_cand)
Ax_rep = Ax_rep * mask.unsqueeze(2) + init * (1 - mask).unsqueeze(2)
Ax_rep_bound = cmp(Ax_rep, dim=-1).values
if self.use_simple and self.train:
return torch.sum(cmp(Ax, Ax_rep_bound), dim=1) + bias
for i in range(1, length + 1):
dp[i][0] = dp[i - 1][0] + Ax[:, i - 1]
for j in range(1, self.budget + 1):
dp[i][j] = cmp(dp[i - 1][j] + Ax[:, i - 1], dp[i - 1][j - 1
] + Ax_rep_bound[:, i - 1])
dp = torch.cat(dp[length], dim=0).reshape(self.budget + 1,
batch_size, dim_out)
return cmp(dp, dim=0).values + bias
def init(self, x, aux=None, forward=False):
tokens, batch = aux
self.tokens = tokens
assert len(x.shape) == 3
batch_size, length, dim_word = x.shape[0], x.shape[1], x.shape[2]
max_pos = 1
can_be_replaced = np.zeros((batch_size, length), dtype=np.bool)
self._build_substitution(batch)
for t in range(batch_size):
cnt = 0
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
for i in range(len(tokens[t])):
if tokens[t][i] == '[UNK]' or len(candidates[i]
) == 0 or tokens[t][i] != candidates[i][0]:
continue
for w in candidates[i][1:]:
if w in self.model.vocab:
can_be_replaced[t][i] = True
cnt += 1
break
max_pos = max(max_pos, cnt)
dim = max_pos * dim_word
if forward:
eye = torch.eye(dim_word)
lw = torch.zeros(batch_size, dim, length, dim_word)
lb = torch.zeros_like(x)
word_embeddings = self.model.word_embeddings.weight
vocab = self.model.vocab
x_rep = [[[] for i in range(length)] for t in range(batch_size)]
max_num_cand = 1
for t in range(batch_size):
candidates = batch[t]['candidates']
if tokens[t][0] == '[CLS]':
candidates = [[]] + candidates + [[]]
cnt = 0
for i in range(length):
if can_be_replaced[t][i]:
word_embed = word_embeddings[vocab[tokens[t][i]]]
other_embed = x[t, i] - word_embed
if forward:
lw[t, cnt * dim_word:(cnt + 1) * dim_word, i, :] = eye
lb[t, i, :] = torch.zeros_like(word_embed)
for w in candidates[i][1:]:
if w in self.model.vocab:
x_rep[t][i].append(word_embeddings[self.model.
vocab[w]] + other_embed)
max_num_cand = max(max_num_cand, len(x_rep[t][i]))
cnt += 1
elif forward:
lb[t, i, :] = x[t, i, :]
if forward:
uw, ub = lw, lb
else:
lw = lb = uw = ub = None
zeros = torch.zeros(dim_word, device=x.device)
x_rep_, mask = [], []
for t in range(batch_size):
for i in range(length):
x_rep_ += x_rep[t][i] + [zeros] * (max_num_cand - len(x_rep
[t][i]))
mask += [1] * len(x_rep[t][i]) + [0] * (max_num_cand - len(
x_rep[t][i]))
x_rep_ = torch.cat(x_rep_).reshape(batch_size, length, max_num_cand,
dim_word)
mask = torch.tensor(mask, dtype=torch.float32, device=x.device
).reshape(batch_size, length, max_num_cand)
x_rep_ = x_rep_ * self.eps + x.unsqueeze(2) * (1 - self.eps)
inf = 1e+20
lower = torch.min(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * inf, dim=2).values
upper = torch.max(mask.unsqueeze(-1) * x_rep_ + (1 - mask).
unsqueeze(-1) * -inf, dim=2).values
lower = torch.min(lower, x)
upper = torch.max(upper, x)
return LinearBound(lw, lb, uw, ub, lower, upper), x, (x_rep_, mask,
can_be_replaced)
def _build_substitution(self, batch):
for t, example in enumerate(batch):
if 'candidates' not in example or example['candidates'] is None:
candidates = []
tokens = example['sentence'].strip().lower().split(' ')
for i in range(len(tokens)):
_cand = []
if tokens[i] in self.synonym:
for w in self.synonym[tokens[i]]:
if w in self.model.vocab:
_cand.append(w)
if len(_cand) > 0:
_cand = [tokens[i]] + _cand
candidates.append(_cand)
example['candidates'] = candidates
class Interval(tuple):
def __new__(self, lb=None, ub=None, ptb=None):
if ub is None:
assert isinstance(lb, tuple)
lb, ub = lb
return tuple.__new__(Interval, (lb, ub))
def __init__(self, lb, ub, ptb=None):
if ptb is None:
self.ptb = None
assert lb is ub
elif not isinstance(ptb, Perturbation):
raise ValueError(
'ptb must be a Perturbation object or None. Got type {}'.
format(type(ptb)))
else:
self.ptb = ptb
def __str__(self):
return '({}, {}) with ptb={}'.format(self[0], self[1], self.ptb)
def __repr__(self):
return 'Interval(lb={}, ub={}, ptb={})'.format(self[0], self[1],
self.ptb)
"""Checking if the other interval is tuple, keep the perturbation."""
@staticmethod
def make_interval(lb, ub, other):
if isinstance(other, Interval):
return Interval(lb, ub, other.ptb)
else:
return lb, ub
"""Given a tuple or Interval object, returns the norm and eps."""
@staticmethod
def get_perturbation(interval):
if isinstance(interval, Interval):
if isinstance(interval.ptb, PerturbationLpNorm):
return interval.ptb.norm, interval.ptb.eps
elif isinstance(interval.ptb, PerturbationSynonym):
return np.inf, 1.0
elif isinstance(interval.ptb, PerturbationL0Norm):
return 0, interval.ptb.eps, interval.ptb.ratio
elif interval.ptb is None:
raise RuntimeError(
'get_perturbation() encountered an interval that is not perturbed.'
)
else:
raise RuntimeError(
'get_perturbation() does not know how to handle {}'.
format(type(interval.ptb)))
else:
return np.inf, np.nan
"""Checking if a Interval or tuple object has perturbation enabled."""
@staticmethod
def is_perturbed(interval):
if isinstance(interval, Interval) and interval.ptb is None:
return False
else:
return True
class Bound(nn.Module):
def __init__(self, input_name, name, ori_name, attr={}, inputs=[],
output_index=0, options={}, device=None):
super().__init__()
self.output_name = []
(self.input_name, self.name, self.ori_name, self.attr, self.inputs,
self.output_index, self.options, self.device) = (input_name,
name, ori_name, attr, inputs, output_index, options, device)
self.fv = None
self.from_input = False
self.bounded = False
self.IBP_rets = None
self.perturbed = False
if options is not None and 'loss_fusion' in options:
self.loss_fusion = options['loss_fusion']
else:
self.loss_fusion = False
"""Check if the i-th input is with perturbation or not."""
def is_input_perturbed(self, i=0):
return self.inputs[i].perturbed
def forward(self, *x):
raise NotImplementedError
def interval_propagate(self, *v):
assert len(v) == 1
h_L, h_U = v[0]
return Interval.make_interval(self.forward(h_L), self.forward(h_U),
v[0])
def bound_forward(self, dim_in, last):
raise NotImplementedError
def bound_backward(self, last_lA, last_uA):
raise NotImplementedError
def infer_batch_dim(self, batch_size, *x):
None
raise NotImplementedError
def broadcast_backward(self, A, x):
shape = x.default_shape
batch_dim = max(self.batch_dim, 0)
if isinstance(A, torch.Tensor):
if x.batch_dim == -1:
shape = torch.Size([A.shape[batch_dim + 1]] + list(shape))
dims = []
cnt_sum = A.ndim - len(shape) - 1
for i in range(1, A.ndim):
if i != self.batch_dim + 1 and cnt_sum > 0:
dims.append(i)
cnt_sum -= 1
if dims:
A = torch.sum(A, dim=dims)
else:
dims = list(range(1, 1 + A.ndim - 1 - len(shape)))
if dims:
A = torch.sum(A, dim=dims)
dims = []
for i in range(len(shape)):
if shape[i] == 1 and A.shape[i + 1] != 1:
dims.append(i + 1)
if dims:
A = torch.sum(A, dim=dims, keepdim=True)
assert A.shape[1:] == shape
elif type(A) == Patches:
pass
return A
@staticmethod
def broadcast_forward(dim_in, x, shape_res):
lw, lb, uw, ub = x.lw, x.lb, x.uw, x.ub
shape_x, shape_res = list(x.lb.shape), list(shape_res)
if lw is None:
lw = uw = torch.zeros(dim_in, *shape_x, device=lb.device)
has_batch_size = False
else:
has_batch_size = True
while len(shape_x) < len(shape_res):
if not has_batch_size:
lw, uw = lw.unsqueeze(0), uw.unsqueeze(0)
lb, ub = lb.unsqueeze(0), ub.unsqueeze(0)
shape_x = [1] + shape_x
has_batch_size = True
else:
lw, uw = lw.unsqueeze(2), uw.unsqueeze(2)
lb, ub = lb.unsqueeze(1), ub.unsqueeze(1)
shape_x = [shape_x[0], 1] + shape_x[1:]
repeat = [(shape_res[i] // shape_x[i]) for i in range(len(shape_x))]
lb, ub = lb.repeat(*repeat), ub.repeat(*repeat)
repeat = repeat[:1] + [1] + repeat[1:]
lw, uw = lw.repeat(*repeat), uw.repeat(*repeat)
return lw, lb, uw, ub
def get_bias(self, A, bias):
if A is None:
return 0
assert not isnan(A)
assert not isnan(bias)
if isinstance(A, torch.Tensor):
if torch.norm(A, p=1) < epsilon:
return 0
output_dim = A.shape[0]
if self.batch_dim != -1:
batch_size = A.shape[self.batch_dim + 1]
A_shape = [A.shape[0], np.prod(A.shape[1:self.batch_dim + 1
]).astype(np.int32), batch_size, np.prod(A.shape[self.
batch_dim + 2:]).astype(np.int32)]
A = A.reshape(*A_shape).permute(2, 0, 1, 3).reshape(batch_size,
output_dim, -1)
bias = bias.reshape(*A_shape[1:]).transpose(0, 1).reshape(
batch_size, -1, 1)
bias_new = A.matmul(bias).squeeze(-1).transpose(0, 1)
else:
batch_size = A.shape[1]
A = A.view(output_dim, batch_size, -1)
bias_new = A.matmul(bias.view(-1))
if isnan(bias_new):
return 0
else:
return bias_new
elif type(A) == Patches:
if torch.norm(A.patches, p=1) < epsilon:
return 0
if self.batch_dim != -1:
batch_size = bias.shape[0]
bias = F.unfold(bias, kernel_size=A.patches.size(-1),
stride=A.stride, padding=A.padding).transpose(-2, -1
).unsqueeze(-2)
bias.size(1)
patches = A.patches.view(A.patches.size(0), A.patches.size(
1), A.patches.size(-4), A.patches.size(-1) * A.patches.
size(-2) * A.patches.size(-3))
prod = bias * patches
bias_new = prod.sum(-1).transpose(-2, -1)
bias_new = bias_new.view(batch_size, bias_new.size(-2), int
(math.sqrt(bias_new.size(-1))), int(math.sqrt(bias_new.
size(-1))))
else:
patches = A.patches
patches_reshape = torch.sum(patches, dim=(-1, -2, -3)) * bias
patches_reshape = patches_reshape.transpose(-1, -2)
return patches_reshape.view(patches_reshape.size(0),
patches_reshape.size(1), int(math.sqrt(patches_reshape.
size(2))), -1).transpose(0, 1)
return bias_new
else:
return NotImplementedError()
class BoundActivation(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs,
output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs,
output_index, options, device)
self.nonlinear = True
self.relaxed = False
def _init_linear(self, x):
self.mask_pos = torch.gt(x.lower, 0)
self.mask_neg = torch.lt(x.upper, 0)
self.mask_both = 1 - self.mask_pos - self.mask_neg
self.lw = torch.zeros(x.lower.shape, device=self.device)
self.lb = self.lw.clone()
self.uw = self.lw.clone()
self.ub = self.lw.clone()
def _add_linear(self, mask, type, k, x0, y0):
if mask is None:
mask = 1
if type == 'lower':
w_out, b_out = self.lw, self.lb
else:
w_out, b_out = self.uw, self.ub
w_out += mask * k
b_out += mask * (-x0 * k + y0)
def bound_relax(self, x):
raise NotImplementedError
def bound_backward(self, last_lA, last_uA, x):
if not self.relaxed:
self._init_linear(x)
self.bound_relax(x)
def _bound_oneside(last_A, sign=-1):
if last_A is None:
return None, 0
if self.batch_dim == 0:
if sign == -1:
_A = last_A.clamp(min=0) * self.lw.unsqueeze(0
) + last_A.clamp(max=0) * self.uw.unsqueeze(0)
_bias = last_A.clamp(min=0) * self.lb.unsqueeze(0
) + last_A.clamp(max=0) * self.ub.unsqueeze(0)
elif sign == 1:
_A = last_A.clamp(min=0) * self.uw.unsqueeze(0
) + last_A.clamp(max=0) * self.lw.unsqueeze(0)
_bias = last_A.clamp(min=0) * self.ub.unsqueeze(0
) + last_A.clamp(max=0) * self.lb.unsqueeze(0)
while _bias.ndim > 2:
_bias = torch.sum(_bias, dim=-1)
elif self.batch_dim == -1:
mask = torch.gt(last_A, 0.0)
if sign == -1:
_A = last_A * (mask * self.lw.unsqueeze(0).unsqueeze(1) +
(1 - mask) * self.uw.unsqueeze(0).unsqueeze(1))
_bias = last_A * (mask * self.lb.unsqueeze(0).unsqueeze
(1) + (1 - mask) * self.ub.unsqueeze(0).unsqueeze(1))
elif sign == 1:
_A = last_A * (mask * self.uw.unsqueeze(0).unsqueeze(1) +
(1 - mask) * self.lw.unsqueeze(0).unsqueeze(1))
_bias = last_A * (mask * self.ub.unsqueeze(0).unsqueeze
(1) + (1 - mask) * self.lb.unsqueeze(0).unsqueeze(1))
while _bias.ndim > 2:
_bias = torch.sum(_bias, dim=-1)
else:
raise NotImplementedError
return _A, _bias
lA, lbias = _bound_oneside(last_lA, sign=-1)
uA, ubias = _bound_oneside(last_uA, sign=+1)
return [(lA, uA)], lbias, ubias
def bound_forward(self, dim_in, x):
if not self.relaxed:
self._init_linear(x)
self.bound_relax(x)
if self.lw.ndim > 0:
if x.lw is not None:
lw = self.lw.unsqueeze(1).clamp(min=0
) * x.lw + self.lw.unsqueeze(1).clamp(max=0) * x.uw
uw = self.uw.unsqueeze(1).clamp(max=0
) * x.lw + self.uw.unsqueeze(1).clamp(min=0) * x.uw
else:
lw = uw = None
elif x.lw is not None:
lw = self.lw.unsqueeze(0).clamp(min=0) * x.lw + self.lw.unsqueeze(0
).clamp(max=0) * x.uw
uw = self.uw.unsqueeze(0).clamp(min=0) * x.lw + self.uw.unsqueeze(0
).clamp(max=0) * x.uw
else:
lw = uw = None
lb = self.lw.clamp(min=0) * x.lb + self.lw.clamp(max=0
) * x.ub + self.lb
ub = self.uw.clamp(max=0) * x.lb + self.uw.clamp(min=0
) * x.ub + self.ub
return LinearBound(lw, lb, uw, ub)
def infer_batch_dim(self, batch_size, *x):
return x[0]
class BoundReciprocalNew(BoundActivation):
def __init__(self, input_name, name, ori_name, attr, inputs,
output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs,
output_index, options, device)
self.nonlinear = True
def bound_relax(self, x):
m = (x.lower + x.upper) / 2
kl = -1 / m.pow(2)
self._add_linear(mask=None, type='lower', k=kl, x0=m, y0=1.0 / m)
ku = -1.0 / (x.lower * x.upper)
self._add_linear(mask=None, type='upper', k=ku, x0=x.lower, y0=1.0 /
x.lower)
def interval_propagate(self, *v):
h_L, h_U = v[0]
return torch.reciprocal(h_U.float()), torch.reciprocal(h_L.float())
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
mnmueller/auto_LiRPA
|
BoundReciprocal
| false
| 7,287
|
[
"BSD-3-Clause"
] | 1
|
55cb270b0b99f07b74541d55706c69fbb9daff66
|
https://github.com/mnmueller/auto_LiRPA/tree/55cb270b0b99f07b74541d55706c69fbb9daff66
|
WeightL1Loss
|
import torch
import torch.nn as nn
class WeightL1Loss(nn.Module):
def __init__(self):
super(WeightL1Loss, self).__init__()
def forward(self, pred_loc, label_loc, loss_weight):
b, _, sh, sw = pred_loc.size()
pred_loc = pred_loc.view(b, 4, -1, sh, sw)
diff = (pred_loc - label_loc).abs()
diff = diff.sum(dim=1).view(b, -1, sh, sw)
loss = diff * loss_weight
return loss.sum().div(b)
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_abs_div_mul_sub_sum_view_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 % 16
r2 = rindex // 64
r4 = rindex % 64
r3 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp1 = tl.load(in_ptr1 + r4, None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr1 + (64 + r4), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr1 + (128 + r4), None, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr1 + (192 + r4), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr2 + r3, None)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp6 = tmp4 - tmp5
tmp7 = tl_math.abs(tmp6)
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tl_math.abs(tmp11)
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tl_math.abs(tmp16)
tmp18 = tmp13 + tmp17
tmp20 = tmp18 * tmp19
tmp21 = tl.broadcast_to(tmp20, [RBLOCK])
tmp23 = triton_helpers.promote_to_tensor(tl.sum(tmp21, 0))
tmp24 = 0.25
tmp25 = tmp23 * tmp24
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp25, 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)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_abs_div_mul_sub_sum_view_0[grid(1)](buf2, arg0_1,
arg1_1, arg2_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf2,
class WeightL1LossNew(nn.Module):
def __init__(self):
super(WeightL1LossNew, self).__init__()
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
mshmoon/siamrpn-lightweight
|
WeightL1Loss
| false
| 7,288
|
[
"MIT"
] | 1
|
f6527e34c9eaaeb45817b12babd78ee73b1c7525
|
https://github.com/mshmoon/siamrpn-lightweight/tree/f6527e34c9eaaeb45817b12babd78ee73b1c7525
|
Corr
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Corr(nn.Module):
def __init__(self):
super(Corr, self).__init__()
def forward(self, x, kernel):
batch = kernel.size(0)
channel = kernel.size(1)
x = x.view(1, batch * channel, x.size(2), x.size(3))
kernel = kernel.view(batch * channel, 1, kernel.size(2), kernel.size(3)
)
out = F.conv2d(x, kernel, groups=batch * channel)
out = out.view(batch, channel, out.size(2), out.size(3))
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 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 + (x1 + 16 * y0), xmask & ymask)
tl.store(out_ptr0 + (y0 + 16 * x1), tmp0, xmask & ymask)
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((1, 16, 4, 4), (256, 1, 64, 16), torch.
float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 16)](arg1_1, buf0, 16, 16,
XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del arg1_1
buf1 = extern_kernels.convolution(buf0, reinterpret_tensor(arg0_1,
(16, 1, 4, 4), (16, 16, 4, 1), 0), stride=(1, 1), padding=(0, 0
), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=16, bias=None)
assert_size_stride(buf1, (1, 16, 1, 1), (16, 1, 16, 16))
del arg0_1
del buf0
return reinterpret_tensor(buf1, (4, 4, 1, 1), (4, 1, 1, 1), 0),
class CorrNew(nn.Module):
def __init__(self):
super(CorrNew, 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]
|
mshmoon/siamrpn-lightweight
|
Corr
| false
| 7,289
|
[
"MIT"
] | 1
|
f6527e34c9eaaeb45817b12babd78ee73b1c7525
|
https://github.com/mshmoon/siamrpn-lightweight/tree/f6527e34c9eaaeb45817b12babd78ee73b1c7525
|
BernoulliLogProb
|
import torch
import torch.nn as nn
import torch.utils
import torch.utils.data
class BernoulliLogProb(nn.Module):
def __init__(self):
super().__init__()
self.bce_with_logits = nn.BCEWithLogitsLoss(reduction='none')
def forward(self, logits, target):
return -self.bce_with_logits(logits, target)
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.utils
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_binary_cross_entropy_with_logits_neg_0(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp2 * tmp3
tmp5 = 0.0
tmp6 = triton_helpers.minimum(tmp5, tmp3)
tmp7 = tl_math.abs(tmp3)
tmp8 = -tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = libdevice.log1p(tmp9)
tmp11 = tmp6 - tmp10
tmp12 = tmp4 - tmp11
tmp13 = -tmp12
tl.store(out_ptr0 + x0, tmp13, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_binary_cross_entropy_with_logits_neg_0[grid(256)](
arg0_1, arg1_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class BernoulliLogProbNew(nn.Module):
def __init__(self):
super().__init__()
self.bce_with_logits = 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]
|
msunardi/vae_experiment
|
BernoulliLogProb
| false
| 7,290
|
[
"MIT"
] | 1
|
e3ce39e586f1189d157e753370a90c07713658b3
|
https://github.com/msunardi/vae_experiment/tree/e3ce39e586f1189d157e753370a90c07713658b3
|
LogSoftMax
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class LogSoftMax(nn.Module):
def __init__(self):
super(LogSoftMax, self).__init__()
def forward(self, cls):
b, a2, h, w = cls.size()
cls = cls.view(b, 2, a2 // 2, h, w)
cls = cls.permute(0, 2, 3, 4, 1).contiguous()
cls = F.log_softmax(cls, dim=4)
return cls
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_clone_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 128
xnumel = 2
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 32
y1 = yindex // 32
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 32 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (y0 + 64 * y1), ymask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (32 + y0 + 64 * y1), ymask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp4 = tmp0 - tmp3
tmp5 = tmp1 - tmp3
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp2 - tmp3
tmp8 = tl_math.exp(tmp7)
tmp9 = tmp6 + tmp8
tmp10 = tl_math.log(tmp9)
tmp11 = tmp4 - tmp10
tl.store(out_ptr0 + (x2 + 2 * y3), tmp11, xmask & ymask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 4, 4, 2), (64, 32, 8, 2, 1), torch
.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_clone_0[grid(128, 2)](arg0_1, buf0,
128, 2, XBLOCK=2, YBLOCK=64, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class LogSoftMaxNew(nn.Module):
def __init__(self):
super(LogSoftMaxNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
mshmoon/siamrpn-lightweight
|
LogSoftMax
| false
| 7,291
|
[
"MIT"
] | 1
|
f6527e34c9eaaeb45817b12babd78ee73b1c7525
|
https://github.com/mshmoon/siamrpn-lightweight/tree/f6527e34c9eaaeb45817b12babd78ee73b1c7525
|
DistillLoss
|
import torch
from torch import nn
import torch.nn.functional as F
class DistillLoss(nn.Module):
def __init__(self, temperature, distillation_weight):
super().__init__()
self.temperature = temperature
self.distillation_weight = distillation_weight
self.kldiv = nn.KLDivLoss(reduction='batchmean')
def forward(self, outputs, labels, outputs_teacher):
"""Compute distillation loss given outputs, labels, and outputs of teacher model
Arguments:
outputs {[type]} -- [description]
labels {[type]} -- [description]
output_teacher {[type]} -- [description]
"""
soft_target_loss = 0
if outputs_teacher is not None and self.distillation_weight > 0:
soft_target_loss = self.kldiv(F.softmax(outputs / self.
temperature, dim=1), F.softmax(outputs_teacher / self.
temperature, dim=1)) * self.temperature ** 2
hard_target_loss = F.cross_entropy(outputs, labels, reduction='mean')
total_loss = (soft_target_loss * self.distillation_weight +
hard_target_loss * (1 - self.distillation_weight))
return soft_target_loss, hard_target_loss, total_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 [[], {'temperature': 4, 'distillation_weight': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.25
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x3, tmp17, xmask)
@triton.jit
def triton_poi_fused__log_softmax__softmax_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.25
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tmp18 = triton_helpers.maximum(tmp3, tmp5)
tmp19 = triton_helpers.maximum(tmp18, tmp8)
tmp20 = triton_helpers.maximum(tmp19, tmp11)
tmp21 = tmp0 - tmp20
tl.store(out_ptr0 + x3, tmp17, xmask)
tl.store(out_ptr1 + x3, tmp21, xmask)
@triton.jit
def triton_per_fused__log_softmax__softmax_add_div_mul_neg_sub_sum_xlogy_2(
in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + r3, None)
tmp19 = tl.load(in_ptr2 + r3, None)
tmp20 = tl.load(in_ptr2 + (r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr2 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr2 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp36 = tl.load(in_ptr3 + r3, None)
tmp37 = tl.load(in_ptr3 + (r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp38 = tl.load(in_ptr3 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp40 = tl.load(in_ptr3 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp42 = tl.load(in_ptr3 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp22 = tmp20 + tmp21
tmp24 = tmp22 + tmp23
tmp26 = tmp24 + tmp25
tmp27 = tmp19 / tmp26
tmp28 = libdevice.isnan(tmp27).to(tl.int1)
tmp29 = 0.0
tmp30 = tmp27 == tmp29
tmp31 = tl_math.log(tmp27)
tmp32 = tmp27 * tmp31
tmp33 = tl.where(tmp30, tmp29, tmp32)
tmp34 = float('nan')
tmp35 = tl.where(tmp28, tmp34, tmp33)
tmp39 = tmp37 + tmp38
tmp41 = tmp39 + tmp40
tmp43 = tmp41 + tmp42
tmp44 = tmp36 / tmp43
tmp45 = tmp27 * tmp44
tmp46 = tmp35 - tmp45
tmp47 = tl.broadcast_to(tmp46, [RBLOCK])
tmp49 = triton_helpers.promote_to_tensor(tl.sum(tmp47, 0))
tmp50 = 0.25
tmp51 = tmp49 * tmp50
tmp52 = 16.0
tmp53 = tmp51 * tmp52
tmp54 = -tmp18
tmp55 = 0.015625
tmp56 = tmp54 * tmp55
tmp57 = 4.0
tmp58 = tmp53 * tmp57
tmp59 = -3.0
tmp60 = tmp56 * tmp59
tmp61 = tmp58 + tmp60
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp53, None)
tl.debug_barrier()
tl.store(in_out_ptr1 + tl.full([1], 0, tl.int32), tmp56, None)
tl.store(out_ptr1 + tl.full([1], 0, tl.int32), tmp61, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__log_softmax__softmax_1[grid(256)](arg1_1, buf2,
buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf6 = empty_strided_cuda((), (), torch.float32)
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
buf7 = buf6
del buf6
buf8 = empty_strided_cuda((), (), torch.float32)
triton_per_fused__log_softmax__softmax_add_div_mul_neg_sub_sum_xlogy_2[
grid(1)](buf4, buf7, buf5, arg2_1, buf0, buf2, buf8, 1, 256,
num_warps=2, num_stages=1)
del arg2_1
del buf0
del buf2
del buf5
return buf4, buf7, buf8
class DistillLossNew(nn.Module):
def __init__(self, temperature, distillation_weight):
super().__init__()
self.temperature = temperature
self.distillation_weight = distillation_weight
self.kldiv = nn.KLDivLoss(reduction='batchmean')
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0], output[1], output[2]
|
mrtunguyen/knowledge_distillation
|
DistillLoss
| false
| 7,292
|
[
"MIT"
] | 1
|
dd114e980dbebda6cc247f658eb801ab948ee6ba
|
https://github.com/mrtunguyen/knowledge_distillation/tree/dd114e980dbebda6cc247f658eb801ab948ee6ba
|
LinRegModel
|
import torch
import torch.nn as nn
class LinRegModel(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Parameter(torch.randn(1))
self.b = nn.Parameter(torch.randn(1))
def forward(self, x):
return self.a * x + self.b
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp4 = tl.load(in_ptr2 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp3 = tmp1 * tmp2
tmp6 = tmp3 + tmp5
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(256)](primals_1, primals_2,
primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_3
return buf0, primals_2
class LinRegModelNew(nn.Module):
def __init__(self):
super().__init__()
self.a = nn.Parameter(torch.randn(1))
self.b = nn.Parameter(torch.randn(1))
def forward(self, input_0):
primals_1 = self.a
primals_3 = self.b
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
muellerzr/walk-with-deep-learning
|
LinRegModel
| false
| 7,293
|
[
"Apache-2.0"
] | 1
|
4adbf26da4885d122ed305eccef3efbb6fb10df5
|
https://github.com/muellerzr/walk-with-deep-learning/tree/4adbf26da4885d122ed305eccef3efbb6fb10df5
|
NormalLogProb
|
import torch
import numpy as np
import torch.nn as nn
import torch.utils
import torch.utils.data
class NormalLogProb(nn.Module):
def __init__(self):
super().__init__()
def forward(self, loc, scale, z):
var = torch.pow(scale, 2)
return -0.5 * torch.log(2 * np.pi * var) - torch.pow(z - loc, 2) / (
2 * var)
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.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils
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_log_mul_pow_sub_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp7 = tl.load(in_ptr1 + x0, xmask)
tmp8 = tl.load(in_ptr2 + x0, xmask)
tmp1 = tmp0 * tmp0
tmp2 = 6.283185307179586
tmp3 = tmp1 * tmp2
tmp4 = tl_math.log(tmp3)
tmp5 = -0.5
tmp6 = tmp4 * tmp5
tmp9 = tmp7 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = 2.0
tmp12 = tmp1 * tmp11
tmp13 = tmp10 / tmp12
tmp14 = tmp6 - tmp13
tl.store(out_ptr0 + x0, tmp14, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_log_mul_pow_sub_0[grid(256)](arg0_1, arg1_1,
arg2_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf0,
class NormalLogProbNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
msunardi/vae_experiment
|
NormalLogProb
| false
| 7,294
|
[
"MIT"
] | 1
|
e3ce39e586f1189d157e753370a90c07713658b3
|
https://github.com/msunardi/vae_experiment/tree/e3ce39e586f1189d157e753370a90c07713658b3
|
VGGNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class VGGNet(nn.Module):
def __init__(self):
super(VGGNet, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1))
self.conv2 = nn.Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1))
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
self.fc1 = nn.Linear(32 * 64 * 64, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, 6)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = self.pool(x)
x = x.view(-1, 32 * 64 * 64)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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 // 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_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
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)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_relu_2(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
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
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, primals_9, primals_10, primals_11) = 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, 64, 64), (12288, 4096, 64, 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, (128, 131072), (131072, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (128, 128), (128, 1))
assert_size_stride(primals_9, (128,), (1,))
assert_size_stride(primals_10, (6, 128), (128, 1))
assert_size_stride(primals_11, (6,), (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=512, num_warps=8, 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, 32, 64, 64), (131072, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(524288)](buf3, primals_5,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 32, 32, 32), (32768, 1024, 32, 1),
torch.int8)
buf5 = empty_strided_cuda((4, 32, 32, 32), (32768, 1024, 32, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_1[grid(131072)](buf3, buf4,
buf5, 131072, XBLOCK=512, num_warps=8, num_stages=1)
buf6 = empty_strided_cuda((1, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (1, 131072), (0, 1), 0),
reinterpret_tensor(primals_6, (131072, 128), (1, 131072), 0),
out=buf6)
buf7 = buf6
del buf6
triton_poi_fused_relu_2[grid(128)](buf7, primals_7, 128, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_7
buf8 = empty_strided_cuda((1, 128), (128, 1), torch.float32)
extern_kernels.mm(buf7, reinterpret_tensor(primals_8, (128, 128), (
1, 128), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_2[grid(128)](buf9, primals_9, 128, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_9
buf10 = empty_strided_cuda((1, 6), (6, 1), torch.float32)
extern_kernels.addmm(primals_11, buf9, reinterpret_tensor(
primals_10, (128, 6), (1, 128), 0), alpha=1, beta=1, out=buf10)
del primals_11
return (buf10, primals_1, primals_3, primals_4, buf1, buf3, buf4,
reinterpret_tensor(buf5, (1, 131072), (131072, 1), 0), buf7, buf9,
primals_10, primals_8, primals_6)
class VGGNetNew(nn.Module):
def __init__(self):
super(VGGNetNew, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1))
self.conv2 = nn.Conv2d(32, 32, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1))
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
self.fc1 = nn.Linear(32 * 64 * 64, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, 6)
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_10 = self.fc3.weight
primals_11 = 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])
return output[0]
|
miyosuda/oculomotor
|
VGGNet
| false
| 7,295
|
[
"Apache-2.0"
] | 1
|
78e7ec61a808d058116c69bff1ea71ecf117c126
|
https://github.com/miyosuda/oculomotor/tree/78e7ec61a808d058116c69bff1ea71ecf117c126
|
CNN
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class CNN(nn.Module):
""" CNN for heat shock protein classification """
def __init__(self, model_cfg, in_channels, dropout_rate):
super(CNN, self).__init__()
self.embedder = model_cfg.embedder
if self.embedder != 'OneHot':
self.embed = nn.Linear(in_channels, model_cfg.embed_dim)
in_channels = model_cfg.embed_dim
self.conv = nn.Conv1d(in_channels, model_cfg.num_channels,
model_cfg.kernel_size, 1)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=dropout_rate if dropout_rate is not
None else 0)
self.max_pool = nn.AdaptiveMaxPool1d(1)
self.linear = nn.Linear(model_cfg.num_channels, 7)
def forward(self, x):
if self.embedder != 'OneHot':
x = self.embed(x)
x = x.permute(0, 2, 1)
x = self.relu(self.conv(x))
x = self.max_pool(x).reshape(len(x), -1)
x = self.dropout(x)
x = self.linear(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'model_cfg': _mock_config(embedder=4, embed_dim=4,
num_channels=4, kernel_size=4), 'in_channels': 4, 'dropout_rate': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_adaptive_max_pool2d_convolution_relu_threshold_backward_1(
in_out_ptr0, in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_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 = tl.full([1], 0, tl.int64)
tmp6 = 0.0
tmp7 = tmp4 <= tmp6
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp5, xmask)
tl.store(out_ptr1 + x2, tmp4, xmask)
tl.store(out_ptr2 + x2, tmp7, 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), (16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (7, 4), (4, 1))
assert_size_stride(primals_7, (7,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (16,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](buf0, buf1, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 1), (4, 1, 1))
del buf1
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.int64)
buf5 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.bool)
triton_poi_fused_adaptive_max_pool2d_convolution_relu_threshold_backward_1[
grid(16)](buf3, primals_5, buf4, buf5, buf7, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 7), (7, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf5, (4, 4), (4,
1), 0), reinterpret_tensor(primals_6, (4, 7), (1, 4), 0), alpha
=1, beta=1, out=buf6)
del primals_7
return buf6, primals_4, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), reinterpret_tensor(buf0, (4, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf3, (4, 4, 1, 1), (4, 1, 1, 1), 0
), buf4, reinterpret_tensor(buf5, (4, 4), (4, 1), 0), primals_6, buf7
class CNNNew(nn.Module):
""" CNN for heat shock protein classification """
def __init__(self, model_cfg, in_channels, dropout_rate):
super(CNNNew, self).__init__()
self.embedder = model_cfg.embedder
if self.embedder != 'OneHot':
self.embed = nn.Linear(in_channels, model_cfg.embed_dim)
in_channels = model_cfg.embed_dim
self.conv = nn.Conv1d(in_channels, model_cfg.num_channels,
model_cfg.kernel_size, 1)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=dropout_rate if dropout_rate is not
None else 0)
self.max_pool = nn.AdaptiveMaxPool1d(1)
self.linear = nn.Linear(model_cfg.num_channels, 7)
def forward(self, input_0):
primals_1 = self.embed.weight
primals_2 = self.embed.bias
primals_3 = self.conv.weight
primals_5 = self.conv.bias
primals_6 = self.linear.weight
primals_7 = self.linear.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
mswzeus/DeeperHSP
|
CNN
| false
| 7,296
|
[
"MIT"
] | 1
|
571387f048d3c33fcd78730fdaef57b6c44a27a7
|
https://github.com/mswzeus/DeeperHSP/tree/571387f048d3c33fcd78730fdaef57b6c44a27a7
|
BlendLinear
|
import torch
import torch.nn as nn
import torch.utils.data
class BlendLinear(nn.Module):
def __init__(self, dim_in, dim_out, layer_type=nn.Linear, **unused_kwargs):
super(BlendLinear, self).__init__()
self._layer0 = layer_type(dim_in, dim_out)
self._layer1 = layer_type(dim_in, dim_out)
def forward(self, t, x):
y0 = self._layer0(x)
y1 = self._layer1(x)
return y0 + (y1 - y0) * t
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mul_sub_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
in_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_ptr3 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp5 - tmp2
tmp8 = tmp6 * tmp7
tmp9 = tmp2 + tmp8
tl.store(in_out_ptr0 + x2, tmp9, 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)
del primals_1
buf1 = 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=buf1)
del primals_4
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_mul_sub_0[grid(256)](buf2, primals_2, buf1,
primals_5, primals_6, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_2
del primals_5
return buf2, primals_6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
class BlendLinearNew(nn.Module):
def __init__(self, dim_in, dim_out, layer_type=nn.Linear, **unused_kwargs):
super(BlendLinearNew, self).__init__()
self._layer0 = layer_type(dim_in, dim_out)
self._layer1 = layer_type(dim_in, dim_out)
def forward(self, input_0, input_1):
primals_1 = self._layer0.weight
primals_2 = self._layer0.bias
primals_4 = self._layer1.weight
primals_5 = self._layer1.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]
|
musyoku/ffjord
|
BlendLinear
| false
| 7,297
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
BlendConv2d
|
import torch
import torch.nn as nn
import torch.utils.data
class BlendConv2d(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0,
dilation=1, groups=1, bias=True, transpose=False, **unused_kwargs):
super(BlendConv2d, self).__init__()
module = nn.ConvTranspose2d if transpose else nn.Conv2d
self._layer0 = module(dim_in, dim_out, kernel_size=ksize, stride=
stride, padding=padding, dilation=dilation, groups=groups, bias
=bias)
self._layer1 = module(dim_in, dim_out, kernel_size=ksize, stride=
stride, padding=padding, dilation=dilation, groups=groups, bias
=bias)
def forward(self, t, x):
y0 = self._layer0(x)
y1 = self._layer1(x)
return y0 + (y1 - y0) * t
def get_inputs():
return [torch.rand([4, 4, 2, 2]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_add_convolution_mul_sub_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
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)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp5 - tmp2
tmp8 = tmp6 * tmp7
tmp9 = tmp2 + tmp8
tl.store(in_out_ptr0 + x3, tmp9, 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, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 2, 2), (16, 4, 2, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 2, 2), (16, 4, 2, 1))
buf1 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 2, 2), (16, 4, 2, 1))
buf2 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_convolution_mul_sub_0[grid(64)](buf2,
primals_2, buf1, primals_5, primals_6, 64, XBLOCK=64, num_warps
=1, num_stages=1)
del buf1
del primals_2
del primals_5
return buf2, primals_1, primals_3, primals_4, primals_6
class BlendConv2dNew(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0,
dilation=1, groups=1, bias=True, transpose=False, **unused_kwargs):
super(BlendConv2dNew, self).__init__()
module = nn.ConvTranspose2d if transpose else nn.Conv2d
self._layer0 = module(dim_in, dim_out, kernel_size=ksize, stride=
stride, padding=padding, dilation=dilation, groups=groups, bias
=bias)
self._layer1 = module(dim_in, dim_out, kernel_size=ksize, stride=
stride, padding=padding, dilation=dilation, groups=groups, bias
=bias)
def forward(self, input_0, input_1):
primals_1 = self._layer0.weight
primals_2 = self._layer0.bias
primals_4 = self._layer1.weight
primals_5 = self._layer1.bias
primals_6 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
musyoku/ffjord
|
BlendConv2d
| false
| 7,298
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
GINPreTransition
|
import torch
import typing
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, input_dim, hidden_sizes: 'typing.Iterable[int]',
out_dim, activation_function=nn.Sigmoid(), activation_out=None):
super(MLP, self).__init__()
i_h_sizes = [input_dim] + hidden_sizes
self.mlp = nn.Sequential()
for idx in range(len(i_h_sizes) - 1):
self.mlp.add_module('layer_{}'.format(idx), nn.Linear(
in_features=i_h_sizes[idx], out_features=i_h_sizes[idx + 1]))
self.mlp.add_module('act', activation_function)
self.mlp.add_module('out_layer', nn.Linear(i_h_sizes[-1], out_dim))
if activation_out is not None:
self.mlp.add_module('out_layer_activation', activation_out)
def init(self):
for i, l in enumerate(self.mlp):
if type(l) == nn.Linear:
nn.init.xavier_normal_(l.weight)
def forward(self, x):
return self.mlp(x)
class GINPreTransition(nn.Module):
def __init__(self, node_state_dim: 'int', node_label_dim: 'int',
mlp_hidden_dim: 'typing.Iterable[int]', activation_function=nn.Tanh()):
super(type(self), self).__init__()
d_i = node_state_dim + node_label_dim
d_o = node_state_dim
d_h = list(mlp_hidden_dim)
self.mlp = MLP(input_dim=d_i, hidden_sizes=d_h, out_dim=d_o,
activation_function=activation_function, activation_out=
activation_function)
def forward(self, node_states, node_labels, edges, agg_matrix):
intermediate_states = self.mlp(torch.cat([node_states, node_labels],
-1))
new_state = torch.matmul(agg_matrix, intermediate_states[edges[:, 1]]
) + torch.matmul(agg_matrix, intermediate_states[edges[:, 0]])
return new_state
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.ones([4, 4],
dtype=torch.int64), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'node_state_dim': 4, 'node_label_dim': 4, 'mlp_hidden_dim':
[4, 4]}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import typing
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 = 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 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_index_tanh_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + 4 * 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)
tmp7 = libdevice.tanh(tmp6)
tmp9 = tmp8 + tmp1
tmp10 = tmp8 < 0
tmp11 = tl.where(tmp10, tmp9, tmp8)
tl.device_assert((0 <= tmp11) & (tmp11 < 4) | ~xmask,
'index out of bounds: 0 <= tmp11 < 4')
tmp13 = tl.load(in_ptr1 + (x0 + 4 * tmp11), xmask)
tmp14 = libdevice.tanh(tmp13)
tl.store(out_ptr0 + x2, tmp7, xmask)
tl.store(out_ptr1 + x2, tmp14, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 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,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 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_tanh_1[grid(16)](buf2, primals_4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, buf2, reinterpret_tensor(primals_5,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
del primals_6
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_8, buf3, reinterpret_tensor(primals_7,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf4)
del primals_8
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_index_tanh_2[grid(16)](primals_9, buf4, buf5, buf6,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels._mm_plus_mm(primals_10, buf5, primals_10, buf6, out=buf7
)
del buf5
del buf6
return buf7, buf0, buf2, buf3, buf4, reinterpret_tensor(primals_9, (4,),
(4,), 1), reinterpret_tensor(primals_9, (4,), (4,), 0
), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0
), primals_7, primals_5
class MLP(nn.Module):
def __init__(self, input_dim, hidden_sizes: 'typing.Iterable[int]',
out_dim, activation_function=nn.Sigmoid(), activation_out=None):
super(MLP, self).__init__()
i_h_sizes = [input_dim] + hidden_sizes
self.mlp = nn.Sequential()
for idx in range(len(i_h_sizes) - 1):
self.mlp.add_module('layer_{}'.format(idx), nn.Linear(
in_features=i_h_sizes[idx], out_features=i_h_sizes[idx + 1]))
self.mlp.add_module('act', activation_function)
self.mlp.add_module('out_layer', nn.Linear(i_h_sizes[-1], out_dim))
if activation_out is not None:
self.mlp.add_module('out_layer_activation', activation_out)
def init(self):
for i, l in enumerate(self.mlp):
if type(l) == nn.Linear:
nn.init.xavier_normal_(l.weight)
def forward(self, x):
return self.mlp(x)
class GINPreTransitionNew(nn.Module):
def __init__(self, node_state_dim: 'int', node_label_dim: 'int',
mlp_hidden_dim: 'typing.Iterable[int]', activation_function=nn.Tanh()):
super(type(self), self).__init__()
d_i = node_state_dim + node_label_dim
d_o = node_state_dim
d_h = list(mlp_hidden_dim)
self.mlp = MLP(input_dim=d_i, hidden_sizes=d_h, out_dim=d_o,
activation_function=activation_function, activation_out=
activation_function)
def forward(self, input_0, input_1, input_2, input_3):
primals_3 = self.mlp.mlp.layer_0.weight
primals_4 = self.mlp.mlp.layer_0.bias
primals_1 = self.mlp.mlp.layer_1.weight
primals_6 = self.mlp.mlp.layer_1.bias
primals_2 = self.mlp.mlp.out_layer.weight
primals_8 = self.mlp.mlp.out_layer.bias
primals_5 = input_0
primals_7 = input_1
primals_9 = input_2
primals_10 = input_3
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]
|
mtiezzi/gnn_site
|
GINPreTransition
| false
| 7,299
|
[
"BSD-3-Clause"
] | 1
|
79a13603db876ac24e66a152104faa8b76e1d8e7
|
https://github.com/mtiezzi/gnn_site/tree/79a13603db876ac24e66a152104faa8b76e1d8e7
|
ConcatSquashLinear
|
import torch
import torch.nn as nn
import torch.utils.data
class ConcatSquashLinear(nn.Module):
def __init__(self, dim_in, dim_out):
super(ConcatSquashLinear, self).__init__()
self._layer = nn.Linear(dim_in, dim_out)
self._hyper_bias = nn.Linear(1, dim_out, bias=False)
self._hyper_gate = nn.Linear(1, dim_out)
def forward(self, t, x):
return self._layer(x) * torch.sigmoid(self._hyper_gate(t.view(1, 1))
) + self._hyper_bias(t.view(1, 1))
def get_inputs():
return [torch.rand([1, 1]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mul_sigmoid_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tmp5 = tmp3 + tmp4
tl.store(out_ptr0 + x2, tmp5, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 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), (1, 1))
assert_size_stride(primals_5, (4, 1), (1, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, primals_4, reinterpret_tensor(
primals_5, (1, 4), (1, 1), 0), alpha=1, beta=1, out=buf1)
del primals_5
del primals_6
buf2 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_4, reinterpret_tensor(primals_7, (1, 4),
(1, 1), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_sigmoid_0[grid(256)](buf0, buf1, buf2,
buf3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
return buf3, primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, buf1
class ConcatSquashLinearNew(nn.Module):
def __init__(self, dim_in, dim_out):
super(ConcatSquashLinearNew, self).__init__()
self._layer = nn.Linear(dim_in, dim_out)
self._hyper_bias = nn.Linear(1, dim_out, bias=False)
self._hyper_gate = nn.Linear(1, dim_out)
def forward(self, input_0, input_1):
primals_1 = self._layer.weight
primals_2 = self._layer.bias
primals_5 = self._hyper_bias.weight
primals_7 = self._hyper_gate.weight
primals_6 = self._hyper_gate.bias
primals_4 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
musyoku/ffjord
|
ConcatSquashLinear
| false
| 7,300
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
ConcatSquashConv2d
|
import torch
import torch.nn as nn
import torch.utils.data
class ConcatSquashConv2d(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0,
dilation=1, groups=1, bias=True, transpose=False):
super(ConcatSquashConv2d, self).__init__()
module = nn.ConvTranspose2d if transpose else nn.Conv2d
self._layer = module(dim_in, dim_out, kernel_size=ksize, stride=
stride, padding=padding, dilation=dilation, groups=groups, bias
=bias)
self._hyper_gate = nn.Linear(1, dim_out)
self._hyper_bias = nn.Linear(1, dim_out, bias=False)
def forward(self, t, x):
return self._layer(x) * torch.sigmoid(self._hyper_gate(t.view(1, 1))
).view(1, -1, 1, 1) + self._hyper_bias(t.view(1, 1)).view(1, -1,
1, 1)
def get_inputs():
return [torch.rand([1, 1]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_convolution_mul_0(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
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tl.sigmoid(tmp3)
tmp5 = tmp2 * tmp4
tmp7 = tmp5 + tmp6
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 1), (1, 1))
assert_size_stride(primals_5, (4, 1), (1, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 2, 2), (16, 4, 2, 1))
buf2 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, primals_4, reinterpret_tensor(
primals_5, (1, 4), (1, 1), 0), alpha=1, beta=1, out=buf2)
del primals_5
del primals_6
buf3 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_4, reinterpret_tensor(primals_7, (1, 4),
(1, 1), 0), out=buf3)
del primals_7
buf1 = buf0
del buf0
buf4 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_convolution_mul_0[grid(64)](buf1, primals_2,
buf2, buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf3
del primals_2
return buf4, primals_1, primals_3, primals_4, buf1, buf2
class ConcatSquashConv2dNew(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0,
dilation=1, groups=1, bias=True, transpose=False):
super(ConcatSquashConv2dNew, self).__init__()
module = nn.ConvTranspose2d if transpose else nn.Conv2d
self._layer = module(dim_in, dim_out, kernel_size=ksize, stride=
stride, padding=padding, dilation=dilation, groups=groups, bias
=bias)
self._hyper_gate = nn.Linear(1, dim_out)
self._hyper_bias = nn.Linear(1, dim_out, bias=False)
def forward(self, input_0, input_1):
primals_1 = self._layer.weight
primals_2 = self._layer.bias
primals_5 = self._hyper_gate.weight
primals_6 = self._hyper_gate.bias
primals_7 = self._hyper_bias.weight
primals_4 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
musyoku/ffjord
|
ConcatSquashConv2d
| false
| 7,301
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
GatedConv
|
import torch
import torch.nn as nn
import torch.utils.data
class GatedConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, groups=1):
super(GatedConv, self).__init__()
self.layer_f = nn.Conv2d(in_channels, out_channels, kernel_size,
stride=stride, padding=padding, dilation=1, groups=groups)
self.layer_g = nn.Conv2d(in_channels, out_channels, kernel_size,
stride=stride, padding=padding, dilation=1, groups=groups)
def forward(self, x):
f = self.layer_f(x)
g = torch.sigmoid(self.layer_g(x))
return f * g
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_mul_sigmoid_0(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tl.sigmoid(tmp5)
tmp7 = tmp2 * tmp6
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(in_out_ptr1 + x2, tmp5, xmask)
tl.store(out_ptr0 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 1, 1), (4, 1, 1, 1))
buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 1, 1), (4, 1, 1, 1))
buf1 = buf0
del buf0
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_mul_sigmoid_0[grid(16)](buf1, buf3,
primals_2, primals_5, buf4, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_2
del primals_5
return buf4, primals_1, primals_3, primals_4, buf1, buf3
class GatedConvNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, groups=1):
super(GatedConvNew, self).__init__()
self.layer_f = nn.Conv2d(in_channels, out_channels, kernel_size,
stride=stride, padding=padding, dilation=1, groups=groups)
self.layer_g = nn.Conv2d(in_channels, out_channels, kernel_size,
stride=stride, padding=padding, dilation=1, groups=groups)
def forward(self, input_0):
primals_1 = self.layer_f.weight
primals_2 = self.layer_f.bias
primals_3 = self.layer_g.weight
primals_5 = self.layer_g.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
musyoku/ffjord
|
GatedConv
| false
| 7,302
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
GatedConv2d
|
import torch
import torch.nn as nn
import torch.utils.data
class GatedConv2d(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, stride,
padding, dilation=1, activation=None):
super(GatedConv2d, self).__init__()
self.activation = activation
self.sigmoid = nn.Sigmoid()
self.h = nn.Conv2d(input_channels, output_channels, kernel_size,
stride, padding, dilation)
self.g = nn.Conv2d(input_channels, output_channels, kernel_size,
stride, padding, dilation)
def forward(self, x):
if self.activation is None:
h = self.h(x)
else:
h = self.activation(self.h(x))
g = self.sigmoid(self.g(x))
return h * g
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_channels': 4, 'output_channels': 4, 'kernel_size':
4, 'stride': 1, 'padding': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_mul_sigmoid_0(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, 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')
tmp3 = tl.load(in_out_ptr1 + x3, xmask)
tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tl.sigmoid(tmp5)
tmp7 = tmp2 * tmp6
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(in_out_ptr1 + x3, tmp5, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 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,))
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))
buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(4, 4), 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))
buf1 = buf0
del buf0
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_sigmoid_0[grid(1296)](buf1, buf3,
primals_2, primals_5, buf4, 1296, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_2
del primals_5
return buf4, primals_1, primals_3, primals_4, buf1, buf3
class GatedConv2dNew(nn.Module):
def __init__(self, input_channels, output_channels, kernel_size, stride,
padding, dilation=1, activation=None):
super(GatedConv2dNew, self).__init__()
self.activation = activation
self.sigmoid = nn.Sigmoid()
self.h = nn.Conv2d(input_channels, output_channels, kernel_size,
stride, padding, dilation)
self.g = nn.Conv2d(input_channels, output_channels, kernel_size,
stride, padding, dilation)
def forward(self, input_0):
primals_1 = self.h.weight
primals_2 = self.h.bias
primals_3 = self.g.weight
primals_5 = self.g.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
musyoku/ffjord
|
GatedConv2d
| false
| 7,303
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
GatedConvTranspose
|
import torch
import torch.nn as nn
import torch.utils.data
class GatedConvTranspose(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, output_padding=0, groups=1):
super(GatedConvTranspose, self).__init__()
self.layer_f = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, output_padding=
output_padding, groups=groups)
self.layer_g = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, output_padding=
output_padding, groups=groups)
def forward(self, x):
f = self.layer_f(x)
g = torch.sigmoid(self.layer_g(x))
return f * g
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_mul_sigmoid_0(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 784
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 49 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr1 + x3, xmask)
tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tl.sigmoid(tmp5)
tmp7 = tmp2 * tmp6
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(in_out_ptr1 + x3, tmp5, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 7, 7), (196, 49, 7, 1))
buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 7, 7), (196, 49, 7, 1))
buf1 = buf0
del buf0
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 7, 7), (196, 49, 7, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_mul_sigmoid_0[grid(784)](buf1, buf3,
primals_2, primals_5, buf4, 784, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_2
del primals_5
return buf4, primals_1, primals_3, primals_4, buf1, buf3
class GatedConvTransposeNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, output_padding=0, groups=1):
super(GatedConvTransposeNew, self).__init__()
self.layer_f = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, output_padding=
output_padding, groups=groups)
self.layer_g = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size, stride=stride, padding=padding, output_padding=
output_padding, groups=groups)
def forward(self, input_0):
primals_1 = self.layer_f.weight
primals_2 = self.layer_f.bias
primals_3 = self.layer_g.weight
primals_5 = self.layer_g.bias
primals_4 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
musyoku/ffjord
|
GatedConvTranspose
| false
| 7,304
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
HyperConv2d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1 or classname.find('Conv') != -1:
nn.init.constant_(m.weight, 0)
nn.init.normal_(m.bias, 0, 0.01)
class HyperConv2d(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0,
dilation=1, groups=1, bias=True, transpose=False):
super(HyperConv2d, self).__init__()
assert dim_in % groups == 0 and dim_out % groups == 0, 'dim_in and dim_out must both be divisible by groups.'
self.dim_in = dim_in
self.dim_out = dim_out
self.ksize = ksize
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.bias = bias
self.transpose = transpose
self.params_dim = int(dim_in * dim_out * ksize * ksize / groups)
if self.bias:
self.params_dim += dim_out
self._hypernet = nn.Linear(1, self.params_dim)
self.conv_fn = F.conv_transpose2d if transpose else F.conv2d
self._hypernet.apply(weights_init)
def forward(self, t, x):
params = self._hypernet(t.view(1, 1)).view(-1)
weight_size = int(self.dim_in * self.dim_out * self.ksize * self.
ksize / self.groups)
if self.transpose:
weight = params[:weight_size].view(self.dim_in, self.dim_out //
self.groups, self.ksize, self.ksize)
else:
weight = params[:weight_size].view(self.dim_out, self.dim_in //
self.groups, self.ksize, self.ksize)
bias = params[:self.dim_out].view(self.dim_out) if self.bias else None
return self.conv_fn(x, weight=weight, bias=bias, stride=self.stride,
padding=self.padding, groups=self.groups, dilation=self.dilation)
def get_inputs():
return [torch.rand([1, 1]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_in': 4, 'dim_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 1), (1, 1))
assert_size_stride(primals_2, (148, 1), (1, 1))
assert_size_stride(primals_3, (148,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 148), (148, 1), torch.float32)
extern_kernels.addmm(primals_3, primals_1, reinterpret_tensor(
primals_2, (1, 148), (1, 1), 0), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = extern_kernels.convolution(primals_4, reinterpret_tensor(
buf0, (4, 4, 3, 3), (36, 9, 3, 1), 0), stride=(1, 1), padding=(
0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 2, 2), (16, 4, 2, 1))
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(64)](buf2, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf2, primals_1, primals_4, reinterpret_tensor(buf0, (4, 4, 3, 3
), (36, 9, 3, 1), 0)
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1 or classname.find('Conv') != -1:
nn.init.constant_(m.weight, 0)
nn.init.normal_(m.bias, 0, 0.01)
class HyperConv2dNew(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0,
dilation=1, groups=1, bias=True, transpose=False):
super(HyperConv2dNew, self).__init__()
assert dim_in % groups == 0 and dim_out % groups == 0, 'dim_in and dim_out must both be divisible by groups.'
self.dim_in = dim_in
self.dim_out = dim_out
self.ksize = ksize
self.stride = stride
self.padding = padding
self.dilation = dilation
self.groups = groups
self.bias = bias
self.transpose = transpose
self.params_dim = int(dim_in * dim_out * ksize * ksize / groups)
if self.bias:
self.params_dim += dim_out
self._hypernet = nn.Linear(1, self.params_dim)
self.conv_fn = F.conv_transpose2d if transpose else F.conv2d
self._hypernet.apply(weights_init)
def forward(self, input_0, input_1):
primals_2 = self._hypernet.weight
primals_3 = self._hypernet.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
musyoku/ffjord
|
HyperConv2d
| false
| 7,305
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
BasicBlock
|
import torch
import torch.nn as nn
import torch.utils.data
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, dim):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.GroupNorm(2, dim, eps=0.0001)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False)
self.bn2 = nn.GroupNorm(2, dim, eps=0.0001)
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out += residual
out = self.relu(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_native_group_norm_0(in_ptr0, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 8
RBLOCK: tl.constexpr = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 32 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 32, 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 = 32.0
tmp18 = tmp16 / tmp17
tmp19 = 0.0001
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tl.store(out_ptr2 + x0, tmp21, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
tl.store(out_ptr1 + x0, tmp16, xmask)
@triton.jit
def triton_poi_fused_native_group_norm_relu_1(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex // 16
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x4 // 2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4 // 2, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = 32.0
tmp5 = tmp3 / tmp4
tmp6 = 0.0001
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp2 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tmp14 = tl.full([1], 0, tl.int32)
tmp15 = triton_helpers.maximum(tmp14, tmp13)
tl.store(out_ptr0 + x3, tmp15, xmask)
@triton.jit
def triton_poi_fused_add_native_group_norm_relu_threshold_backward_2(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, out_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex // 16
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x4 // 2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4 // 2, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr5 + x3, xmask)
tmp2 = tmp0 - tmp1
tmp4 = 32.0
tmp5 = tmp3 / tmp4
tmp6 = 0.0001
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp2 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp16 = tl.full([1], 0, tl.int32)
tmp17 = triton_helpers.maximum(tmp16, tmp15)
tmp18 = 0.0
tmp19 = tmp17 <= tmp18
tl.store(out_ptr0 + x3, tmp17, xmask)
tl.store(out_ptr1 + x3, tmp19, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 2, 1, 1), (2, 1, 8, 8), torch.float32)
buf2 = empty_strided_cuda((4, 2, 1, 1), (2, 1, 8, 8), torch.float32)
buf4 = empty_strided_cuda((4, 2, 1, 1), (2, 1, 8, 8), torch.float32)
get_raw_stream(0)
triton_per_fused_native_group_norm_0[grid(8)](buf0, buf1, buf2,
buf4, 8, 32, XBLOCK=1, num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_group_norm_relu_1[grid(256)](buf0, buf1,
buf2, primals_3, primals_4, buf5, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_4
buf6 = extern_kernels.convolution(buf5, primals_5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1))
buf7 = buf2
del buf2
buf8 = empty_strided_cuda((4, 2, 1, 1), (2, 1, 8, 8), torch.float32)
buf10 = empty_strided_cuda((4, 2, 1, 1), (2, 1, 8, 8), torch.float32)
triton_per_fused_native_group_norm_0[grid(8)](buf6, buf7, buf8,
buf10, 8, 32, XBLOCK=1, num_warps=2, num_stages=1)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_native_group_norm_relu_threshold_backward_2[grid
(256)](buf6, buf7, buf8, primals_6, primals_7, primals_1, buf11,
buf12, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf8
del primals_7
return (buf11, primals_1, primals_2, primals_3, primals_5, primals_6,
buf0, reinterpret_tensor(buf1, (4, 2), (2, 1), 0),
reinterpret_tensor(buf4, (4, 2), (2, 1), 0), buf5, buf6,
reinterpret_tensor(buf7, (4, 2), (2, 1), 0), reinterpret_tensor(
buf10, (4, 2), (2, 1), 0), buf12)
class BasicBlockNew(nn.Module):
expansion = 1
def __init__(self, dim):
super(BasicBlockNew, self).__init__()
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.GroupNorm(2, dim, eps=0.0001)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False)
self.bn2 = nn.GroupNorm(2, dim, eps=0.0001)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.bn1.weight
primals_4 = self.bn1.bias
primals_5 = self.conv2.weight
primals_6 = self.bn2.weight
primals_7 = self.bn2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
musyoku/ffjord
|
BasicBlock
| false
| 7,306
|
[
"MIT"
] | 1
|
9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
https://github.com/musyoku/ffjord/tree/9e431e122e59fa9a71f3f301dec8fdd3db51e0ce
|
PNTrainingSigmoid
|
import torch
from torch import nn
class PNTrainingSigmoid(nn.Module):
def __init__(self):
super(PNTrainingSigmoid, self).__init__()
return
def forward(self, output_p, output_n, prior):
cost = prior * torch.mean(torch.sigmoid(-output_p))
cost = cost + (1 - prior) * torch.mean(torch.sigmoid(output_n))
return cost
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 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_mul_neg_rsub_sigmoid_0(in_ptr0, in_ptr1,
in_ptr2, out_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)
tmp6 = tl.load(in_ptr1 + r0, None)
tmp11 = tl.load(in_ptr2 + r0, None)
tmp1 = -tmp0
tmp2 = tl.sigmoid(tmp1)
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp7 = tl.sigmoid(tmp6)
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp12 = 256.0
tmp13 = tmp5 / tmp12
tmp14 = tmp11 * tmp13
tmp15 = 1.0
tmp16 = tmp15 - tmp11
tmp17 = tmp10 / tmp12
tmp18 = tmp16 * tmp17
tmp19 = tmp14 + tmp18
tl.store(out_ptr2 + tl.broadcast_to(r0, [RBLOCK]), 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)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_mean_mul_neg_rsub_sigmoid_0[grid(1)](arg0_1,
arg2_1, arg1_1, buf2, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf2,
class PNTrainingSigmoidNew(nn.Module):
def __init__(self):
super(PNTrainingSigmoidNew, self).__init__()
return
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]
|
mxuq/Imbalance-PU
|
PNTrainingSigmoid
| false
| 7,307
|
[
"MIT"
] | 1
|
fd4403b05f98ca6bc8156783e8275888d63f6435
|
https://github.com/mxuq/Imbalance-PU/tree/fd4403b05f98ca6bc8156783e8275888d63f6435
|
TwoWordPSDProbe
|
import torch
import torch.nn as nn
class Probe(nn.Module):
pass
class TwoWordPSDProbe(Probe):
""" Computes squared L2 distance after projection by a matrix.
For a batch of sentences, computes all n^2 pairs of distances
for each sentence in the batch.
"""
def __init__(self, model_dim, probe_rank=1024):
None
super(TwoWordPSDProbe, self).__init__()
self.probe_rank = probe_rank
self.model_dim = model_dim
self.proj = nn.Parameter(data=torch.zeros(self.model_dim, self.
probe_rank))
nn.init.uniform_(self.proj, -0.05, 0.05)
def forward(self, batch):
""" Computes all n^2 pairs of distances after projection
for each sentence in a batch.
Note that due to padding, some distances will be non-zero for pads.
Computes (B(h_i-h_j))^T(B(h_i-h_j)) for all i,j
Args:
batch: a batch of word representations of the shape
(batch_size, max_seq_len, representation_dim)
Returns:
A tensor of distances of shape (batch_size, max_seq_len, max_seq_len)
"""
transformed = torch.matmul(batch, self.proj)
_batchlen, seqlen, _rank = transformed.size()
transformed = transformed.unsqueeze(2)
transformed = transformed.expand(-1, -1, seqlen, -1)
transposed = transformed.transpose(1, 2)
diffs = transformed - transposed
squared_diffs = diffs.pow(2)
squared_distances = torch.sum(squared_diffs, -1)
return squared_distances
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'model_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_red_fused_pow_sub_sum_0(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 64
rnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x4 = xindex // 4
x0 = xindex % 4
x2 = xindex // 16
_tmp5 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x5 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r3 = rindex
tmp0 = tl.load(in_ptr0 + (r3 + 1024 * x4), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tl.load(in_ptr0 + (r3 + 1024 * x0 + 4096 * x2), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = _tmp5 + tmp4
_tmp5 = tl.where(rmask & xmask, tmp6, _tmp5)
tmp5 = tl.sum(_tmp5, 1)[:, None]
tl.store(out_ptr0 + x5, tmp5, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 1024), (1024, 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((16, 1024), (1024, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
primals_1, out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_red_fused_pow_sub_sum_0[grid(64)](buf0, buf1, 64, 1024,
XBLOCK=1, RBLOCK=1024, num_warps=8, num_stages=1)
return buf1, buf0, reinterpret_tensor(primals_2, (4, 16), (1, 4), 0)
class Probe(nn.Module):
pass
class TwoWordPSDProbeNew(Probe):
""" Computes squared L2 distance after projection by a matrix.
For a batch of sentences, computes all n^2 pairs of distances
for each sentence in the batch.
"""
def __init__(self, model_dim, probe_rank=1024):
None
super(TwoWordPSDProbeNew, self).__init__()
self.probe_rank = probe_rank
self.model_dim = model_dim
self.proj = nn.Parameter(data=torch.zeros(self.model_dim, self.
probe_rank))
nn.init.uniform_(self.proj, -0.05, 0.05)
def forward(self, input_0):
primals_1 = self.proj
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
muziyongshixin/pytorch_SSRP
|
TwoWordPSDProbe
| false
| 7,308
|
[
"MIT"
] | 1
|
e54b3098927ba2ff16bdc8f64f3a2bf46d1f72c5
|
https://github.com/muziyongshixin/pytorch_SSRP/tree/e54b3098927ba2ff16bdc8f64f3a2bf46d1f72c5
|
GroupPointWise
|
import torch
import torch.nn as nn
class GroupPointWise(nn.Module):
def __init__(self, in_dim, n_heads=4, proj_factor=1, target_dim=None):
super().__init__()
if target_dim is not None:
proj_ch = target_dim // proj_factor
else:
proj_ch = in_dim // proj_factor
self.w = nn.Parameter(torch.Tensor(in_dim, n_heads, proj_ch // n_heads)
)
nn.init.normal_(self.w, std=0.01)
def forward(self, x):
x = x.permute(0, 2, 3, 1)
out = torch.einsum('bhwc,cnp->bnhwp', x, self.w)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 1, 1), (64, 16, 4, 1, 1, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((1, 64, 4), (256, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (1, 64, 4), (0, 4, 1),
0), reinterpret_tensor(primals_2, (1, 4, 4), (16, 4, 1), 0),
out=buf1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4, 1), (64, 1, 16, 4, 1), 0
), reinterpret_tensor(buf0, (1, 4, 64), (256, 1, 4), 0)
class GroupPointWiseNew(nn.Module):
def __init__(self, in_dim, n_heads=4, proj_factor=1, target_dim=None):
super().__init__()
if target_dim is not None:
proj_ch = target_dim // proj_factor
else:
proj_ch = in_dim // proj_factor
self.w = nn.Parameter(torch.Tensor(in_dim, n_heads, proj_ch // n_heads)
)
nn.init.normal_(self.w, std=0.01)
def forward(self, input_0):
primals_2 = self.w
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
nachiket273/VisTrans
|
GroupPointWise
| false
| 7,309
|
[
"MIT"
] | 1
|
99129b02f275424ebff900189ec2055f26bb9912
|
https://github.com/nachiket273/VisTrans/tree/99129b02f275424ebff900189ec2055f26bb9912
|
Attention
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, embed_dim, hidden_dim=None, out_dim=None, n_head=1,
score_function='scaled_dot_product', dropout=0):
""" Attention Mechanism
:param embed_dim:
:param hidden_dim:
:param out_dim:
:param n_head: num of head (Multi-Head Attention)
:param score_function: scaled_dot_product / mlp (concat) / bi_linear (general dot)
:return (?, q_len, out_dim,)
"""
super(Attention, self).__init__()
if hidden_dim is None:
hidden_dim = embed_dim // n_head
if out_dim is None:
out_dim = embed_dim
self.embed_dim = embed_dim
self.hidden_dim = hidden_dim
self.n_head = n_head
self.score_function = score_function
self.w_kx = nn.Parameter(torch.FloatTensor(n_head, embed_dim,
hidden_dim))
self.w_qx = nn.Parameter(torch.FloatTensor(n_head, embed_dim,
hidden_dim))
self.proj = nn.Linear(n_head * hidden_dim, out_dim)
self.dropout = nn.Dropout(dropout)
if score_function == 'mlp':
self.weight = nn.Parameter(torch.Tensor(hidden_dim * 2))
elif self.score_function == 'bi_linear':
self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
else:
self.register_parameter('weight', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.hidden_dim)
self.w_kx.data.uniform_(-stdv, stdv)
self.w_qx.data.uniform_(-stdv, stdv)
if self.weight is not None:
self.weight.data.uniform_(-stdv, stdv)
def forward(self, k, q):
if len(q.shape) == 2:
q = torch.unsqueeze(q, dim=1)
if len(k.shape) == 2:
k = torch.unsqueeze(k, dim=1)
mb_size = k.shape[0]
k_len = k.shape[1]
q_len = q.shape[1]
kx = k.repeat(self.n_head, 1, 1).view(self.n_head, -1, self.embed_dim)
qx = q.repeat(self.n_head, 1, 1).view(self.n_head, -1, self.embed_dim)
kx = torch.bmm(kx, self.w_kx).view(-1, k_len, self.hidden_dim)
qx = torch.bmm(qx, self.w_qx).view(-1, q_len, self.hidden_dim)
if self.score_function == 'scaled_dot_product':
kt = kx.permute(0, 2, 1)
qkt = torch.bmm(qx, kt)
score = torch.div(qkt, math.sqrt(self.hidden_dim))
elif self.score_function == 'mlp':
kxx = torch.unsqueeze(kx, dim=1).expand(-1, q_len, -1, -1)
qxx = torch.unsqueeze(qx, dim=2).expand(-1, -1, k_len, -1)
kq = torch.cat((kxx, qxx), dim=-1)
score = F.tanh(torch.matmul(kq, self.weight))
elif self.score_function == 'bi_linear':
qw = torch.matmul(qx, self.weight)
kt = kx.permute(0, 2, 1)
score = torch.bmm(qw, kt)
else:
raise RuntimeError('invalid score_function')
score = F.softmax(score, dim=-1)
output = torch.bmm(score, kx)
output = torch.cat(torch.split(output, mb_size, dim=0), dim=-1)
output = self.proj(output)
output = self.dropout(output)
return output
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'embed_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.5
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x2, tmp17, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_2, (1, 16, 4), (64, 4,
1), 0), primals_3, out=buf0)
del primals_3
buf1 = empty_strided_cuda((1, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (1, 16, 4), (64, 4,
1), 0), primals_4, out=buf1)
del primals_4
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf0, (4, 4, 4), (16, 1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = buf2
del buf2
triton_poi_fused__softmax_1[grid(64)](buf3, buf4, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf5 = buf3
del buf3
extern_kernels.bmm(buf4, reinterpret_tensor(buf0, (4, 4, 4), (16, 4,
1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf5, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf6)
del primals_6
return reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(buf0, (4, 4, 4), (16, 1, 4), 0
), buf4, reinterpret_tensor(buf5, (16, 4), (4, 1), 0
), primals_5, reinterpret_tensor(buf1, (4, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(primals_1, (1, 4, 16), (64, 1, 4), 0
), reinterpret_tensor(primals_2, (1, 4, 16), (64, 1, 4), 0)
class AttentionNew(nn.Module):
def __init__(self, embed_dim, hidden_dim=None, out_dim=None, n_head=1,
score_function='scaled_dot_product', dropout=0):
""" Attention Mechanism
:param embed_dim:
:param hidden_dim:
:param out_dim:
:param n_head: num of head (Multi-Head Attention)
:param score_function: scaled_dot_product / mlp (concat) / bi_linear (general dot)
:return (?, q_len, out_dim,)
"""
super(AttentionNew, self).__init__()
if hidden_dim is None:
hidden_dim = embed_dim // n_head
if out_dim is None:
out_dim = embed_dim
self.embed_dim = embed_dim
self.hidden_dim = hidden_dim
self.n_head = n_head
self.score_function = score_function
self.w_kx = nn.Parameter(torch.FloatTensor(n_head, embed_dim,
hidden_dim))
self.w_qx = nn.Parameter(torch.FloatTensor(n_head, embed_dim,
hidden_dim))
self.proj = nn.Linear(n_head * hidden_dim, out_dim)
self.dropout = nn.Dropout(dropout)
if score_function == 'mlp':
self.weight = nn.Parameter(torch.Tensor(hidden_dim * 2))
elif self.score_function == 'bi_linear':
self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
else:
self.register_parameter('weight', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.hidden_dim)
self.w_kx.data.uniform_(-stdv, stdv)
self.w_qx.data.uniform_(-stdv, stdv)
if self.weight is not None:
self.weight.data.uniform_(-stdv, stdv)
def forward(self, input_0, input_1):
primals_3 = self.w_kx
primals_4 = self.w_qx
primals_5 = self.proj.weight
primals_6 = self.proj.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
n-log-n/ABSA-PyTorch
|
Attention
| false
| 7,310
|
[
"MIT"
] | 1
|
27b37e05954940fe37369cc679c080d1d8717362
|
https://github.com/n-log-n/ABSA-PyTorch/tree/27b37e05954940fe37369cc679c080d1d8717362
|
FitnetRegressor
|
import torch
import torch.nn.functional as F
class FitnetRegressor(torch.nn.Module):
def __init__(self, in_feature, out_feature):
super(FitnetRegressor, self).__init__()
self.in_feature = in_feature
self.out_feature = out_feature
self.regressor = torch.nn.Conv2d(in_feature, out_feature, 1, bias=False
)
torch.nn.init.kaiming_normal_(self.regressor.weight, mode='fan_out',
nonlinearity='relu')
self.regressor.weight.data.uniform_(-0.005, 0.005)
def forward(self, feature):
if feature.dim() == 2:
feature = feature.unsqueeze(2).unsqueeze(3)
return F.relu(self.regressor(feature))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_feature': 4, 'out_feature': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1, buf2,
256, XBLOCK=128, num_warps=4, num_stages=1)
return buf1, primals_1, primals_2, buf2
class FitnetRegressorNew(torch.nn.Module):
def __init__(self, in_feature, out_feature):
super(FitnetRegressorNew, self).__init__()
self.in_feature = in_feature
self.out_feature = out_feature
self.regressor = torch.nn.Conv2d(in_feature, out_feature, 1, bias=False
)
torch.nn.init.kaiming_normal_(self.regressor.weight, mode='fan_out',
nonlinearity='relu')
self.regressor.weight.data.uniform_(-0.005, 0.005)
def forward(self, input_0):
primals_2 = self.regressor.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
naver-ai/cgl_fairness
|
FitnetRegressor
| false
| 7,311
|
[
"MIT"
] | 1
|
00d3bec233c9b3e0f88496118abaed8321ca3159
|
https://github.com/naver-ai/cgl_fairness/tree/00d3bec233c9b3e0f88496118abaed8321ca3159
|
ZeroOneTest
|
import torch
from torch import nn
class ZeroOneTest(nn.Module):
def __init__(self):
super(ZeroOneTest, self).__init__()
return
def forward(self, output_p, output_n, prior):
cost = prior * torch.mean((1 - torch.sign(output_p)) / 2)
cost = cost + (1 - prior) * torch.mean((1 + torch.sign(output_n)) / 2)
return cost
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 import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_sign_0(in_ptr0, in_ptr1, in_ptr2,
out_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)
tmp15 = tl.load(in_ptr1 + r0, None)
tmp27 = tl.load(in_ptr2 + r0, None)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp1 < tmp0
tmp3 = tmp2.to(tl.int8)
tmp4 = tmp0 < tmp1
tmp5 = tmp4.to(tl.int8)
tmp6 = tmp3 - tmp5
tmp7 = tmp6.to(tmp0.dtype)
tmp8 = 1.0
tmp9 = tmp8 - tmp7
tmp10 = 0.5
tmp11 = tmp9 * tmp10
tmp12 = tl.broadcast_to(tmp11, [RBLOCK])
tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0))
tmp16 = tmp1 < tmp15
tmp17 = tmp16.to(tl.int8)
tmp18 = tmp15 < tmp1
tmp19 = tmp18.to(tl.int8)
tmp20 = tmp17 - tmp19
tmp21 = tmp20.to(tmp15.dtype)
tmp22 = tmp21 + tmp8
tmp23 = tmp22 * tmp10
tmp24 = tl.broadcast_to(tmp23, [RBLOCK])
tmp26 = triton_helpers.promote_to_tensor(tl.sum(tmp24, 0))
tmp28 = 256.0
tmp29 = tmp14 / tmp28
tmp30 = tmp27 * tmp29
tmp31 = tmp8 - tmp27
tmp32 = tmp26 / tmp28
tmp33 = tmp31 * tmp32
tmp34 = tmp30 + tmp33
tl.store(out_ptr2 + tl.broadcast_to(r0, [RBLOCK]), tmp34, 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)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_mean_mul_rsub_sign_0[grid(1)](arg0_1,
arg2_1, arg1_1, buf2, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf2,
class ZeroOneTestNew(nn.Module):
def __init__(self):
super(ZeroOneTestNew, self).__init__()
return
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]
|
mxuq/Imbalance-PU
|
ZeroOneTest
| false
| 7,312
|
[
"MIT"
] | 1
|
fd4403b05f98ca6bc8156783e8275888d63f6435
|
https://github.com/mxuq/Imbalance-PU/tree/fd4403b05f98ca6bc8156783e8275888d63f6435
|
Landsat2ViirsNet
|
import torch
from torch import nn
from torch.nn import functional as F
class Landsat2ViirsNet(nn.Module):
def __init__(self, latent_dim=64, init_channels=8, kernel_size=4,
image_in_channels=3, image_out_channels=1):
super(Landsat2ViirsNet, self).__init__()
self.enc1 = nn.Conv2d(in_channels=image_in_channels, out_channels=
init_channels, kernel_size=kernel_size, stride=4, padding=1,
dilation=2)
self.enc2 = nn.Conv2d(in_channels=init_channels, out_channels=
init_channels * 2, kernel_size=kernel_size, stride=3, padding=1)
self.enc3 = nn.Conv2d(in_channels=init_channels * 2, out_channels=
init_channels * 4, kernel_size=kernel_size, stride=3, padding=1)
self.enc4 = nn.Conv2d(in_channels=init_channels * 4, out_channels=
64, kernel_size=7, stride=2, padding=0)
self.fc1 = nn.Linear(64, 128)
self.fc_mu = nn.Linear(128, latent_dim)
self.fc_log_var = nn.Linear(128, latent_dim)
self.fc2 = nn.Linear(latent_dim, 64)
self.dec1 = nn.ConvTranspose2d(in_channels=64, out_channels=
init_channels * 4, kernel_size=kernel_size, stride=1, padding=0)
self.dec2 = nn.ConvTranspose2d(in_channels=init_channels * 4,
out_channels=init_channels * 2, kernel_size=kernel_size, stride
=2, padding=0)
self.dec3 = nn.ConvTranspose2d(in_channels=init_channels * 2,
out_channels=image_out_channels, kernel_size=kernel_size + 1,
stride=2, padding=1)
def reparameterize(self, mu, log_var):
"""
:param mu: mean from the encoder's latent space
:param log_var: log variance from the encoder's latent space
"""
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
sample = mu + eps * std
return sample
def forward(self, x):
x = F.leaky_relu(self.enc1(x))
x = F.leaky_relu(self.enc2(x))
x = F.leaky_relu(self.enc3(x))
x = F.leaky_relu(self.enc4(x))
batch, _, _, _ = x.shape
x = F.adaptive_avg_pool2d(x, 1).reshape(batch, -1)
hidden = self.fc1(x)
mu = self.fc_mu(hidden)
log_var = self.fc_log_var(hidden)
z = self.reparameterize(mu, log_var)
z = self.fc2(z)
z = z.view(-1, 64, 1, 1)
x = F.leaky_relu(self.dec1(z))
x = F.leaky_relu(self.dec2(x))
reconstruction = torch.sigmoid(self.dec3(x))
return reconstruction, mu, log_var
def get_inputs():
return [torch.rand([4, 3, 256, 256])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch import device
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 127008
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3969 % 8
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 28224
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 441 % 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 6272
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 49 % 32
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_mean_3(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
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp8 = 1.0
tmp9 = tmp7 / tmp8
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_add_exp_mul_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask)
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp1 * tmp5
tmp7 = tmp0 + tmp6
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_5(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 % 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_convolution_leaky_relu_6(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 100 % 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_sigmoid_7(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1764
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, 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
) = args
args.clear()
assert_size_stride(primals_1, (8, 3, 4, 4), (48, 16, 4, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 3, 256, 256), (196608, 65536, 256, 1))
assert_size_stride(primals_4, (16, 8, 4, 4), (128, 16, 4, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (32, 16, 4, 4), (256, 16, 4, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (64, 32, 7, 7), (1568, 49, 7, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (128, 64), (64, 1))
assert_size_stride(primals_11, (128,), (1,))
assert_size_stride(primals_12, (64, 128), (128, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (64, 128), (128, 1))
assert_size_stride(primals_15, (64,), (1,))
assert_size_stride(primals_16, (64, 64), (64, 1))
assert_size_stride(primals_17, (64,), (1,))
assert_size_stride(primals_18, (64, 32, 4, 4), (512, 16, 4, 1))
assert_size_stride(primals_19, (32,), (1,))
assert_size_stride(primals_20, (32, 16, 4, 4), (256, 16, 4, 1))
assert_size_stride(primals_21, (16,), (1,))
assert_size_stride(primals_22, (16, 1, 5, 5), (25, 25, 5, 1))
assert_size_stride(primals_23, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(4,
4), padding=(1, 1), dilation=(2, 2), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 8, 63, 63), (31752, 3969, 63, 1))
buf1 = empty_strided_cuda((4, 8, 63, 63), (31752, 3969, 63, 1),
torch.bool)
buf2 = empty_strided_cuda((4, 8, 63, 63), (31752, 3969, 63, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_leaky_relu_0[grid(127008)](buf0,
primals_2, buf1, buf2, 127008, XBLOCK=1024, num_warps=4,
num_stages=1)
del buf0
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(3, 3),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 16, 21, 21), (7056, 441, 21, 1))
buf4 = empty_strided_cuda((4, 16, 21, 21), (7056, 441, 21, 1),
torch.bool)
buf5 = empty_strided_cuda((4, 16, 21, 21), (7056, 441, 21, 1),
torch.float32)
triton_poi_fused_convolution_leaky_relu_1[grid(28224)](buf3,
primals_5, buf4, buf5, 28224, XBLOCK=256, num_warps=4, num_stages=1
)
del buf3
del primals_5
buf6 = extern_kernels.convolution(buf5, primals_6, stride=(3, 3),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 32, 7, 7), (1568, 49, 7, 1))
buf7 = empty_strided_cuda((4, 32, 7, 7), (1568, 49, 7, 1), torch.bool)
buf8 = empty_strided_cuda((4, 32, 7, 7), (1568, 49, 7, 1), torch.
float32)
triton_poi_fused_convolution_leaky_relu_2[grid(6272)](buf6,
primals_7, buf7, buf8, 6272, XBLOCK=256, num_warps=4, num_stages=1)
del buf6
del primals_7
buf9 = extern_kernels.convolution(buf8, primals_8, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 64, 1, 1), (64, 1, 1, 1))
buf10 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 1, 1), torch.bool)
buf11 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 256, 256), torch.
float32)
triton_poi_fused_convolution_leaky_relu_mean_3[grid(256)](buf9,
primals_9, buf10, buf11, 256, XBLOCK=256, num_warps=4, num_stages=1
)
del primals_9
buf12 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf11, (4, 64),
(64, 1), 0), reinterpret_tensor(primals_10, (64, 128), (1, 64),
0), alpha=1, beta=1, out=buf12)
del primals_11
buf13 = reinterpret_tensor(buf9, (4, 64), (64, 1), 0)
del buf9
extern_kernels.addmm(primals_13, buf12, reinterpret_tensor(
primals_12, (128, 64), (1, 128), 0), alpha=1, beta=1, out=buf13)
del primals_13
buf14 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
extern_kernels.addmm(primals_15, buf12, reinterpret_tensor(
primals_14, (128, 64), (1, 128), 0), alpha=1, beta=1, out=buf14)
del primals_15
buf15 = torch.ops.aten.randn.default([4, 64], dtype=torch.float32,
device=device(type='cuda', index=0), pin_memory=False)
buf16 = buf15
del buf15
buf17 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
triton_poi_fused_add_exp_mul_4[grid(256)](buf13, buf16, buf14,
buf17, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf18 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
extern_kernels.addmm(primals_17, buf17, reinterpret_tensor(
primals_16, (64, 64), (1, 64), 0), alpha=1, beta=1, out=buf18)
del primals_17
buf19 = extern_kernels.convolution(reinterpret_tensor(buf18, (4, 64,
1, 1), (64, 1, 1, 1), 0), primals_18, stride=(1, 1), padding=(0,
0), dilation=(1, 1), transposed=True, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf19, (4, 32, 4, 4), (512, 16, 4, 1))
buf20 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.bool)
buf21 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.
float32)
triton_poi_fused_convolution_leaky_relu_5[grid(2048)](buf19,
primals_19, buf20, buf21, 2048, XBLOCK=256, num_warps=4,
num_stages=1)
del buf19
del primals_19
buf22 = extern_kernels.convolution(buf21, primals_20, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf22, (4, 16, 10, 10), (1600, 100, 10, 1))
buf23 = empty_strided_cuda((4, 16, 10, 10), (1600, 100, 10, 1),
torch.bool)
buf24 = empty_strided_cuda((4, 16, 10, 10), (1600, 100, 10, 1),
torch.float32)
triton_poi_fused_convolution_leaky_relu_6[grid(6400)](buf22,
primals_21, buf23, buf24, 6400, XBLOCK=256, num_warps=4,
num_stages=1)
del buf22
del primals_21
buf25 = extern_kernels.convolution(buf24, primals_22, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf25, (4, 1, 21, 21), (441, 441, 21, 1))
buf26 = buf25
del buf25
triton_poi_fused_convolution_sigmoid_7[grid(1764)](buf26,
primals_23, 1764, XBLOCK=256, num_warps=4, num_stages=1)
del primals_23
return (buf26, buf13, buf14, primals_1, primals_3, primals_4, primals_6,
primals_8, primals_18, primals_20, primals_22, buf1, buf2, buf4,
buf5, buf7, buf8, buf10, reinterpret_tensor(buf11, (4, 64), (64, 1),
0), buf12, buf14, buf16, buf17, reinterpret_tensor(buf18, (4, 64, 1,
1), (64, 1, 1, 1), 0), buf20, buf21, buf23, buf24, buf26,
primals_16, primals_14, primals_12, primals_10)
class Landsat2ViirsNetNew(nn.Module):
def __init__(self, latent_dim=64, init_channels=8, kernel_size=4,
image_in_channels=3, image_out_channels=1):
super(Landsat2ViirsNetNew, self).__init__()
self.enc1 = nn.Conv2d(in_channels=image_in_channels, out_channels=
init_channels, kernel_size=kernel_size, stride=4, padding=1,
dilation=2)
self.enc2 = nn.Conv2d(in_channels=init_channels, out_channels=
init_channels * 2, kernel_size=kernel_size, stride=3, padding=1)
self.enc3 = nn.Conv2d(in_channels=init_channels * 2, out_channels=
init_channels * 4, kernel_size=kernel_size, stride=3, padding=1)
self.enc4 = nn.Conv2d(in_channels=init_channels * 4, out_channels=
64, kernel_size=7, stride=2, padding=0)
self.fc1 = nn.Linear(64, 128)
self.fc_mu = nn.Linear(128, latent_dim)
self.fc_log_var = nn.Linear(128, latent_dim)
self.fc2 = nn.Linear(latent_dim, 64)
self.dec1 = nn.ConvTranspose2d(in_channels=64, out_channels=
init_channels * 4, kernel_size=kernel_size, stride=1, padding=0)
self.dec2 = nn.ConvTranspose2d(in_channels=init_channels * 4,
out_channels=init_channels * 2, kernel_size=kernel_size, stride
=2, padding=0)
self.dec3 = nn.ConvTranspose2d(in_channels=init_channels * 2,
out_channels=image_out_channels, kernel_size=kernel_size + 1,
stride=2, padding=1)
def reparameterize(self, mu, log_var):
"""
:param mu: mean from the encoder's latent space
:param log_var: log variance from the encoder's latent space
"""
std = torch.exp(0.5 * log_var)
eps = torch.randn_like(std)
sample = mu + eps * std
return sample
def forward(self, input_0):
primals_1 = self.enc1.weight
primals_2 = self.enc1.bias
primals_4 = self.enc2.weight
primals_5 = self.enc2.bias
primals_6 = self.enc3.weight
primals_7 = self.enc3.bias
primals_8 = self.enc4.weight
primals_9 = self.enc4.bias
primals_10 = self.fc1.weight
primals_11 = self.fc1.bias
primals_12 = self.fc_mu.weight
primals_13 = self.fc_mu.bias
primals_14 = self.fc_log_var.weight
primals_15 = self.fc_log_var.bias
primals_16 = self.fc2.weight
primals_17 = self.fc2.bias
primals_18 = self.dec1.weight
primals_19 = self.dec1.bias
primals_20 = self.dec2.weight
primals_21 = self.dec2.bias
primals_22 = self.dec3.weight
primals_23 = self.dec3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23])
return output[0], output[1], output[2]
|
mrmauer/detecting_poverty
|
Landsat2ViirsNet
| false
| 7,313
|
[
"MIT"
] | 1
|
2c8a28295264674f5bfe06ef1fed6dd8b898b8b5
|
https://github.com/mrmauer/detecting_poverty/tree/2c8a28295264674f5bfe06ef1fed6dd8b898b8b5
|
VertexDirectEmbedder
|
import torch
import torch.utils.data
from torch import nn
def normalize_embeddings(embeddings: 'torch.Tensor', epsilon: 'float'=1e-06
) ->torch.Tensor:
"""
Normalize N D-dimensional embedding vectors arranged in a tensor [N, D]
Args:
embeddings (tensor [N, D]): N D-dimensional embedding vectors
epsilon (float): minimum value for a vector norm
Return:
Normalized embeddings (tensor [N, D]), such that L2 vector norms are all equal to 1.
"""
return embeddings / torch.clamp(embeddings.norm(p=None, dim=1, keepdim=
True), min=epsilon)
class VertexDirectEmbedder(nn.Module):
"""
Class responsible for embedding vertices. Vertex embeddings take
the form of a tensor of size [N, D], where
N = number of vertices
D = number of dimensions in the embedding space
"""
def __init__(self, num_vertices: 'int', embed_dim: 'int'):
"""
Initialize embedder, set random embeddings
Args:
num_vertices (int): number of vertices to embed
embed_dim (int): number of dimensions in the embedding space
"""
super(VertexDirectEmbedder, self).__init__()
self.embeddings = nn.Parameter(torch.Tensor(num_vertices, embed_dim))
self.reset_parameters()
@torch.no_grad()
def reset_parameters(self):
"""
Reset embeddings to random values
"""
torch.nn.init.uniform_(self.embeddings, a=-0.5, b=0.5)
def forward(self) ->torch.Tensor:
"""
Produce vertex embeddings, a tensor of shape [N, D] where:
N = number of vertices
D = number of dimensions in the embedding space
Return:
Full vertex embeddings, a tensor of shape [N, D]
"""
return normalize_embeddings(self.embeddings)
@torch.no_grad()
def load(self, fpath: 'str'):
"""
Load data from a file
Args:
fpath (str): file path to load data from
"""
with PathManager.open(fpath, 'rb') as hFile:
data = pickle.load(hFile)
for name in ['embeddings']:
if name in data:
getattr(self, name).copy_(torch.tensor(data[name]).float())
def get_inputs():
return []
def get_init_inputs():
return [[], {'num_vertices': 4, 'embed_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
from torch._inductor.runtime.triton_helpers import libdevice
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_div_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
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-06
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
def call(args):
primals_1, = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_div_linalg_vector_norm_0[grid(16)](primals_1,
buf0, 16, XBLOCK=16, num_warps=1, num_stages=1)
return buf0, primals_1
def normalize_embeddings(embeddings: 'torch.Tensor', epsilon: 'float'=1e-06
) ->torch.Tensor:
"""
Normalize N D-dimensional embedding vectors arranged in a tensor [N, D]
Args:
embeddings (tensor [N, D]): N D-dimensional embedding vectors
epsilon (float): minimum value for a vector norm
Return:
Normalized embeddings (tensor [N, D]), such that L2 vector norms are all equal to 1.
"""
return embeddings / torch.clamp(embeddings.norm(p=None, dim=1, keepdim=
True), min=epsilon)
class VertexDirectEmbedderNew(nn.Module):
"""
Class responsible for embedding vertices. Vertex embeddings take
the form of a tensor of size [N, D], where
N = number of vertices
D = number of dimensions in the embedding space
"""
def __init__(self, num_vertices: 'int', embed_dim: 'int'):
"""
Initialize embedder, set random embeddings
Args:
num_vertices (int): number of vertices to embed
embed_dim (int): number of dimensions in the embedding space
"""
super(VertexDirectEmbedderNew, self).__init__()
self.embeddings = nn.Parameter(torch.Tensor(num_vertices, embed_dim))
self.reset_parameters()
@torch.no_grad()
def reset_parameters(self):
"""
Reset embeddings to random values
"""
torch.nn.init.uniform_(self.embeddings, a=-0.5, b=0.5)
@torch.no_grad()
def load(self, fpath: 'str'):
"""
Load data from a file
Args:
fpath (str): file path to load data from
"""
with PathManager.open(fpath, 'rb') as hFile:
data = pickle.load(hFile)
for name in ['embeddings']:
if name in data:
getattr(self, name).copy_(torch.tensor(data[name]).float())
def forward(self):
primals_1 = self.embeddings
output = call([primals_1])
return output[0]
|
nationaldronesau/detectron2
|
VertexDirectEmbedder
| false
| 7,314
|
[
"Apache-2.0"
] | 1
|
6afaee60eb6e0032b5b2edfbec1179f7e7b7b75f
|
https://github.com/nationaldronesau/detectron2/tree/6afaee60eb6e0032b5b2edfbec1179f7e7b7b75f
|
xTanH
|
import torch
import torch.nn
class xTanH(torch.nn.Module):
def forward(self, x: 'torch.Tensor'):
return x - torch.tanh(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn
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_sub_tanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
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_sub_tanh_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class xTanHNew(torch.nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nayyarv/bayesnets
|
xTanH
| false
| 7,315
|
[
"MIT"
] | 1
|
090abd1a0a91c2b9d6d57a182ee5be1f65a22e11
|
https://github.com/nayyarv/bayesnets/tree/090abd1a0a91c2b9d6d57a182ee5be1f65a22e11
|
LRN
|
import torch
import torch.nn as nn
class LRN(nn.Module):
def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=
False):
super(LRN, self).__init__()
self.ACROSS_CHANNELS = ACROSS_CHANNELS
if self.ACROSS_CHANNELS:
self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1),
stride=1, padding=(int((local_size - 1.0) / 2), 0, 0))
else:
self.average = nn.AvgPool2d(kernel_size=local_size, stride=1,
padding=int((local_size - 1.0) / 2))
self.alpha = alpha
self.beta = beta
def forward(self, x):
if self.ACROSS_CHANNELS:
div = x.pow(2).unsqueeze(1)
div = self.average(div).squeeze(1)
div = div.mul(self.alpha).add(1.0).pow(self.beta)
else:
div = x.pow(2)
div = self.average(div)
div = div.mul(self.alpha).add(1.0).pow(self.beta)
x = x.div(div)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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_avg_pool2d_div_mul_pow_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0 * tmp0
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 + tmp2
tmp6 = 0.75
tmp7 = libdevice.pow(tmp5, tmp6)
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_avg_pool2d_div_mul_pow_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class LRNNew(nn.Module):
def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=
False):
super(LRNNew, self).__init__()
self.ACROSS_CHANNELS = ACROSS_CHANNELS
if self.ACROSS_CHANNELS:
self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1),
stride=1, padding=(int((local_size - 1.0) / 2), 0, 0))
else:
self.average = nn.AvgPool2d(kernel_size=local_size, stride=1,
padding=int((local_size - 1.0) / 2))
self.alpha = alpha
self.beta = beta
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nbswords/Paper-implemention-by-Pytorch
|
LRN
| false
| 7,316
|
[
"MIT"
] | 1
|
429514c4f51c41ec7b3013683fb79ad4b4ab4638
|
https://github.com/nbswords/Paper-implemention-by-Pytorch/tree/429514c4f51c41ec7b3013683fb79ad4b4ab4638
|
FocalLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def focal_loss(input_values, gamma=10):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return loss.mean()
class FocalLoss(nn.Module):
def __init__(self, weight=None, gamma=0.5):
super(FocalLoss, self).__init__()
assert gamma >= 0
self.gamma = gamma
self.weight = weight
def forward(self, input, target):
return focal_loss(F.cross_entropy(input, target, reduction='none',
weight=self.weight), self.gamma)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_exp_mean_mul_neg_pow_rsub_sum_1(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp13 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp20 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp24 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp1 = tl_math.exp(tmp0)
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 + tmp3
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp4 + tmp6
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp0 - tmp11
tmp14 = tmp12 * tmp13
tmp15 = tmp2 - tmp11
tmp17 = tmp15 * tmp16
tmp18 = tmp14 + tmp17
tmp19 = tmp5 - tmp11
tmp21 = tmp19 * tmp20
tmp22 = tmp18 + tmp21
tmp23 = tmp8 - tmp11
tmp25 = tmp23 * tmp24
tmp26 = tmp22 + tmp25
tmp27 = -tmp26
tmp28 = -tmp27
tmp29 = tl_math.exp(tmp28)
tmp30 = 1.0
tmp31 = tmp30 - tmp29
tmp32 = libdevice.sqrt(tmp31)
tmp33 = tmp32 * tmp27
tmp34 = tl.broadcast_to(tmp33, [XBLOCK, RBLOCK])
tmp36 = tl.sum(tmp34, 1)[:, None]
tmp37 = 64.0
tmp38 = tmp36 / tmp37
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp38, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused__log_softmax_exp_mean_mul_neg_pow_rsub_sum_1[grid(1)](
buf3, buf0, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf3,
def focal_loss(input_values, gamma=10):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return loss.mean()
class FocalLossNew(nn.Module):
def __init__(self, weight=None, gamma=0.5):
super(FocalLossNew, self).__init__()
assert gamma >= 0
self.gamma = gamma
self.weight = weight
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
naver-ai/cgl_fairness
|
FocalLoss
| false
| 7,317
|
[
"MIT"
] | 1
|
00d3bec233c9b3e0f88496118abaed8321ca3159
|
https://github.com/naver-ai/cgl_fairness/tree/00d3bec233c9b3e0f88496118abaed8321ca3159
|
MultiHeadSelfAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.distributed
import torch.nn.functional as F
import torch.nn as nn
class MultiHeadSelfAttention(nn.Module):
def __init__(self, config):
super(MultiHeadSelfAttention, self).__init__()
self.query = nn.Linear(config.hidden_size, config.hidden_size)
self.key = nn.Linear(config.hidden_size, config.hidden_size)
self.value = nn.Linear(config.hidden_size, config.hidden_size)
self.attn_drop = nn.Dropout(config.attn_pdrop)
self.resid_drop = nn.Dropout(config.resid_pdrop)
self.proj = nn.Linear(config.hidden_size, config.hidden_size)
assert config.hidden_size % config.n_heads == 0, 'Hidden size should be multiple of n_heads'
self.n_heads = config.n_heads
self.head_size = config.hidden_size // self.n_heads
def forward(self, x):
batch_size, seq_length, hidden_size = x.size()
q = self.query(x).view(batch_size, seq_length, self.n_heads, self.
head_size).transpose(1, 2)
k = self.key(x).view(batch_size, seq_length, self.head_size, self.
n_heads).transpose(1, 3)
v = self.value(x).view(batch_size, seq_length, self.n_heads, self.
head_size).transpose(1, 2)
attention_mask = torch.full((seq_length, seq_length), -float('inf'),
device=x.device, dtype=x.dtype)
attention_mask = torch.triu(attention_mask, diagonal=1)
attention_score = torch.matmul(q, k) / math.sqrt(self.head_size
) + attention_mask
attention_score = F.softmax(attention_score, dim=-1)
attention_score = self.attn_drop(attention_score)
score = torch.matmul(attention_score, v)
score = score.transpose(1, 2).contiguous().view(batch_size,
seq_length, hidden_size)
score = self.proj(score)
score = self.resid_drop(score)
return score
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, attn_pdrop=0.5,
resid_pdrop=0.5, 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 math as tl_math
import torch.distributed
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_add_div_full_triu_1(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + 4 * x2, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr0 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp24 = tl.load(in_ptr0 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = -1 * x0
tmp4 = tl.full([1], 1, tl.int64)
tmp5 = tmp3 >= tmp4
tmp6 = float('-inf')
tmp7 = 0.0
tmp8 = tl.where(tmp5, tmp6, tmp7)
tmp9 = tmp2 + tmp8
tmp11 = tmp10 * tmp1
tmp12 = 1 + -1 * x0
tmp13 = tmp12 >= tmp4
tmp14 = tl.where(tmp13, tmp6, tmp7)
tmp15 = tmp11 + tmp14
tmp16 = triton_helpers.maximum(tmp9, tmp15)
tmp18 = tmp17 * tmp1
tmp19 = 2 + -1 * x0
tmp20 = tmp19 >= tmp4
tmp21 = tl.where(tmp20, tmp6, tmp7)
tmp22 = tmp18 + tmp21
tmp23 = triton_helpers.maximum(tmp16, tmp22)
tmp25 = tmp24 * tmp1
tmp26 = 3 + -1 * x0
tmp27 = tmp26 >= tmp4
tmp28 = tl.where(tmp27, tmp6, tmp7)
tmp29 = tmp25 + tmp28
tmp30 = triton_helpers.maximum(tmp23, tmp29)
tmp31 = tmp9 - tmp30
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp15 - tmp30
tmp34 = tl_math.exp(tmp33)
tmp35 = tmp32 + tmp34
tmp36 = tmp22 - tmp30
tmp37 = tl_math.exp(tmp36)
tmp38 = tmp35 + tmp37
tmp39 = tmp29 - tmp30
tmp40 = tl_math.exp(tmp39)
tmp41 = tmp38 + tmp40
tl.store(out_ptr0 + x2, tmp30, xmask)
tl.store(out_ptr1 + x2, tmp41, xmask)
@triton.jit
def triton_poi_fused__softmax_add_div_full_triu_2(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x1 = xindex // 4 % 4
x4 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp10 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = x0 + -1 * x1
tmp4 = tl.full([1], 1, tl.int64)
tmp5 = tmp3 >= tmp4
tmp6 = float('-inf')
tmp7 = 0.0
tmp8 = tl.where(tmp5, tmp6, tmp7)
tmp9 = tmp2 + tmp8
tmp11 = tmp9 - tmp10
tmp12 = tl_math.exp(tmp11)
tmp14 = tmp12 / tmp13
tl.store(in_out_ptr0 + x3, tmp14, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_3, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf1
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_add_div_full_triu_1[grid(64)](buf5, buf6,
buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused__softmax_add_div_full_triu_2[grid(256)](buf8, buf6,
buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf7
triton_poi_fused_clone_0[grid(16, 4)](buf2, primals_7, buf9, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf10 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), out=buf10)
buf11 = reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf6
triton_poi_fused_clone_3[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.addmm(primals_9, reinterpret_tensor(buf11, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf12)
del primals_9
return reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf8, reinterpret_tensor(buf11, (16, 4), (4, 1), 0
), primals_8, reinterpret_tensor(buf9, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 4), 0)
class MultiHeadSelfAttentionNew(nn.Module):
def __init__(self, config):
super(MultiHeadSelfAttentionNew, self).__init__()
self.query = nn.Linear(config.hidden_size, config.hidden_size)
self.key = nn.Linear(config.hidden_size, config.hidden_size)
self.value = nn.Linear(config.hidden_size, config.hidden_size)
self.attn_drop = nn.Dropout(config.attn_pdrop)
self.resid_drop = nn.Dropout(config.resid_pdrop)
self.proj = nn.Linear(config.hidden_size, config.hidden_size)
assert config.hidden_size % config.n_heads == 0, 'Hidden size should be multiple of n_heads'
self.n_heads = config.n_heads
self.head_size = config.hidden_size // self.n_heads
def forward(self, input_0):
primals_2 = self.query.weight
primals_3 = self.query.bias
primals_4 = self.key.weight
primals_5 = self.key.bias
primals_6 = self.value.weight
primals_7 = self.value.bias
primals_8 = self.proj.weight
primals_9 = self.proj.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]
|
myoons/image-gpt-pytorch
|
MultiHeadSelfAttention
| false
| 7,318
|
[
"Apache-2.0"
] | 1
|
d05081250d01ce208796dfb246ea1c9a093237c5
|
https://github.com/myoons/image-gpt-pytorch/tree/d05081250d01ce208796dfb246ea1c9a093237c5
|
Matcher
|
import math
import torch
import torch.nn as nn
class Matcher(nn.Module):
"""
Matching between a pair of nodes to conduct link prediction.
Use multi-head attention as matching model.
"""
def __init__(self, n_hid):
super(Matcher, self).__init__()
self.left_linear = nn.Linear(n_hid, n_hid)
self.right_linear = nn.Linear(n_hid, n_hid)
self.sqrt_hd = math.sqrt(n_hid)
self.cache = None
def forward(self, x, y, infer=False, pair=False):
ty = self.right_linear(y)
if infer:
"""
During testing, we will consider millions or even billions of nodes as candidates (x).
It's not possible to calculate them again for different query (y)
Since the model is fixed, we propose to cache them, and dirrectly use the results.
"""
if self.cache is not None:
tx = self.cache
else:
tx = self.left_linear(x)
self.cache = tx
else:
tx = self.left_linear(x)
if pair:
res = (tx * ty).sum(dim=-1)
else:
res = torch.matmul(tx, ty.transpose(0, 1))
return res / self.sqrt_hd
def __repr__(self):
return '{}(n_hid={})'.format(self.__class__.__name__, self.n_hid)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_hid': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex % 16
x0 = xindex % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x4 + 16 * x3 + 64 * x2), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x5, tmp2, xmask)
@triton.jit
def triton_poi_fused_div_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (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)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf0, primals_2, buf2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf3 = reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0), out=buf3)
buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused_div_1[grid(256)](buf4, 256, XBLOCK=256, num_warps=
4, num_stages=1)
return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf2, (16, 4, 4), (16, 1, 4), 0)
class MatcherNew(nn.Module):
"""
Matching between a pair of nodes to conduct link prediction.
Use multi-head attention as matching model.
"""
def __init__(self, n_hid):
super(MatcherNew, self).__init__()
self.left_linear = nn.Linear(n_hid, n_hid)
self.right_linear = nn.Linear(n_hid, n_hid)
self.sqrt_hd = math.sqrt(n_hid)
self.cache = None
def __repr__(self):
return '{}(n_hid={})'.format(self.__class__.__name__, self.n_hid)
def forward(self, input_0, input_1):
primals_1 = self.left_linear.weight
primals_2 = self.left_linear.bias
primals_4 = self.right_linear.weight
primals_5 = self.right_linear.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]
|
nchungvh/pyhgt
|
Matcher
| false
| 7,319
|
[
"MIT"
] | 1
|
3cb08ea856ca02aaf1664aa7486024a8742c7567
|
https://github.com/nchungvh/pyhgt/tree/3cb08ea856ca02aaf1664aa7486024a8742c7567
|
Q
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Q(nn.Module):
"""
Simple fully connected Q function. Also used for skip-Q when concatenating behaviour action and state together.
Used for simpler environments such as mountain-car or lunar-lander.
"""
def __init__(self, state_dim, action_dim, non_linearity=F.relu,
hidden_dim=50):
super(Q, self).__init__()
self.fc1 = nn.Linear(state_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(hidden_dim, action_dim)
self._non_linearity = non_linearity
def forward(self, x):
x = self._non_linearity(self.fc1(x))
x = self._non_linearity(self.fc2(x))
return self.fc3(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4, 'action_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 3200
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)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (50, 4), (4, 1))
assert_size_stride(primals_2, (50,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (50, 50), (50, 1))
assert_size_stride(primals_5, (50,), (1,))
assert_size_stride(primals_6, (4, 50), (50, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 50), (50, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 50), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 50), (800, 200, 50, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 50), (800, 200, 50, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(3200)](buf1,
primals_2, buf6, 3200, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 50), (50, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 50), (50, 1), 0),
reinterpret_tensor(primals_4, (50, 50), (1, 50), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 50), (800, 200, 50, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 50), (800, 200, 50, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(3200)](buf3,
primals_5, buf5, 3200, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 50),
(50, 1), 0), reinterpret_tensor(primals_6, (50, 4), (1, 50), 0),
alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 50), (50, 1), 0), reinterpret_tensor(
buf3, (64, 50), (50, 1), 0), primals_6, buf5, primals_4, buf6
class QNew(nn.Module):
"""
Simple fully connected Q function. Also used for skip-Q when concatenating behaviour action and state together.
Used for simpler environments such as mountain-car or lunar-lander.
"""
def __init__(self, state_dim, action_dim, non_linearity=F.relu,
hidden_dim=50):
super(QNew, self).__init__()
self.fc1 = nn.Linear(state_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, hidden_dim)
self.fc3 = nn.Linear(hidden_dim, action_dim)
self._non_linearity = non_linearity
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]
|
ndangtt/LeadingOnesDAC
|
Q
| false
| 7,320
|
[
"Apache-2.0"
] | 1
|
953747d8702f179851d7973c65779a1f830e03a1
|
https://github.com/ndangtt/LeadingOnesDAC/tree/953747d8702f179851d7973c65779a1f830e03a1
|
DropoutModel8x8
|
import torch
import torch.nn as nn
import torch.nn.functional as func
class DropoutModel8x8(nn.Module):
def __init__(self, channel):
"""
Define useful layers
Argument:
channel: number of channel, or depth or number of different sprite types
"""
super(DropoutModel8x8, self).__init__()
self.dropout_1 = nn.Dropout2d(0.3)
self.conv_1 = nn.Conv2d(channel, channel * 2, kernel_size=3, stride=1)
self.conv_2 = nn.Conv2d(channel * 2, channel * 4, kernel_size=3,
stride=1)
self.conv_3 = nn.Conv2d(channel * 4, channel * 8, kernel_size=3,
stride=1)
self.conv_middle = nn.Conv2d(channel * 8, channel * 8, kernel_size=
3, stride=1, padding=1)
self.conv_T1 = nn.ConvTranspose2d(channel * 8, channel * 4,
kernel_size=3, stride=1)
self.conv_T2 = nn.ConvTranspose2d(channel * 4, channel * 2,
kernel_size=3, stride=1)
self.conv_T3 = nn.ConvTranspose2d(channel * 2, channel, kernel_size
=3, stride=1)
def forward(self, x):
if self.training:
x = self.dropout_1(x)
x = func.relu(self.conv_1(x))
x = func.relu(self.conv_2(x))
x = func.relu(self.conv_3(x))
x = self.conv_middle(x)
x = self.conv_T1(x)
x = self.conv_T2(x)
x = torch.sigmoid(self.conv_T3(x))
return x
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'channel': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 123008
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3844 % 8
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 230400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3600 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 430592
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3364 % 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_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 430592
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3364 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 230400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3600 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 123008
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3844 % 8
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_sigmoid_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 4
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x3, tmp3, None)
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, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4, 64, 64), (16384, 4096, 64, 1))
assert_size_stride(primals_4, (16, 8, 3, 3), (72, 9, 3, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (32, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (32, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (16, 8, 3, 3), (72, 9, 3, 1))
assert_size_stride(primals_13, (8,), (1,))
assert_size_stride(primals_14, (8, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_15, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 8, 62, 62), (30752, 3844, 62, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(123008)](buf1, primals_2,
123008, 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, 16, 60, 60), (57600, 3600, 60, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(230400)](buf3, primals_5,
230400, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 58, 58), (107648, 3364, 58, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(430592)](buf5, primals_7,
430592, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 32, 58, 58), (107648, 3364, 58, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_3[grid(430592)](buf7, primals_9,
430592, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 16, 60, 60), (57600, 3600, 60, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_4[grid(230400)](buf9, primals_11,
230400, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_11
buf10 = extern_kernels.convolution(buf9, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 8, 62, 62), (30752, 3844, 62, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_5[grid(123008)](buf11, primals_13,
123008, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf12 = extern_kernels.convolution(buf11, primals_14, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 4, 64, 64), (16384, 4096, 64, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_sigmoid_6[grid(65536)](buf13,
primals_15, 65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_15
return (buf13, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, buf1, buf3, buf5, buf7, buf9,
buf11, buf13)
class DropoutModel8x8New(nn.Module):
def __init__(self, channel):
"""
Define useful layers
Argument:
channel: number of channel, or depth or number of different sprite types
"""
super(DropoutModel8x8New, self).__init__()
self.dropout_1 = nn.Dropout2d(0.3)
self.conv_1 = nn.Conv2d(channel, channel * 2, kernel_size=3, stride=1)
self.conv_2 = nn.Conv2d(channel * 2, channel * 4, kernel_size=3,
stride=1)
self.conv_3 = nn.Conv2d(channel * 4, channel * 8, kernel_size=3,
stride=1)
self.conv_middle = nn.Conv2d(channel * 8, channel * 8, kernel_size=
3, stride=1, padding=1)
self.conv_T1 = nn.ConvTranspose2d(channel * 8, channel * 4,
kernel_size=3, stride=1)
self.conv_T2 = nn.ConvTranspose2d(channel * 4, channel * 2,
kernel_size=3, stride=1)
self.conv_T3 = nn.ConvTranspose2d(channel * 2, channel, kernel_size
=3, stride=1)
def forward(self, input_0):
primals_1 = self.conv_1.weight
primals_2 = self.conv_1.bias
primals_4 = self.conv_2.weight
primals_5 = self.conv_2.bias
primals_6 = self.conv_3.weight
primals_7 = self.conv_3.bias
primals_8 = self.conv_middle.weight
primals_9 = self.conv_middle.bias
primals_10 = self.conv_T1.weight
primals_11 = self.conv_T1.bias
primals_12 = self.conv_T2.weight
primals_13 = self.conv_T2.bias
primals_14 = self.conv_T3.weight
primals_15 = self.conv_T3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15])
return output[0]
|
mwxely/Cross-domain-PCGML-Level-Generator
|
DropoutModel8x8
| false
| 7,321
|
[
"MIT"
] | 1
|
baa5d214d6cf22272d144aa6c444a778ac202afe
|
https://github.com/mwxely/Cross-domain-PCGML-Level-Generator/tree/baa5d214d6cf22272d144aa6c444a778ac202afe
|
Attn
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy import sqrt
class Attn(nn.Module):
def __init__(self, hidden_size, batch_first=True):
super(Attn, self).__init__()
self.hidden_size = hidden_size
self.batch_first = batch_first
self.weights = nn.Parameter(torch.Tensor(hidden_size, 1))
stdv = 1.0 / sqrt(self.hidden_size)
for weight in self.weights:
nn.init.uniform_(weight, -stdv, stdv)
def forward(self, x):
if self.batch_first:
batch_size, _seq_size = x.size()[:2]
else:
_seq_size, batch_size = x.size()[:2]
weights = torch.bmm(x, self.weights.unsqueeze(0).repeat(batch_size,
1, 1))
attentions = torch.softmax(F.relu(weights.squeeze()), dim=-1)
weighted_input = torch.mul(x, attentions.unsqueeze(-1).expand_as(x))
return weighted_input, attentions
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from numpy import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_repeat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused__softmax_relu_threshold_backward_1(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp1, tmp3)
tmp6 = triton_helpers.maximum(tmp1, tmp5)
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = triton_helpers.maximum(tmp1, tmp8)
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = triton_helpers.maximum(tmp1, tmp11)
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tl_math.exp(tmp14)
tmp16 = 0.0
tmp17 = tmp2 <= tmp16
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp17, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_3(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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 1), (1, 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_repeat_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(primals_1, buf0, out=buf1)
buf2 = reinterpret_tensor(buf0, (4, 4), (4, 1), 0)
del buf0
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused__softmax_relu_threshold_backward_1[grid(16)](buf1,
buf2, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4), (4, 1), 0)
del buf1
triton_poi_fused__softmax_2[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf2
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_mul_3[grid(64)](primals_1, buf3, buf4, 64, XBLOCK=
64, num_warps=1, num_stages=1)
return buf4, buf3, primals_1, buf3, buf5
class AttnNew(nn.Module):
def __init__(self, hidden_size, batch_first=True):
super(AttnNew, self).__init__()
self.hidden_size = hidden_size
self.batch_first = batch_first
self.weights = nn.Parameter(torch.Tensor(hidden_size, 1))
stdv = 1.0 / sqrt(self.hidden_size)
for weight in self.weights:
nn.init.uniform_(weight, -stdv, stdv)
def forward(self, input_0):
primals_2 = self.weights
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0], output[1]
|
nauhc/biLSTM-many-to-one
|
Attn
| false
| 7,322
|
[
"MIT"
] | 1
|
14dab1c75b395c88bdddfe751461af7dc30e1166
|
https://github.com/nauhc/biLSTM-many-to-one/tree/14dab1c75b395c88bdddfe751461af7dc30e1166
|
VAE
|
import torch
from torch import nn
import torch.nn.functional as F
class VAE(nn.Module):
def __init__(self):
super().__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 F.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
from torch import nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_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=128, 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().__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 F.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]
|
nd1511/argus
|
VAE
| false
| 7,323
|
[
"MIT"
] | 1
|
00aaed41ac1321d669ac7060f4d21b24cc3456f0
|
https://github.com/nd1511/argus/tree/00aaed41ac1321d669ac7060f4d21b24cc3456f0
|
GCN
|
from torch.nn import Module
import math
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import torch.nn as nn
import torch.nn.functional as F
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, topology, bsize, i, n_class, bias=True):
super(GraphConvolution, self).__init__()
if i == 0:
self.in_features = in_features
else:
self.in_features = topology[i - 1] * bsize
if i == len(topology):
self.out_features = n_class
else:
self.out_features = topology[i] * bsize
self.weight = Parameter(torch.FloatTensor(self.in_features, self.
out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(self.out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GCN(nn.Module):
def __init__(self, infeat, bsize, topology, n_class, dropout):
super(GCN, self).__init__()
self.num_layers = len(topology)
self.layers = nn.ModuleDict({'gc{}'.format(i): GraphConvolution(
infeat, topology, bsize, i, n_class) for i in range(self.
num_layers)})
self.outlayer = GraphConvolution(infeat, topology, bsize, self.
num_layers, n_class)
self.dropout = dropout
def forward(self, x, adj, ls=False):
for i in range(self.num_layers):
x = self.layers['gc' + str(i)](x, adj)
x = F.relu(x)
if i == 0:
x = F.dropout(x, self.dropout, training=self.training)
if ls:
pred = x
else:
x = self.outlayer(x, adj)
pred = F.log_softmax(x, dim=1)
return pred
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'infeat': 4, 'bsize': 4, 'topology': [4, 4], 'n_class': 4,
'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn import Module
import math
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
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_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 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__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 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) = args
args.clear()
assert_size_stride(primals_1, (4, 16), (16, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (16, 16), (16, 1))
assert_size_stride(primals_6, (16,), (1,))
assert_size_stride(primals_7, (16, 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, 16), (16, 1), torch.float32)
extern_kernels.mm(primals_2, primals_1, out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(primals_3, buf0, out=buf1)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_add_relu_0[grid(64)](buf2, primals_4, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del primals_4
buf3 = buf0
del buf0
extern_kernels.mm(buf2, primals_5, out=buf3)
buf4 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(primals_3, buf3, out=buf4)
del buf3
buf5 = buf4
del buf4
triton_poi_fused_add_relu_0[grid(64)](buf5, primals_6, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del primals_6
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf5, primals_7, out=buf6)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_8, primals_3, buf6, alpha=1, beta=1,
out=buf7)
del primals_8
buf8 = buf6
del buf6
triton_poi_fused__log_softmax_1[grid(16)](buf7, buf8, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused__log_softmax_2[grid(16)](buf8, buf9, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf8
return buf9, buf2, buf5, buf9, reinterpret_tensor(primals_3, (4, 4), (1,
4), 0), reinterpret_tensor(primals_7, (4, 16), (1, 4), 0
), reinterpret_tensor(primals_5, (16, 16), (1, 16), 0
), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0)
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, topology, bsize, i, n_class, bias=True):
super(GraphConvolution, self).__init__()
if i == 0:
self.in_features = in_features
else:
self.in_features = topology[i - 1] * bsize
if i == len(topology):
self.out_features = n_class
else:
self.out_features = topology[i] * bsize
self.weight = Parameter(torch.FloatTensor(self.in_features, self.
out_features))
if bias:
self.bias = Parameter(torch.FloatTensor(self.out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GCNNew(nn.Module):
def __init__(self, infeat, bsize, topology, n_class, dropout):
super(GCNNew, self).__init__()
self.num_layers = len(topology)
self.layers = nn.ModuleDict({'gc{}'.format(i): GraphConvolution(
infeat, topology, bsize, i, n_class) for i in range(self.
num_layers)})
self.outlayer = GraphConvolution(infeat, topology, bsize, self.
num_layers, n_class)
self.dropout = dropout
def forward(self, input_0, input_1):
primals_1 = self.layers.gc0.weight
primals_4 = self.layers.gc0.bias
primals_5 = self.layers.gc1.weight
primals_6 = self.layers.gc1.bias
primals_7 = self.outlayer.weight
primals_8 = self.outlayer.bias
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
negarhdr/PGCN
|
GCN
| false
| 7,324
|
[
"MIT"
] | 1
|
5143049afcfadc5ab0173e6083ebbb4fd8c8903d
|
https://github.com/negarhdr/PGCN/tree/5143049afcfadc5ab0173e6083ebbb4fd8c8903d
|
Perceptron
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Perceptron(nn.Module):
"""Implements a 1-layer perceptron."""
def __init__(self, input_dimension, hidden_dimension, output_dimension):
super(Perceptron, self).__init__()
self._layer1 = nn.Linear(input_dimension, hidden_dimension)
self._layer2 = nn.Linear(hidden_dimension, output_dimension, bias=False
)
def forward(self, inp):
return F.sigmoid(self._layer2(F.relu(self._layer1(inp), inplace=True)))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dimension': 4, 'hidden_dimension': 4,
'output_dimension': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + x4, tmp6, xmask)
@triton.jit
def triton_poi_fused_view_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * (x1 % 4 // 4) + 64 * ((4 *
(x1 // 4 % 4) + x1 % 4) // 16)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_sigmoid_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
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
triton_poi_fused_sigmoid_2[grid(256)](buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2, buf4, primals_4, buf5
class PerceptronNew(nn.Module):
"""Implements a 1-layer perceptron."""
def __init__(self, input_dimension, hidden_dimension, output_dimension):
super(PerceptronNew, self).__init__()
self._layer1 = nn.Linear(input_dimension, hidden_dimension)
self._layer2 = nn.Linear(hidden_dimension, output_dimension, bias=False
)
def forward(self, input_0):
primals_1 = self._layer1.weight
primals_2 = self._layer1.bias
primals_4 = self._layer2.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
negotiatorvivian/SAT-Solver
|
Perceptron
| false
| 7,325
|
[
"MIT"
] | 1
|
acbf375ce73103e945aee3e2a225126684a19076
|
https://github.com/negotiatorvivian/SAT-Solver/tree/acbf375ce73103e945aee3e2a225126684a19076
|
PerceptronTanh
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class PerceptronTanh(nn.Module):
"""Implements a 1-layer perceptron with Tanh activaton."""
def __init__(self, input_dimension, hidden_dimension, output_dimension):
super(PerceptronTanh, self).__init__()
self._layer1 = nn.Linear(input_dimension, hidden_dimension)
self._layer2 = nn.Linear(hidden_dimension, output_dimension, bias=False
)
def forward(self, inp):
return F.tanh(self._layer2(F.relu(self._layer1(inp), inplace=True)))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dimension': 4, 'hidden_dimension': 4,
'output_dimension': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + x4, tmp6, xmask)
@triton.jit
def triton_poi_fused_view_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * (x1 % 4 // 4) + 64 * ((4 *
(x1 // 4 % 4) + x1 % 4) // 16)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_tanh_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
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
triton_poi_fused_tanh_2[grid(256)](buf4, 256, XBLOCK=128, num_warps
=4, num_stages=1)
return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2, buf4, primals_4, buf5
class PerceptronTanhNew(nn.Module):
"""Implements a 1-layer perceptron with Tanh activaton."""
def __init__(self, input_dimension, hidden_dimension, output_dimension):
super(PerceptronTanhNew, self).__init__()
self._layer1 = nn.Linear(input_dimension, hidden_dimension)
self._layer2 = nn.Linear(hidden_dimension, output_dimension, bias=False
)
def forward(self, input_0):
primals_1 = self._layer1.weight
primals_2 = self._layer1.bias
primals_4 = self._layer2.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
negotiatorvivian/SAT-Solver
|
PerceptronTanh
| false
| 7,326
|
[
"MIT"
] | 1
|
acbf375ce73103e945aee3e2a225126684a19076
|
https://github.com/negotiatorvivian/SAT-Solver/tree/acbf375ce73103e945aee3e2a225126684a19076
|
ConfidentMSELoss
|
from torch.nn import Module
import torch
class ConfidentMSELoss(Module):
def __init__(self, threshold=0.96):
self.threshold = threshold
super().__init__()
def forward(self, input, target):
n = input.size(0)
conf_mask = torch.gt(target, self.threshold).float()
input_flat = input.view(n, -1)
target_flat = target.view(n, -1)
conf_mask_flat = conf_mask.view(n, -1)
diff = (input_flat - target_flat) ** 2
diff_conf = diff * conf_mask_flat
loss = diff_conf.mean()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch.nn import Module
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mean_mul_pow_sub_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = 0.96
tmp5 = tmp1 > tmp4
tmp6 = tmp5.to(tl.float32)
tmp7 = tmp3 * tmp6
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tmp11 = 256.0
tmp12 = tmp10 / tmp11
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp12, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mean_mul_pow_sub_0[grid(1)](buf1, arg0_1, arg1_1,
1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class ConfidentMSELossNew(Module):
def __init__(self, threshold=0.96):
self.threshold = threshold
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
neuropoly/medicaltorch
|
ConfidentMSELoss
| false
| 7,327
|
[
"Apache-2.0"
] | 1
|
ac129fe894cb1906285dfe380ba4f0aa3bdec787
|
https://github.com/neuropoly/medicaltorch/tree/ac129fe894cb1906285dfe380ba4f0aa3bdec787
|
Conv2
|
import math
import torch
import torch.nn as nn
class Conv2(nn.Module):
""" A convolution layer with the stride of 2.
Input:
x: (N, 2L+2, in_channels) numeric tensor
global_cond: (N, global_cond_channels) numeric tensor
Output:
y: (N, L, out_channels) numeric tensor
"""
def __init__(self, in_channels, out_channels, global_cond_channels):
super().__init__()
ksz = 4
self.out_channels = out_channels
if 0 < global_cond_channels:
self.w_cond = nn.Linear(global_cond_channels, 2 * out_channels,
bias=False)
self.conv_wide = nn.Conv1d(in_channels, 2 * out_channels, ksz, stride=2
)
wsize = 2.967 / math.sqrt(ksz * in_channels)
self.conv_wide.weight.data.uniform_(-wsize, wsize)
self.conv_wide.bias.data.zero_()
def forward(self, x, global_cond):
x1 = self.conv_wide(x.transpose(1, 2)).transpose(1, 2)
if global_cond is not None:
x2 = self.w_cond(global_cond).unsqueeze(1).expand(-1, x1.size(1
), -1)
else:
x2 = torch.zeros_like(x1)
a, b = (x1 + x2).split(self.out_channels, dim=2)
return torch.sigmoid(a) * torch.tanh(b)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4,
'global_cond_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_mul_sigmoid_tanh_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
out_ptr1, out_ptr2, 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 + 8 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 8 * x1), xmask)
tmp6 = tl.load(in_ptr0 + (4 + x0 + 8 * x1), xmask)
tmp7 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + (4 + x0 + 8 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = libdevice.tanh(tmp10)
tmp12 = tmp5 * tmp11
tl.store(out_ptr0 + x2, tmp5, xmask)
tl.store(out_ptr1 + x2, tmp11, xmask)
tl.store(out_ptr2 + x2, tmp12, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (8, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (8,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (8, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(2,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 8, 1), (8, 1, 1))
del buf0
buf2 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(primals_4, reinterpret_tensor(primals_5, (4, 8),
(1, 4), 0), out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_tanh_1[grid(16)](buf1, primals_3, buf2,
buf3, buf4, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf1
del buf2
del primals_3
return buf5, primals_2, primals_4, reinterpret_tensor(primals_1, (4, 4,
4), (16, 1, 4), 0), buf3, buf4
class Conv2New(nn.Module):
""" A convolution layer with the stride of 2.
Input:
x: (N, 2L+2, in_channels) numeric tensor
global_cond: (N, global_cond_channels) numeric tensor
Output:
y: (N, L, out_channels) numeric tensor
"""
def __init__(self, in_channels, out_channels, global_cond_channels):
super().__init__()
ksz = 4
self.out_channels = out_channels
if 0 < global_cond_channels:
self.w_cond = nn.Linear(global_cond_channels, 2 * out_channels,
bias=False)
self.conv_wide = nn.Conv1d(in_channels, 2 * out_channels, ksz, stride=2
)
wsize = 2.967 / math.sqrt(ksz * in_channels)
self.conv_wide.weight.data.uniform_(-wsize, wsize)
self.conv_wide.bias.data.zero_()
def forward(self, input_0, input_1):
primals_5 = self.w_cond.weight
primals_2 = self.conv_wide.weight
primals_3 = self.conv_wide.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
neverix/voice-conv
|
Conv2
| false
| 7,328
|
[
"MIT"
] | 1
|
6df0053a59aa26318bdbc096dd312ecc55596ac0
|
https://github.com/neverix/voice-conv/tree/6df0053a59aa26318bdbc096dd312ecc55596ac0
|
Attention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
"""
Applies an attention mechanism on the query features from the decoder.
.. math::
\\begin{array}{ll}
x = context*query \\\\
attn_scores = exp(x_i) / sum_j exp(x_j) \\\\
attn_out = attn * context
\\end{array}
Args:
dim(int): The number of expected features in the query
Inputs: query, context
- **query** (batch, query_len, dimensions): tensor containing the query features from the decoder.
- **context** (batch, input_len, dimensions): tensor containing features of the encoded input sequence.
Outputs: query, attn
- **query** (batch, query_len, dimensions): tensor containing the attended query features from the decoder.
- **attn** (batch, query_len, input_len): tensor containing attention weights.
Attributes:
mask (torch.Tensor, optional): applies a :math:`-inf` to the indices specified in the `Tensor`.
"""
def __init__(self):
super(Attention, self).__init__()
self.mask = None
def set_mask(self, mask):
"""
Sets indices to be masked
Args:
mask (torch.Tensor): tensor containing indices to be masked
"""
self.mask = mask
"""
- query (batch, query_len, dimensions): tensor containing the query features from the decoder.
- context (batch, input_len, dimensions): tensor containing features of the encoded input sequence.
"""
def forward(self, query, context):
batch_size = query.size(0)
query.size(2)
in_len = context.size(1)
attn = torch.bmm(query, context.transpose(1, 2))
if self.mask is not None:
attn.data.masked_fill_(self.mask, -float('inf'))
attn_scores = F.softmax(attn.view(-1, in_len), dim=1).view(batch_size,
-1, in_len)
attn_out = torch.bmm(attn_scores, context)
return attn_out, attn_scores
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
arg0_1, arg1_1 = 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(arg0_1, reinterpret_tensor(arg1_1, (4, 4, 4), (
16, 1, 4), 0), out=buf0)
del arg0_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf0, (16, 4), (4, 1), 0)
del buf0
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1),
0), arg1_1, out=buf3)
del arg1_1
return buf3, reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0)
class AttentionNew(nn.Module):
"""
Applies an attention mechanism on the query features from the decoder.
.. math::
\\begin{array}{ll}
x = context*query \\\\
attn_scores = exp(x_i) / sum_j exp(x_j) \\\\
attn_out = attn * context
\\end{array}
Args:
dim(int): The number of expected features in the query
Inputs: query, context
- **query** (batch, query_len, dimensions): tensor containing the query features from the decoder.
- **context** (batch, input_len, dimensions): tensor containing features of the encoded input sequence.
Outputs: query, attn
- **query** (batch, query_len, dimensions): tensor containing the attended query features from the decoder.
- **attn** (batch, query_len, input_len): tensor containing attention weights.
Attributes:
mask (torch.Tensor, optional): applies a :math:`-inf` to the indices specified in the `Tensor`.
"""
def __init__(self):
super(AttentionNew, self).__init__()
self.mask = None
def set_mask(self, mask):
"""
Sets indices to be masked
Args:
mask (torch.Tensor): tensor containing indices to be masked
"""
self.mask = mask
"""
- query (batch, query_len, dimensions): tensor containing the query features from the decoder.
- context (batch, input_len, dimensions): tensor containing features of the encoded input sequence.
"""
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]
|
nguyenxuanhoi2903/SRSF_summarization
|
Attention
| false
| 7,329
|
[
"MIT"
] | 1
|
3d19e6b7669e0b22bab533fc637a434f379ed392
|
https://github.com/nguyenxuanhoi2903/SRSF_summarization/tree/3d19e6b7669e0b22bab533fc637a434f379ed392
|
MinusRbfHSIC
|
import torch
import torch.nn as nn
class HSIC(nn.Module):
"""Base class for the finite sample estimator of Hilbert-Schmidt Independence Criterion (HSIC)
..math:: HSIC (X, Y) := || C_{x, y} ||^2_{HS}, where HSIC (X, Y) = 0 iif X and Y are independent.
Empirically, we use the finite sample estimator of HSIC (with m observations) by,
(1) biased estimator (HSIC_0)
Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
:math: (m - 1)^2 tr KHLH.
where K_{ij} = kernel_x (x_i, x_j), L_{ij} = kernel_y (y_i, y_j), H = 1 - m^{-1} 1 1 (Hence, K, L, H are m by m matrices).
(2) unbiased estimator (HSIC_1)
Song, Le, et al. "Feature selection via dependence maximization." 2012.
:math: rac{1}{m (m - 3)} igg[ tr ( ilde K ilde L) + rac{1^ op ilde K 1 1^ op ilde L 1}{(m-1)(m-2)} - rac{2}{m-2} 1^ op ilde K ilde L 1 igg].
where ilde K and ilde L are related to K and L by the diagonal entries of ilde K_{ij} and ilde L_{ij} are set to zero.
Parameters
----------
sigma_x : float
the kernel size of the kernel function for X.
sigma_y : float
the kernel size of the kernel function for Y.
algorithm: str ('unbiased' / 'biased')
the algorithm for the finite sample estimator. 'unbiased' is used for our paper.
reduction: not used (for compatibility with other losses).
"""
def __init__(self, sigma_x, sigma_y=None, algorithm='unbiased',
reduction=None):
super(HSIC, self).__init__()
if sigma_y is None:
sigma_y = sigma_x
self.sigma_x = sigma_x
self.sigma_y = sigma_y
if algorithm == 'biased':
self.estimator = self.biased_estimator
elif algorithm == 'unbiased':
self.estimator = self.unbiased_estimator
else:
raise ValueError('invalid estimator: {}'.format(algorithm))
def _kernel_x(self, X):
raise NotImplementedError
def _kernel_y(self, Y):
raise NotImplementedError
def biased_estimator(self, input1, input2):
"""Biased estimator of Hilbert-Schmidt Independence Criterion
Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
"""
K = self._kernel_x(input1)
L = self._kernel_y(input2)
KH = K - K.mean(0, keepdim=True)
LH = L - L.mean(0, keepdim=True)
N = len(input1)
return torch.trace(KH @ LH / (N - 1) ** 2)
def unbiased_estimator(self, input1, input2):
"""Unbiased estimator of Hilbert-Schmidt Independence Criterion
Song, Le, et al. "Feature selection via dependence maximization." 2012.
"""
kernel_XX = self._kernel_x(input1)
kernel_YY = self._kernel_y(input2)
tK = kernel_XX - torch.diag(kernel_XX)
tL = kernel_YY - torch.diag(kernel_YY)
N = len(input1)
hsic = torch.trace(tK @ tL) + torch.sum(tK) * torch.sum(tL) / (N - 1
) / (N - 2) - 2 * torch.sum(tK, 0).dot(torch.sum(tL, 0)) / (N - 2)
return hsic / (N * (N - 3))
def forward(self, input1, input2, **kwargs):
return self.estimator(input1, input2)
class RbfHSIC(HSIC):
"""Radial Basis Function (RBF) kernel HSIC implementation.
"""
def _kernel(self, X, sigma):
X = X.view(len(X), -1)
Xn = X.norm(2, dim=1, keepdim=True)
X = X.div(Xn)
XX = X @ X.t()
X_sqnorms = torch.diag(XX)
X_L2 = -2 * XX + X_sqnorms.unsqueeze(1) + X_sqnorms.unsqueeze(0)
X_L2 = X_L2.clamp(1e-12)
sigma_avg = X_L2.mean().detach()
gamma = 1 / (2 * sigma_avg)
kernel_XX = torch.exp(-gamma * X_L2)
return kernel_XX
def _kernel_x(self, X):
return self._kernel(X, self.sigma_x)
def _kernel_y(self, Y):
return self._kernel(Y, self.sigma_y)
class MinusRbfHSIC(RbfHSIC):
"""``Minus'' RbfHSIC for the ``max'' optimization.
"""
def forward(self, input1, input2, **kwargs):
return -self.estimator(input1, input2)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'sigma_x': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_div_linalg_vector_norm_0(in_ptr0, out_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = libdevice.sqrt(tmp5)
tmp7 = tmp0 / tmp6
tl.store(out_ptr1 + (r1 + 64 * x0), tmp7, xmask)
@triton.jit
def triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1(
in_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
r1 = rindex // 4
r0 = rindex % 4
tmp0 = tl.load(in_ptr0 + r2, None)
tmp3 = tl.load(in_ptr0 + 5 * r1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last')
tmp1 = -2.0
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 1e-12
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.sum(tmp9, 1)[:, None]
tmp12 = 16.0
tmp13 = tmp11 / tmp12
tmp14 = 2.0
tmp15 = tmp13 * tmp14
tmp16 = tl.full([1, 1], 1, tl.int32)
tmp17 = tmp16 / tmp15
tmp18 = 1.0
tmp19 = tmp17 * tmp18
tmp20 = -tmp19
tmp21 = tmp20 * tmp8
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp5 * tmp1
tmp24 = tmp23 + tmp5
tmp25 = tmp24 + tmp5
tmp26 = triton_helpers.maximum(tmp25, tmp7)
tmp27 = tmp20 * tmp26
tmp28 = tl_math.exp(tmp27)
tmp29 = tmp22 - tmp28
tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
tmp32 = tl.sum(tmp30, 1)[:, None]
tl.store(out_ptr1 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp29, None)
tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)
@triton.jit
def triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, xnumel, rnumel, XBLOCK: tl
.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + r0, None)
tmp5 = tl.load(in_ptr1 + (4 + r0), None)
tmp7 = tl.load(in_ptr1 + (8 + r0), None)
tmp9 = tl.load(in_ptr1 + (12 + r0), None)
tmp11 = tl.load(in_ptr2 + r0, None)
tmp12 = tl.load(in_ptr2 + (4 + r0), None)
tmp14 = tl.load(in_ptr2 + (8 + r0), None)
tmp16 = tl.load(in_ptr2 + (12 + r0), None)
tmp22 = tl.load(in_ptr3 + 0)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK, 1])
tmp24 = tl.load(in_ptr4 + 0)
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, 1])
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.sum(tmp1, 1)[:, None]
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp17 = tmp15 + tmp16
tmp18 = tmp10 * tmp17
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp21 = tl.sum(tmp19, 1)[:, None]
tmp26 = tmp23 * tmp25
tmp27 = 0.3333333333333333
tmp28 = tmp26 * tmp27
tmp29 = 0.5
tmp30 = tmp28 * tmp29
tmp31 = tmp3 + tmp30
tmp32 = 2.0
tmp33 = tmp21 * tmp32
tmp34 = tmp33 * tmp29
tmp35 = tmp31 - tmp34
tmp36 = 0.25
tmp37 = tmp35 * tmp36
tmp38 = -tmp37
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp38, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_div_linalg_vector_norm_0[grid(4)](arg0_1, buf1, 4,
64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(buf1, (64, 4), (1, 64),
0), out=buf2)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf12 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1[
grid(1)](buf2, buf4, buf12, 1, 16, XBLOCK=1, num_warps=2,
num_stages=1)
buf6 = buf1
del buf1
triton_per_fused_div_linalg_vector_norm_0[grid(4)](arg1_1, buf6, 4,
64, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
buf7 = buf2
del buf2
extern_kernels.mm(buf6, reinterpret_tensor(buf6, (64, 4), (1, 64),
0), out=buf7)
del buf6
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf13 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1[
grid(1)](buf7, buf9, buf13, 1, 16, XBLOCK=1, num_warps=2,
num_stages=1)
buf10 = buf7
del buf7
extern_kernels.mm(buf4, buf9, out=buf10)
buf11 = empty_strided_cuda((), (), torch.float32)
buf15 = buf11
del buf11
triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2[grid(1)](buf15,
buf10, buf4, buf9, buf12, buf13, 1, 4, XBLOCK=1, num_warps=2,
num_stages=1)
del buf10
del buf12
del buf13
del buf4
del buf9
return buf15,
class HSIC(nn.Module):
"""Base class for the finite sample estimator of Hilbert-Schmidt Independence Criterion (HSIC)
..math:: HSIC (X, Y) := || C_{x, y} ||^2_{HS}, where HSIC (X, Y) = 0 iif X and Y are independent.
Empirically, we use the finite sample estimator of HSIC (with m observations) by,
(1) biased estimator (HSIC_0)
Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
:math: (m - 1)^2 tr KHLH.
where K_{ij} = kernel_x (x_i, x_j), L_{ij} = kernel_y (y_i, y_j), H = 1 - m^{-1} 1 1 (Hence, K, L, H are m by m matrices).
(2) unbiased estimator (HSIC_1)
Song, Le, et al. "Feature selection via dependence maximization." 2012.
:math: rac{1}{m (m - 3)} igg[ tr ( ilde K ilde L) + rac{1^ op ilde K 1 1^ op ilde L 1}{(m-1)(m-2)} - rac{2}{m-2} 1^ op ilde K ilde L 1 igg].
where ilde K and ilde L are related to K and L by the diagonal entries of ilde K_{ij} and ilde L_{ij} are set to zero.
Parameters
----------
sigma_x : float
the kernel size of the kernel function for X.
sigma_y : float
the kernel size of the kernel function for Y.
algorithm: str ('unbiased' / 'biased')
the algorithm for the finite sample estimator. 'unbiased' is used for our paper.
reduction: not used (for compatibility with other losses).
"""
def __init__(self, sigma_x, sigma_y=None, algorithm='unbiased',
reduction=None):
super(HSIC, self).__init__()
if sigma_y is None:
sigma_y = sigma_x
self.sigma_x = sigma_x
self.sigma_y = sigma_y
if algorithm == 'biased':
self.estimator = self.biased_estimator
elif algorithm == 'unbiased':
self.estimator = self.unbiased_estimator
else:
raise ValueError('invalid estimator: {}'.format(algorithm))
def _kernel_x(self, X):
raise NotImplementedError
def _kernel_y(self, Y):
raise NotImplementedError
def biased_estimator(self, input1, input2):
"""Biased estimator of Hilbert-Schmidt Independence Criterion
Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
"""
K = self._kernel_x(input1)
L = self._kernel_y(input2)
KH = K - K.mean(0, keepdim=True)
LH = L - L.mean(0, keepdim=True)
N = len(input1)
return torch.trace(KH @ LH / (N - 1) ** 2)
def unbiased_estimator(self, input1, input2):
"""Unbiased estimator of Hilbert-Schmidt Independence Criterion
Song, Le, et al. "Feature selection via dependence maximization." 2012.
"""
kernel_XX = self._kernel_x(input1)
kernel_YY = self._kernel_y(input2)
tK = kernel_XX - torch.diag(kernel_XX)
tL = kernel_YY - torch.diag(kernel_YY)
N = len(input1)
hsic = torch.trace(tK @ tL) + torch.sum(tK) * torch.sum(tL) / (N - 1
) / (N - 2) - 2 * torch.sum(tK, 0).dot(torch.sum(tL, 0)) / (N - 2)
return hsic / (N * (N - 3))
def forward(self, input1, input2, **kwargs):
return self.estimator(input1, input2)
class RbfHSIC(HSIC):
"""Radial Basis Function (RBF) kernel HSIC implementation.
"""
def _kernel(self, X, sigma):
X = X.view(len(X), -1)
Xn = X.norm(2, dim=1, keepdim=True)
X = X.div(Xn)
XX = X @ X.t()
X_sqnorms = torch.diag(XX)
X_L2 = -2 * XX + X_sqnorms.unsqueeze(1) + X_sqnorms.unsqueeze(0)
X_L2 = X_L2.clamp(1e-12)
sigma_avg = X_L2.mean().detach()
gamma = 1 / (2 * sigma_avg)
kernel_XX = torch.exp(-gamma * X_L2)
return kernel_XX
def _kernel_x(self, X):
return self._kernel(X, self.sigma_x)
def _kernel_y(self, Y):
return self._kernel(Y, self.sigma_y)
class MinusRbfHSICNew(RbfHSIC):
"""``Minus'' RbfHSIC for the ``max'' optimization.
"""
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
naver-ai/cgl_fairness
|
MinusRbfHSIC
| false
| 7,330
|
[
"MIT"
] | 1
|
00d3bec233c9b3e0f88496118abaed8321ca3159
|
https://github.com/naver-ai/cgl_fairness/tree/00d3bec233c9b3e0f88496118abaed8321ca3159
|
LayerNorm
|
import torch
class LayerNorm(torch.nn.Module):
"""
A vanilla implementation of layer normalization https://arxiv.org/pdf/1607.06450.pdf
norm_x = (x - mean) / sqrt((x - mean) ^ 2)
This does not include the trainable parameters gamma and beta for performance speed.
Typically, this is norm_x * gamma + beta
"""
def forward(self, layer_activations: 'torch.Tensor') ->torch.Tensor:
mean = torch.mean(layer_activations, dim=-1, keepdim=True)
var = torch.mean((layer_activations - mean) ** 2, dim=-1, keepdim=True)
return (layer_activations - mean) / torch.sqrt(var + 1e-05)
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_pow_sqrt_sub_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = 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 + x2, 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_pow_sqrt_sub_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class LayerNormNew(torch.nn.Module):
"""
A vanilla implementation of layer normalization https://arxiv.org/pdf/1607.06450.pdf
norm_x = (x - mean) / sqrt((x - mean) ^ 2)
This does not include the trainable parameters gamma and beta for performance speed.
Typically, this is norm_x * gamma + beta
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
netdrones/ml-agents
|
LayerNorm
| false
| 7,331
|
[
"Apache-2.0"
] | 1
|
7d7d6f149c92ea2067d7cea364d92c8c3b8db3f4
|
https://github.com/netdrones/ml-agents/tree/7d7d6f149c92ea2067d7cea364d92c8c3b8db3f4
|
TokenClassifier
|
import torch
import torch.nn as nn
def transformer_weights_init(module, std_init_range=0.02, xavier=True):
"""
Initialize different weights in Transformer model.
Args:
module: torch.nn.Module to be initialized
std_init_range: standard deviation of normal initializer
xavier: if True, xavier initializer will be used in Linear layers
as was proposed in AIAYN paper, otherwise normal initializer
will be used (like in BERT paper)
"""
if isinstance(module, nn.Linear):
if xavier:
nn.init.xavier_uniform_(module.weight)
else:
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
if module.bias is not None:
nn.init.constant_(module.bias, 0.0)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
elif isinstance(module, nn.LayerNorm):
nn.init.constant_(module.weight, 1.0)
nn.init.constant_(module.bias, 0.0)
class MultiLayerPerceptron(torch.nn.Module):
"""
A simple MLP that can either be used independently or put on top
of pretrained models (such as BERT) and act as a classifier.
Args:
hidden_size (int): the size of each layer
num_classes (int): number of output classes
num_layers (int): number of layers
activation (str): type of activations for layers in between
log_softmax (bool): whether to add a log_softmax layer before output
"""
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=2, activation: 'str'='relu', log_softmax: 'bool'=True):
super().__init__()
self.layers = 0
activations = {'relu': nn.ReLU(), 'gelu': nn.GELU(), 'sigmoid': nn.
Sigmoid(), 'tanh': nn.Tanh()}
for _ in range(num_layers - 1):
layer = torch.nn.Linear(hidden_size, hidden_size)
setattr(self, f'layer{self.layers}', layer)
setattr(self, f'layer{self.layers + 1}', activations[activation])
self.layers += 2
layer = torch.nn.Linear(hidden_size, num_classes)
setattr(self, f'layer{self.layers}', layer)
self.layers += 1
self.log_softmax = log_softmax
@property
def last_linear_layer(self):
return getattr(self, f'layer{self.layers - 1}')
def forward(self, hidden_states):
output_states = hidden_states[:]
for i in range(self.layers):
output_states = getattr(self, f'layer{i}')(output_states)
if self.log_softmax:
output_states = torch.log_softmax(output_states, dim=-1)
else:
output_states = torch.softmax(output_states, dim=-1)
return output_states
class TokenClassifier(nn.Module):
"""
A module to perform token level classification tasks such as Named entity recognition.
"""
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=1, activation: 'str'='relu', log_softmax: 'bool'=True,
dropout: 'float'=0.0, use_transformer_init: 'bool'=True) ->None:
"""
Initializes the Token Classifier module.
Args:
hidden_size: the size of the hidden dimension
num_classes: number of classes
num_layers: number of fully connected layers in the multilayer perceptron (MLP)
activation: activation to usee between fully connected layers in the MLP
log_softmax: whether to apply softmax to the output of the MLP
dropout: dropout to apply to the input hidden states
use_transformer_init: whether to initialize the weights of the classifier head with the same approach used in Transformer
"""
super().__init__()
self.log_softmax = log_softmax
self.mlp = MultiLayerPerceptron(hidden_size, num_classes,
num_layers=num_layers, activation=activation, log_softmax=
log_softmax)
self.dropout = nn.Dropout(dropout)
if use_transformer_init:
self.apply(lambda module: transformer_weights_init(module,
xavier=False))
def forward(self, hidden_states):
"""
Performs the forward step of the module.
Args:
hidden_states: batch of hidden states (for example, from the BERT encoder module)
[BATCH_SIZE x SEQ_LENGTH x HIDDEN_SIZE]
Returns: logits value for each class [BATCH_SIZE x SEQ_LENGTH x NUM_CLASSES]
"""
hidden_states = self.dropout(hidden_states)
logits = self.mlp(hidden_states)
return logits
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](buf0, buf1, 256, XBLOCK=
256, num_warps=4, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused__log_softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del buf1
return buf2, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), buf2
def transformer_weights_init(module, std_init_range=0.02, xavier=True):
"""
Initialize different weights in Transformer model.
Args:
module: torch.nn.Module to be initialized
std_init_range: standard deviation of normal initializer
xavier: if True, xavier initializer will be used in Linear layers
as was proposed in AIAYN paper, otherwise normal initializer
will be used (like in BERT paper)
"""
if isinstance(module, nn.Linear):
if xavier:
nn.init.xavier_uniform_(module.weight)
else:
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
if module.bias is not None:
nn.init.constant_(module.bias, 0.0)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
elif isinstance(module, nn.LayerNorm):
nn.init.constant_(module.weight, 1.0)
nn.init.constant_(module.bias, 0.0)
class MultiLayerPerceptron(torch.nn.Module):
"""
A simple MLP that can either be used independently or put on top
of pretrained models (such as BERT) and act as a classifier.
Args:
hidden_size (int): the size of each layer
num_classes (int): number of output classes
num_layers (int): number of layers
activation (str): type of activations for layers in between
log_softmax (bool): whether to add a log_softmax layer before output
"""
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=2, activation: 'str'='relu', log_softmax: 'bool'=True):
super().__init__()
self.layers = 0
activations = {'relu': nn.ReLU(), 'gelu': nn.GELU(), 'sigmoid': nn.
Sigmoid(), 'tanh': nn.Tanh()}
for _ in range(num_layers - 1):
layer = torch.nn.Linear(hidden_size, hidden_size)
setattr(self, f'layer{self.layers}', layer)
setattr(self, f'layer{self.layers + 1}', activations[activation])
self.layers += 2
layer = torch.nn.Linear(hidden_size, num_classes)
setattr(self, f'layer{self.layers}', layer)
self.layers += 1
self.log_softmax = log_softmax
@property
def last_linear_layer(self):
return getattr(self, f'layer{self.layers - 1}')
def forward(self, hidden_states):
output_states = hidden_states[:]
for i in range(self.layers):
output_states = getattr(self, f'layer{i}')(output_states)
if self.log_softmax:
output_states = torch.log_softmax(output_states, dim=-1)
else:
output_states = torch.softmax(output_states, dim=-1)
return output_states
class TokenClassifierNew(nn.Module):
"""
A module to perform token level classification tasks such as Named entity recognition.
"""
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=1, activation: 'str'='relu', log_softmax: 'bool'=True,
dropout: 'float'=0.0, use_transformer_init: 'bool'=True) ->None:
"""
Initializes the Token Classifier module.
Args:
hidden_size: the size of the hidden dimension
num_classes: number of classes
num_layers: number of fully connected layers in the multilayer perceptron (MLP)
activation: activation to usee between fully connected layers in the MLP
log_softmax: whether to apply softmax to the output of the MLP
dropout: dropout to apply to the input hidden states
use_transformer_init: whether to initialize the weights of the classifier head with the same approach used in Transformer
"""
super().__init__()
self.log_softmax = log_softmax
self.mlp = MultiLayerPerceptron(hidden_size, num_classes,
num_layers=num_layers, activation=activation, log_softmax=
log_softmax)
self.dropout = nn.Dropout(dropout)
if use_transformer_init:
self.apply(lambda module: transformer_weights_init(module,
xavier=False))
def forward(self, input_0):
primals_2 = self.mlp.layer0.weight
primals_3 = self.mlp.layer0.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ngxingyu/Domain-Transfer-for-Punctuation-Retrieval
|
TokenClassifier
| false
| 7,332
|
[
"Apache-2.0"
] | 1
|
f5aa0ea0946c68aaf7fcf49a5085e6c823766a2f
|
https://github.com/ngxingyu/Domain-Transfer-for-Punctuation-Retrieval/tree/f5aa0ea0946c68aaf7fcf49a5085e6c823766a2f
|
MultichannelIamge
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ModulatedConv2d(nn.Module):
def __init__(self, channels_in, channels_out, style_dim, kernel_size,
demodulate=True):
super().__init__()
self.weight = nn.Parameter(torch.randn(channels_out, channels_in,
kernel_size, kernel_size))
self.modulation = nn.Linear(style_dim, channels_in, bias=True)
self.modulation.bias.data.fill_(1.0)
self.demodulate = demodulate
if self.demodulate:
self.register_buffer('style_inv', torch.randn(1, 1, channels_in,
1, 1))
self.scale = 1.0 / math.sqrt(channels_in * kernel_size ** 2)
self.padding = kernel_size // 2
def forward(self, x, style):
modulation = self.get_modulation(style)
x = modulation * x
x = F.conv2d(x, self.weight, padding=self.padding)
if self.demodulate:
demodulation = self.get_demodulation(style)
x = demodulation * x
return x
def get_modulation(self, style):
style = self.modulation(style).view(style.size(0), -1, 1, 1)
modulation = self.scale * style
return modulation
def get_demodulation(self, style):
w = self.weight.unsqueeze(0)
norm = torch.rsqrt((self.scale * self.style_inv * w).pow(2).sum([2,
3, 4]) + 1e-08)
demodulation = norm
return demodulation.view(*demodulation.size(), 1, 1)
class MultichannelIamge(nn.Module):
def __init__(self, channels_in, channels_out, style_dim, kernel_size=1):
super().__init__()
self.conv = ModulatedConv2d(channels_in, channels_out, style_dim,
kernel_size, demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, channels_out, 1, 1))
def forward(self, hidden, style):
out = self.conv(hidden, style)
out = out + self.bias
return out
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'channels_in': 4, 'channels_out': 4, 'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
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_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex // 16
x1 = xindex // 16 % 4
x0 = xindex % 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tl.store(out_ptr0 + x4, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_6, (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, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 4),
(1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](buf0, primals_2, primals_4, buf1,
256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_5, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_add_1[grid(256)](buf3, primals_6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_6
return buf3, primals_3, primals_4, primals_5, buf1
class ModulatedConv2d(nn.Module):
def __init__(self, channels_in, channels_out, style_dim, kernel_size,
demodulate=True):
super().__init__()
self.weight = nn.Parameter(torch.randn(channels_out, channels_in,
kernel_size, kernel_size))
self.modulation = nn.Linear(style_dim, channels_in, bias=True)
self.modulation.bias.data.fill_(1.0)
self.demodulate = demodulate
if self.demodulate:
self.register_buffer('style_inv', torch.randn(1, 1, channels_in,
1, 1))
self.scale = 1.0 / math.sqrt(channels_in * kernel_size ** 2)
self.padding = kernel_size // 2
def forward(self, x, style):
modulation = self.get_modulation(style)
x = modulation * x
x = F.conv2d(x, self.weight, padding=self.padding)
if self.demodulate:
demodulation = self.get_demodulation(style)
x = demodulation * x
return x
def get_modulation(self, style):
style = self.modulation(style).view(style.size(0), -1, 1, 1)
modulation = self.scale * style
return modulation
def get_demodulation(self, style):
w = self.weight.unsqueeze(0)
norm = torch.rsqrt((self.scale * self.style_inv * w).pow(2).sum([2,
3, 4]) + 1e-08)
demodulation = norm
return demodulation.view(*demodulation.size(), 1, 1)
class MultichannelIamgeNew(nn.Module):
def __init__(self, channels_in, channels_out, style_dim, kernel_size=1):
super().__init__()
self.conv = ModulatedConv2d(channels_in, channels_out, style_dim,
kernel_size, demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, channels_out, 1, 1))
def forward(self, input_0, input_1):
primals_6 = self.bias
primals_5 = self.conv.weight
primals_1 = self.conv.modulation.weight
primals_2 = self.conv.modulation.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
nhorton04/mobile_styletransfer
|
MultichannelIamge
| false
| 7,333
|
[
"Apache-2.0"
] | 1
|
db8b9a61b67fd58b9e4d61457ee58e36800cfbbe
|
https://github.com/nhorton04/mobile_styletransfer/tree/db8b9a61b67fd58b9e4d61457ee58e36800cfbbe
|
Net
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.data
class Net(nn.Module):
def __init__(self, input_size, num_classes):
super(Net, self).__init__()
self.linear1 = nn.Linear(input_size, 128)
self.linear2 = nn.Linear(128, 256)
self.linear3 = nn.Linear(256, 512)
self.linear4 = nn.Linear(512, 256)
self.linear5 = nn.Linear(256, 128)
self.linear6 = nn.Linear(128, num_classes)
def forward(self, x):
x = x.float()
x = F.relu(self.linear1(x))
x = F.relu(self.linear2(x))
x = F.relu(self.linear3(x))
x = F.relu(self.linear4(x))
x = F.relu(self.linear5(x))
x = self.linear6(x)
return F.log_softmax(x, dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_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 % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(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__log_softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x3, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (128, 4), (4, 1))
assert_size_stride(primals_3, (128,), (1,))
assert_size_stride(primals_4, (256, 128), (128, 1))
assert_size_stride(primals_5, (256,), (1,))
assert_size_stride(primals_6, (512, 256), (256, 1))
assert_size_stride(primals_7, (512,), (1,))
assert_size_stride(primals_8, (256, 512), (512, 1))
assert_size_stride(primals_9, (256,), (1,))
assert_size_stride(primals_10, (128, 256), (256, 1))
assert_size_stride(primals_11, (128,), (1,))
assert_size_stride(primals_12, (4, 128), (128, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 128), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf0
buf17 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf1,
primals_3, buf17, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 128), (128, 1), 0),
reinterpret_tensor(primals_4, (128, 256), (1, 128), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf2
buf16 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(16384)](buf3,
primals_5, buf16, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_6, (256, 512), (1, 256), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 512), (8192, 2048, 512, 1), 0
)
del buf4
buf15 = empty_strided_cuda((4, 4, 4, 512), (8192, 2048, 512, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(32768)](buf5,
primals_7, buf15, 32768, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (64, 512), (512, 1), 0),
reinterpret_tensor(primals_8, (512, 256), (1, 512), 0), out=buf6)
buf7 = reinterpret_tensor(buf6, (4, 4, 4, 256), (4096, 1024, 256, 1), 0
)
del buf6
buf14 = empty_strided_cuda((4, 4, 4, 256), (4096, 1024, 256, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(16384)](buf7,
primals_9, buf14, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (64, 256), (256, 1), 0),
reinterpret_tensor(primals_10, (256, 128), (1, 256), 0), out=buf8)
buf9 = reinterpret_tensor(buf8, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf8
buf13 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf9,
primals_11, buf13, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf10 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf9, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_12, (128, 4), (1, 128),
0), alpha=1, beta=1, out=buf10)
del primals_13
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_3[grid(256)](buf10, buf11, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf12 = reinterpret_tensor(buf10, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf10
triton_poi_fused__log_softmax_4[grid(256)](buf11, buf12, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del buf11
return (buf12, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (64, 128), (128, 1), 0),
reinterpret_tensor(buf3, (64, 256), (256, 1), 0),
reinterpret_tensor(buf5, (64, 512), (512, 1), 0),
reinterpret_tensor(buf7, (64, 256), (256, 1), 0),
reinterpret_tensor(buf9, (64, 128), (128, 1), 0), buf12, primals_12,
buf13, primals_10, buf14, primals_8, buf15, primals_6, buf16,
primals_4, buf17)
class NetNew(nn.Module):
def __init__(self, input_size, num_classes):
super(NetNew, self).__init__()
self.linear1 = nn.Linear(input_size, 128)
self.linear2 = nn.Linear(128, 256)
self.linear3 = nn.Linear(256, 512)
self.linear4 = nn.Linear(512, 256)
self.linear5 = nn.Linear(256, 128)
self.linear6 = nn.Linear(128, num_classes)
def forward(self, input_0):
primals_2 = self.linear1.weight
primals_3 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_6 = self.linear3.weight
primals_7 = self.linear3.bias
primals_8 = self.linear4.weight
primals_9 = self.linear4.bias
primals_10 = self.linear5.weight
primals_11 = self.linear5.bias
primals_12 = self.linear6.weight
primals_13 = self.linear6.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
nce3xin/spam
|
Net
| false
| 7,334
|
[
"MIT"
] | 1
|
908421d5cf2dd103e2a7044bf1c8586aaf5f2ada
|
https://github.com/nce3xin/spam/tree/908421d5cf2dd103e2a7044bf1c8586aaf5f2ada
|
ResidualBlock
|
import torch
import torch.nn as nn
class ConvLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride):
super(ConvLayer, self).__init__()
padding = kernel_size // 2
self.reflection_pad = nn.ReflectionPad2d(padding)
self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride)
def forward(self, x):
out = self.reflection_pad(x)
out = self.conv2d(out)
return out
class ResidualBlock(nn.Module):
def __init__(self, channels):
super(ResidualBlock, self).__init__()
self.conv1 = ConvLayer(channels, channels, kernel_size=3, stride=1)
self.in1 = nn.InstanceNorm2d(channels, affine=True)
self.relu = nn.ReLU()
self.conv2 = ConvLayer(channels, channels, kernel_size=3, stride=1)
self.in2 = nn.InstanceNorm2d(channels, affine=True)
def forward(self, x):
residual = x
out = self.relu(self.in1(self.conv1(x)))
out = self.in2(self.conv2(out))
out = out + residual
out = self.relu(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_reflection_pad2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6 % 6
x2 = xindex // 36
x3 = xindex
tmp0 = tl.load(in_ptr0 + (15 + -1 * tl_math.abs(-3 + tl_math.abs(-1 +
x0)) + -4 * tl_math.abs(-3 + tl_math.abs(-1 + x1)) + 16 * x2),
xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_convolution_1(in_out_ptr0,
in_out_ptr1, in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tl.where(xmask, tmp3, 0)
tmp6 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 16.0
tmp20 = tmp18 / tmp19
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(in_out_ptr0 + (r2 + 16 * x3), tmp2, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp23, xmask)
tl.store(out_ptr0 + x3, tmp12, xmask)
@triton.jit
def triton_poi_fused_repeat_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0 % 4, xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_reflection_pad2d_relu_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6 % 6
x2 = xindex // 36
x3 = xindex
tmp0 = tl.load(in_ptr0 + (15 + -1 * tl_math.abs(-3 + tl_math.abs(-1 +
x0)) + -4 * tl_math.abs(-3 + tl_math.abs(-1 + x1)) + 16 * x2),
xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_4(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1,
out_ptr3, out_ptr4, out_ptr5, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex
r3 = rindex
x1 = xindex % 4
tmp0 = tl.load(in_ptr0 + x0 % 4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_out_ptr0 + (r3 + 16 * x0), xmask, other=0.0)
tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr3 + (r3 + 16 * x0), xmask, other=0.0)
tmp3 = tmp1 + tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tl.where(xmask, tmp4, 0)
tmp7 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp12 = tmp11.to(tl.float32)
tmp13 = tmp10 / tmp12
tmp14 = tmp4 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.where(xmask, tmp16, 0)
tmp19 = tl.sum(tmp18, 1)[:, None]
tmp20 = tmp3 - tmp13
tmp21 = 16.0
tmp22 = tmp19 / tmp21
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.rsqrt(tmp24)
tmp26 = tmp20 * tmp25
tmp27 = tmp26 * tmp0
tmp29 = tmp27 + tmp28
tmp31 = tmp29 + tmp30
tmp32 = tl.full([1, 1], 0, tl.int32)
tmp33 = triton_helpers.maximum(tmp32, tmp31)
tmp34 = 0.0
tmp35 = tmp33 <= tmp34
tl.store(out_ptr0 + x0, tmp0, xmask)
tl.store(in_out_ptr0 + (r3 + 16 * x0), tmp3, xmask)
tl.store(out_ptr3 + (r3 + 16 * x0), tmp33, xmask)
tl.store(out_ptr4 + (r3 + 16 * x0), tmp35, xmask)
tl.store(out_ptr5 + x0, tmp25, xmask)
tl.store(out_ptr1 + x0, 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, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_reflection_pad2d_0[grid(576)](primals_1, buf0, 576,
XBLOCK=128, num_warps=4, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
buf5 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf6 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf8 = reinterpret_tensor(buf6, (1, 16, 1, 1), (16, 1, 1, 1), 0)
del buf6
triton_per_fused__native_batch_norm_legit_convolution_1[grid(16)](buf2,
buf8, primals_3, buf5, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((16,), (1,), torch.float32)
triton_poi_fused_repeat_2[grid(16)](primals_4, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_4
buf4 = empty_strided_cuda((16,), (1,), torch.float32)
triton_poi_fused_repeat_2[grid(16)](primals_5, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_5
buf9 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
triton_poi_fused_reflection_pad2d_relu_3[grid(576)](buf2, buf5,
buf8, buf3, buf4, buf9, 576, XBLOCK=128, num_warps=4, num_stages=1)
buf10 = extern_kernels.convolution(buf9, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 4, 4, 4), (64, 16, 4, 1))
buf12 = empty_strided_cuda((16,), (1,), torch.float32)
buf11 = buf10
del buf10
buf13 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
buf17 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf18 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf16 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
triton_per_fused__native_batch_norm_legit_add_convolution_relu_repeat_threshold_backward_4[
grid(16)](buf11, primals_8, primals_7, primals_9, primals_1,
buf12, buf13, buf17, buf18, buf16, 16, 16, XBLOCK=8, num_warps=
2, num_stages=1)
del primals_1
del primals_7
del primals_8
del primals_9
return (buf17, primals_2, primals_6, buf0, buf2, buf3, buf4, buf5, buf8,
buf9, buf11, buf12, reinterpret_tensor(buf16, (16,), (1,), 0),
buf18, reinterpret_tensor(buf13, (1, 16, 1, 1), (16, 1, 1, 1), 0))
class ConvLayer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride):
super(ConvLayer, self).__init__()
padding = kernel_size // 2
self.reflection_pad = nn.ReflectionPad2d(padding)
self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride)
def forward(self, x):
out = self.reflection_pad(x)
out = self.conv2d(out)
return out
class ResidualBlockNew(nn.Module):
def __init__(self, channels):
super(ResidualBlockNew, self).__init__()
self.conv1 = ConvLayer(channels, channels, kernel_size=3, stride=1)
self.in1 = nn.InstanceNorm2d(channels, affine=True)
self.relu = nn.ReLU()
self.conv2 = ConvLayer(channels, channels, kernel_size=3, stride=1)
self.in2 = nn.InstanceNorm2d(channels, affine=True)
def forward(self, input_0):
primals_2 = self.conv1.conv2d.weight
primals_3 = self.conv1.conv2d.bias
primals_4 = self.in1.weight
primals_5 = self.in1.bias
primals_6 = self.conv2.conv2d.weight
primals_7 = self.conv2.conv2d.bias
primals_8 = self.in2.weight
primals_9 = self.in2.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]
|
naver-ai/cgl_fairness
|
ResidualBlock
| false
| 7,335
|
[
"MIT"
] | 1
|
00d3bec233c9b3e0f88496118abaed8321ca3159
|
https://github.com/naver-ai/cgl_fairness/tree/00d3bec233c9b3e0f88496118abaed8321ca3159
|
PositionGenerator
|
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
"""Construct a layernorm module (See citation for details)."""
def __init__(self, features, eps=1e-06):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class PositionGenerator(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, d_model):
super(PositionGenerator, self).__init__()
self.norm = LayerNorm(d_model)
self.proj = nn.Linear(d_model, 3)
def forward(self, x, mask):
mask = mask.unsqueeze(-1).float()
out_masked = self.norm(x) * mask
projected = self.proj(out_masked)
return projected
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 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_add_div_mean_mul_std_sub_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 4.0
tmp10 = tmp8 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp0 * tmp11
tmp13 = tmp2 - tmp10
tmp14 = tmp13 * tmp13
tmp15 = tmp3 - tmp10
tmp16 = tmp15 * tmp15
tmp17 = tmp14 + tmp16
tmp18 = tmp5 - tmp10
tmp19 = tmp18 * tmp18
tmp20 = tmp17 + tmp19
tmp21 = tmp7 - tmp10
tmp22 = tmp21 * tmp21
tmp23 = tmp20 + tmp22
tmp24 = 3.0
tmp25 = tmp23 / tmp24
tmp26 = libdevice.sqrt(tmp25)
tmp27 = 1e-06
tmp28 = tmp26 + tmp27
tmp29 = tmp12 / tmp28
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x2, tmp31, xmask)
@triton.jit
def triton_poi_fused_mul_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
x3 = xindex % 256
x4 = xindex // 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x5, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 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, (3, 4), (4, 1))
assert_size_stride(primals_6, (3,), (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_std_sub_0[grid(256)](primals_3,
primals_2, primals_4, buf0, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_3
del primals_4
buf1 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_mul_1[grid(1024)](buf0, primals_1, buf1, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
del buf0
buf2 = empty_strided_cuda((256, 3), (3, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf1, (256, 4),
(4, 1), 0), reinterpret_tensor(primals_5, (4, 3), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_6
return reinterpret_tensor(buf2, (4, 4, 4, 4, 3), (192, 48, 12, 3, 1), 0
), primals_1, primals_2, reinterpret_tensor(buf1, (256, 4), (4, 1), 0
), primals_5
class LayerNorm(nn.Module):
"""Construct a layernorm module (See citation for details)."""
def __init__(self, features, eps=1e-06):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class PositionGeneratorNew(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, d_model):
super(PositionGeneratorNew, self).__init__()
self.norm = LayerNorm(d_model)
self.proj = nn.Linear(d_model, 3)
def forward(self, input_0, input_1):
primals_3 = self.norm.a_2
primals_4 = self.norm.b_2
primals_5 = self.proj.weight
primals_6 = self.proj.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
nigelnnk/MATCh-sensitivity
|
PositionGenerator
| false
| 7,336
|
[
"MIT"
] | 1
|
aaf2b924ac98c8c5925bbf431481724d11a102f8
|
https://github.com/nigelnnk/MATCh-sensitivity/tree/aaf2b924ac98c8c5925bbf431481724d11a102f8
|
EdgeFeaturesLayer
|
import torch
import torch.nn as nn
class EdgeFeaturesLayer(nn.Module):
def __init__(self, d_model, d_edge, h, dropout):
super(EdgeFeaturesLayer, self).__init__()
assert d_model % h == 0
d_model // h
self.linear = nn.Linear(d_edge, 1, bias=False)
with torch.no_grad():
self.linear.weight.fill_(0.25)
def forward(self, x):
p_edge = x.permute(0, 2, 3, 1)
p_edge = self.linear(p_edge).permute(0, 3, 1, 2)
return torch.relu(p_edge)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'd_edge': 4, 'h': 4, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_1, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 1), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 1, 4, 4), (16, 1, 4, 1), 0)
del buf1
buf3 = empty_strided_cuda((4, 1, 4, 4), (16, 1, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf2, buf3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
return buf2, reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf3
class EdgeFeaturesLayerNew(nn.Module):
def __init__(self, d_model, d_edge, h, dropout):
super(EdgeFeaturesLayerNew, self).__init__()
assert d_model % h == 0
d_model // h
self.linear = nn.Linear(d_edge, 1, bias=False)
with torch.no_grad():
self.linear.weight.fill_(0.25)
def forward(self, input_0):
primals_2 = self.linear.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
nigelnnk/MATCh-sensitivity
|
EdgeFeaturesLayer
| false
| 7,337
|
[
"MIT"
] | 1
|
aaf2b924ac98c8c5925bbf431481724d11a102f8
|
https://github.com/nigelnnk/MATCh-sensitivity/tree/aaf2b924ac98c8c5925bbf431481724d11a102f8
|
Generator
|
import math
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
"""Construct a layernorm module (See citation for details)."""
def __init__(self, features, eps=1e-06):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class ScaleNorm(nn.Module):
"""ScaleNorm"""
"""All g’s in SCALE NORM are initialized to sqrt(d)"""
def __init__(self, scale, eps=1e-05):
super(ScaleNorm, self).__init__()
self.scale = nn.Parameter(torch.tensor(math.sqrt(scale)))
self.eps = eps
def forward(self, x):
norm = self.scale / torch.norm(x, dim=-1, keepdim=True).clamp(min=
self.eps)
return x * norm
class Generator(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, d_model, aggregation_type='mean', n_output=1,
n_layers=1, leaky_relu_slope=0.01, dropout=0.0, scale_norm=False):
super(Generator, self).__init__()
if n_layers == 1:
self.proj = nn.Linear(d_model, n_output)
else:
self.proj = []
for i in range(n_layers - 1):
self.proj.append(nn.Linear(d_model, d_model))
self.proj.append(nn.LeakyReLU(leaky_relu_slope))
self.proj.append(ScaleNorm(d_model) if scale_norm else
LayerNorm(d_model))
self.proj.append(nn.Dropout(dropout))
self.proj.append(nn.Linear(d_model, n_output))
self.proj = torch.nn.Sequential(*self.proj)
self.aggregation_type = aggregation_type
def forward(self, x, mask):
mask = mask.unsqueeze(-1).float()
out_masked = x * mask
if self.aggregation_type == 'mean':
out_sum = out_masked.sum(dim=1)
mask_sum = mask.sum(dim=1)
out_avg_pooling = out_sum / mask_sum
elif self.aggregation_type == 'sum':
out_sum = out_masked.sum(dim=1)
out_avg_pooling = out_sum
elif self.aggregation_type == 'dummy_node':
out_avg_pooling = out_masked[:, 0]
projected = self.proj(out_avg_pooling)
return projected
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_div_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 64
x1 = xindex // 4 % 16
x2 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (64 + x3), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (16 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (128 + x3), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (32 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (192 + x3), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + (48 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tmp15 = tmp1 + tmp4
tmp16 = tmp15 + tmp8
tmp17 = tmp16 + tmp12
tmp18 = tmp14 / tmp17
tl.store(out_ptr0 + x4, tmp18, 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, (1, 4), (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, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_mul_sum_0[grid(256)](primals_2, primals_1,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_3, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_3
del primals_4
return reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class LayerNorm(nn.Module):
"""Construct a layernorm module (See citation for details)."""
def __init__(self, features, eps=1e-06):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class ScaleNorm(nn.Module):
"""ScaleNorm"""
"""All g’s in SCALE NORM are initialized to sqrt(d)"""
def __init__(self, scale, eps=1e-05):
super(ScaleNorm, self).__init__()
self.scale = nn.Parameter(torch.tensor(math.sqrt(scale)))
self.eps = eps
def forward(self, x):
norm = self.scale / torch.norm(x, dim=-1, keepdim=True).clamp(min=
self.eps)
return x * norm
class GeneratorNew(nn.Module):
"""Define standard linear + softmax generation step."""
def __init__(self, d_model, aggregation_type='mean', n_output=1,
n_layers=1, leaky_relu_slope=0.01, dropout=0.0, scale_norm=False):
super(GeneratorNew, self).__init__()
if n_layers == 1:
self.proj = nn.Linear(d_model, n_output)
else:
self.proj = []
for i in range(n_layers - 1):
self.proj.append(nn.Linear(d_model, d_model))
self.proj.append(nn.LeakyReLU(leaky_relu_slope))
self.proj.append(ScaleNorm(d_model) if scale_norm else
LayerNorm(d_model))
self.proj.append(nn.Dropout(dropout))
self.proj.append(nn.Linear(d_model, n_output))
self.proj = torch.nn.Sequential(*self.proj)
self.aggregation_type = aggregation_type
def forward(self, input_0, input_1):
primals_3 = self.proj.weight
primals_4 = self.proj.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
nigelnnk/MATCh-sensitivity
|
Generator
| false
| 7,338
|
[
"MIT"
] | 1
|
aaf2b924ac98c8c5925bbf431481724d11a102f8
|
https://github.com/nigelnnk/MATCh-sensitivity/tree/aaf2b924ac98c8c5925bbf431481724d11a102f8
|
SqueezeNet
|
import copy
import torch
import torch.nn as nn
import torch.utils.data
from torchvision.models.squeezenet import squeezenet1_0
from torchvision.models.squeezenet import squeezenet1_1
import torch.nn.modules.activation
class GramMatrix(nn.Module):
def forward(self, x):
b, c, h, w = x.size()
F = x.view(b, c, h * w)
G = torch.bmm(F, F.transpose(1, 2))
G.div_(h * w)
return G
class GramDiag(nn.Module):
"""
docstring for GramDiag
"""
def __init__(self, gram_diagonal_squared=False):
super().__init__()
self.__gram_diagonal_squared = gram_diagonal_squared
def forward(self, x):
b, c, h, w = x.size()
x = x.view(b, c, 1, h * w)
gram_diag = None
for b in range(x.size(0)):
if self.__gram_diagonal_squared:
z = torch.bmm(x[b] * x[b], (x[b] * x[b]).transpose(2, 1))
else:
z = torch.bmm(x[b], x[b].transpose(2, 1))
if isinstance(gram_diag, torch.Tensor):
gram_diag = torch.cat(gram_diag, z)
else:
gram_diag = z
gram_diag = torch.squeeze(gram_diag).unsqueeze(0)
return gram_diag.div_(h * w)
class SqueezeNet(nn.Module):
def __init__(self, version=1.0, num_classes=1000, pretrained=False,
layer='', gram=False, gram_diag=False, gram_diagonal_squared=False):
super().__init__()
if version not in [1.0, 1.1]:
raise ValueError(
'Unsupported SqueezeNet version {version}:1.0 or 1.1 expected'
.format(version=version))
self.num_classes = num_classes
if version == 1.0:
pytorch_squeeze = squeezenet1_0(pretrained, num_classes=num_classes
)
features_names = ['conv_1', 'relu_1', 'maxpool_1', 'fire_2',
'fire_3', 'fire_4', 'maxpool_4', 'fire_5', 'fire_6',
'fire_7', 'fire_8', 'maxpool_8', 'fire_9']
else:
pytorch_squeeze = squeezenet1_1(pretrained, num_classes=num_classes
)
features_names = ['conv_1', 'relu_1', 'maxpool_1', 'fire_2',
'fire_3', 'maxpool_3', 'fire_4', 'fire_5', 'maxpool_5',
'fire_6', 'fire_7', 'fire_8', 'fire_9']
classifier_names = ['drop_10', 'conv_10', 'relu_10', 'avgpool_10']
self.features = torch.nn.Sequential()
for name, module in zip(features_names, pytorch_squeeze.features):
self.features.add_module(name, copy.deepcopy(module))
if layer is name:
break
if len(features_names) == len(self.features
) and layer != features_names[-1]:
for name, module in zip(classifier_names, pytorch_squeeze.
classifier):
self.features.add_module(name, copy.deepcopy(module))
if layer is name:
break
del pytorch_squeeze
if gram:
self.features.add_module('gram matrix', GramMatrix())
elif gram_diag:
self.features.add_module('gram diagonal', GramDiag(
gram_diagonal_squared))
def forward(self, x):
return self.features(x)
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import copy
import torch.nn as nn
import torch.utils.data
from torchvision.models.squeezenet import squeezenet1_0
from torchvision.models.squeezenet import squeezenet1_1
import torch.nn.modules.activation
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 = 288
xnumel = 49
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 49 * y3), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 147 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 12
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 16
y1 = yindex // 16
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 16 * x2 + 144 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 32
y1 = yindex // 32
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 32 * x2 + 288 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 48
y1 = yindex // 48
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 48 * x2 + 432 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 322944
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 96
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_max_pool2d_with_indices_7(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 75264
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 96
x1 = xindex // 96 % 14
x2 = xindex // 1344 % 14
x3 = xindex // 18816
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 192 * x1 + 5568 * x2 + 80736 * x3), xmask)
tmp1 = tl.load(in_ptr0 + (96 + x0 + 192 * x1 + 5568 * x2 + 80736 * x3),
xmask)
tmp3 = tl.load(in_ptr0 + (192 + x0 + 192 * x1 + 5568 * x2 + 80736 * x3),
xmask)
tmp5 = tl.load(in_ptr0 + (2784 + x0 + 192 * x1 + 5568 * x2 + 80736 * x3
), xmask)
tmp7 = tl.load(in_ptr0 + (2880 + x0 + 192 * x1 + 5568 * x2 + 80736 * x3
), xmask)
tmp9 = tl.load(in_ptr0 + (2976 + x0 + 192 * x1 + 5568 * x2 + 80736 * x3
), xmask)
tmp11 = tl.load(in_ptr0 + (5568 + x0 + 192 * x1 + 5568 * x2 + 80736 *
x3), xmask)
tmp13 = tl.load(in_ptr0 + (5664 + x0 + 192 * x1 + 5568 * x2 + 80736 *
x3), xmask)
tmp15 = tl.load(in_ptr0 + (5760 + x0 + 192 * x1 + 5568 * x2 + 80736 *
x3), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp17 = tmp1 > tmp0
tmp18 = tl.full([1], 1, tl.int8)
tmp19 = tl.full([1], 0, tl.int8)
tmp20 = tl.where(tmp17, tmp18, tmp19)
tmp21 = tmp3 > tmp2
tmp22 = tl.full([1], 2, tl.int8)
tmp23 = tl.where(tmp21, tmp22, tmp20)
tmp24 = tmp5 > tmp4
tmp25 = tl.full([1], 3, tl.int8)
tmp26 = tl.where(tmp24, tmp25, tmp23)
tmp27 = tmp7 > tmp6
tmp28 = tl.full([1], 4, tl.int8)
tmp29 = tl.where(tmp27, tmp28, tmp26)
tmp30 = tmp9 > tmp8
tmp31 = tl.full([1], 5, tl.int8)
tmp32 = tl.where(tmp30, tmp31, tmp29)
tmp33 = tmp11 > tmp10
tmp34 = tl.full([1], 6, tl.int8)
tmp35 = tl.where(tmp33, tmp34, tmp32)
tmp36 = tmp13 > tmp12
tmp37 = tl.full([1], 7, tl.int8)
tmp38 = tl.where(tmp36, tmp37, tmp35)
tmp39 = tmp15 > tmp14
tmp40 = tl.full([1], 8, tl.int8)
tmp41 = tl.where(tmp39, tmp40, tmp38)
tl.store(out_ptr0 + x4, tmp16, xmask)
tl.store(out_ptr1 + x4, tmp41, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_8(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 12544
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 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_cat_9(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)
x0 = xindex % 128
x1 = xindex // 128
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 64, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (64 * x1 + x0), tmp4, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, 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], 128, tl.int64)
tmp15 = tl.load(in_ptr2 + (64 * x1 + (-64 + x0)), tmp12,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-64 + x0), 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 + x2, tmp21, None)
@triton.jit
def triton_poi_fused_convolution_relu_10(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 25088
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_cat_11(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)
x0 = xindex % 256
x1 = xindex // 256
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 128, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (128 * x1 + x0), tmp4, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, 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], 256, tl.int64)
tmp15 = tl.load(in_ptr2 + (128 * x1 + (-128 + x0)), tmp12,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-128 + x0), 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 + x2, tmp21, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_12(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 50176
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 1792 % 7
x1 = xindex // 256 % 7
x0 = xindex % 256
x5 = xindex // 1792
x6 = xindex
tmp0 = 2 * x2
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 14, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = 2 * x1
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (x0 + 512 * x1 + 7168 * x5), tmp10 & xmask,
other=float('-inf'))
tmp12 = 1 + 2 * x1
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (256 + x0 + 512 * x1 + 7168 * x5), tmp16 &
xmask, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 2 + 2 * x1
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (512 + x0 + 512 * x1 + 7168 * x5), tmp23 &
xmask, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = 1 + 2 * x2
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (3584 + x0 + 512 * x1 + 7168 * x5), tmp30 &
xmask, other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + (3840 + x0 + 512 * x1 + 7168 * x5), tmp33 &
xmask, other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (4096 + x0 + 512 * x1 + 7168 * x5), tmp36 &
xmask, other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = 2 + 2 * x2
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (7168 + x0 + 512 * x1 + 7168 * x5), tmp43 &
xmask, other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp38)
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (7424 + x0 + 512 * x1 + 7168 * x5), tmp46 &
xmask, other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (7680 + x0 + 512 * x1 + 7168 * x5), tmp49 &
xmask, other=float('-inf'))
tmp51 = triton_helpers.maximum(tmp50, tmp48)
tmp52 = tmp17 > tmp11
tmp53 = tl.full([1], 1, tl.int8)
tmp54 = tl.full([1], 0, tl.int8)
tmp55 = tl.where(tmp52, tmp53, tmp54)
tmp56 = tmp24 > tmp18
tmp57 = tl.full([1], 2, tl.int8)
tmp58 = tl.where(tmp56, tmp57, tmp55)
tmp59 = tmp31 > tmp25
tmp60 = tl.full([1], 3, tl.int8)
tmp61 = tl.where(tmp59, tmp60, tmp58)
tmp62 = tmp34 > tmp32
tmp63 = tl.full([1], 4, tl.int8)
tmp64 = tl.where(tmp62, tmp63, tmp61)
tmp65 = tmp37 > tmp35
tmp66 = tl.full([1], 5, tl.int8)
tmp67 = tl.where(tmp65, tmp66, tmp64)
tmp68 = tmp44 > tmp38
tmp69 = tl.full([1], 6, tl.int8)
tmp70 = tl.where(tmp68, tmp69, tmp67)
tmp71 = tmp47 > tmp45
tmp72 = tl.full([1], 7, tl.int8)
tmp73 = tl.where(tmp71, tmp72, tmp70)
tmp74 = tmp50 > tmp48
tmp75 = tl.full([1], 8, tl.int8)
tmp76 = tl.where(tmp74, tmp75, tmp73)
tl.store(out_ptr0 + x6, tmp51, xmask)
tl.store(out_ptr1 + x6, tmp76, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_13(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 6272
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_cat_14(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 50176
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 256
x1 = xindex // 256
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 128, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (128 * x1 + x0), tmp4 & xmask, eviction_policy
='evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tl.full([1], 256, tl.int64)
tmp15 = tl.load(in_ptr2 + (128 * x1 + (-128 + x0)), tmp12 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-128 + x0), tmp12 & xmask, 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 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_15(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 9408
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 48
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_cat_16(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 75264
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 384
x1 = xindex // 384
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 192, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (192 * x1 + x0), tmp4 & xmask, eviction_policy
='evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full([1], 0, tl.int32)
tmp9 = triton_helpers.maximum(tmp8, tmp7)
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp4, tmp9, tmp10)
tmp12 = tmp0 >= tmp3
tl.full([1], 384, tl.int64)
tmp15 = tl.load(in_ptr2 + (192 * x1 + (-192 + x0)), tmp12 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-192 + x0), tmp12 & xmask, 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 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_17(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 12544
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_poi_fused_cat_18(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)
x0 = xindex % 512
x1 = xindex // 512
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 256, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (256 * x1 + x0), tmp4, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, 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], 512, tl.int64)
tmp15 = tl.load(in_ptr2 + (256 * x1 + (-256 + x0)), tmp12,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-256 + x0), 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 + x2, tmp21, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_19(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 % 512
x1 = xindex // 512 % 3
x2 = xindex // 1536 % 3
x3 = xindex // 4608
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 1024 * x1 + 7168 * x2 + 25088 * x3), None)
tmp1 = tl.load(in_ptr0 + (512 + x0 + 1024 * x1 + 7168 * x2 + 25088 * x3
), None)
tmp3 = tl.load(in_ptr0 + (1024 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp5 = tl.load(in_ptr0 + (3584 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp7 = tl.load(in_ptr0 + (4096 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp9 = tl.load(in_ptr0 + (4608 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp11 = tl.load(in_ptr0 + (7168 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp13 = tl.load(in_ptr0 + (7680 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp15 = tl.load(in_ptr0 + (8192 + x0 + 1024 * x1 + 7168 * x2 + 25088 *
x3), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp17 = tmp1 > tmp0
tmp18 = tl.full([1], 1, tl.int8)
tmp19 = tl.full([1], 0, tl.int8)
tmp20 = tl.where(tmp17, tmp18, tmp19)
tmp21 = tmp3 > tmp2
tmp22 = tl.full([1], 2, tl.int8)
tmp23 = tl.where(tmp21, tmp22, tmp20)
tmp24 = tmp5 > tmp4
tmp25 = tl.full([1], 3, tl.int8)
tmp26 = tl.where(tmp24, tmp25, tmp23)
tmp27 = tmp7 > tmp6
tmp28 = tl.full([1], 4, tl.int8)
tmp29 = tl.where(tmp27, tmp28, tmp26)
tmp30 = tmp9 > tmp8
tmp31 = tl.full([1], 5, tl.int8)
tmp32 = tl.where(tmp30, tmp31, tmp29)
tmp33 = tmp11 > tmp10
tmp34 = tl.full([1], 6, tl.int8)
tmp35 = tl.where(tmp33, tmp34, tmp32)
tmp36 = tmp13 > tmp12
tmp37 = tl.full([1], 7, tl.int8)
tmp38 = tl.where(tmp36, tmp37, tmp35)
tmp39 = tmp15 > tmp14
tmp40 = tl.full([1], 8, tl.int8)
tmp41 = tl.where(tmp39, tmp40, tmp38)
tl.store(out_ptr0 + x4, tmp16, None)
tl.store(out_ptr1 + x4, tmp41, None)
@triton.jit
def triton_poi_fused_convolution_relu_20(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 2304
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_poi_fused_cat_21(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)
x0 = xindex % 512
x1 = xindex // 512
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 256, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (256 * x1 + x0), tmp4, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + x0, 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], 512, tl.int64)
tmp15 = tl.load(in_ptr2 + (256 * x1 + (-256 + x0)), tmp12,
eviction_policy='evict_last', other=0.0)
tmp16 = tl.load(in_ptr3 + (-256 + x0), 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 + x2, tmp21, None)
@triton.jit
def triton_per_fused_convolution_mean_relu_22(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4000
rnumel = 9
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 % 1000
x1 = xindex // 1000
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 1000 * r2 + 9000 * x1), rmask & xmask,
other=0.0)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.where(rmask & xmask, tmp5, 0)
tmp8 = tl.sum(tmp7, 1)[:, None]
tmp9 = 9.0
tmp10 = tmp8 / tmp9
tl.debug_barrier()
tl.store(in_out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_23(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 36000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 1000
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_24(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 9216
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_25(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 50176
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_26(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 37632
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 192
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_27(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 25088
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_28(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)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + 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(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_29(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 50176
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, 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, (96, 3, 7, 7), (147, 49, 7, 1))
assert_size_stride(primals_2, (96,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (16, 96, 1, 1), (96, 1, 1, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (64, 16, 1, 1), (16, 1, 1, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (64, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (16, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (64, 16, 1, 1), (16, 1, 1, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (64, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_15, (64,), (1,))
assert_size_stride(primals_16, (32, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_17, (32,), (1,))
assert_size_stride(primals_18, (128, 32, 1, 1), (32, 1, 1, 1))
assert_size_stride(primals_19, (128,), (1,))
assert_size_stride(primals_20, (128, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_21, (128,), (1,))
assert_size_stride(primals_22, (32, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_23, (32,), (1,))
assert_size_stride(primals_24, (128, 32, 1, 1), (32, 1, 1, 1))
assert_size_stride(primals_25, (128,), (1,))
assert_size_stride(primals_26, (128, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_27, (128,), (1,))
assert_size_stride(primals_28, (48, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_29, (48,), (1,))
assert_size_stride(primals_30, (192, 48, 1, 1), (48, 1, 1, 1))
assert_size_stride(primals_31, (192,), (1,))
assert_size_stride(primals_32, (192, 48, 3, 3), (432, 9, 3, 1))
assert_size_stride(primals_33, (192,), (1,))
assert_size_stride(primals_34, (48, 384, 1, 1), (384, 1, 1, 1))
assert_size_stride(primals_35, (48,), (1,))
assert_size_stride(primals_36, (192, 48, 1, 1), (48, 1, 1, 1))
assert_size_stride(primals_37, (192,), (1,))
assert_size_stride(primals_38, (192, 48, 3, 3), (432, 9, 3, 1))
assert_size_stride(primals_39, (192,), (1,))
assert_size_stride(primals_40, (64, 384, 1, 1), (384, 1, 1, 1))
assert_size_stride(primals_41, (64,), (1,))
assert_size_stride(primals_42, (256, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_43, (256,), (1,))
assert_size_stride(primals_44, (256, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_45, (256,), (1,))
assert_size_stride(primals_46, (64, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_47, (64,), (1,))
assert_size_stride(primals_48, (256, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_49, (256,), (1,))
assert_size_stride(primals_50, (256, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_51, (256,), (1,))
assert_size_stride(primals_52, (1000, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_53, (1000,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((96, 3, 7, 7), (147, 1, 21, 3), torch.float32
)
get_raw_stream(0)
triton_poi_fused_0[grid(288, 49)](primals_1, buf0, 288, 49, XBLOCK=
32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch
.float32)
triton_poi_fused_1[grid(12, 4096)](primals_3, buf1, 12, 4096,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 16, 3, 3), (144, 1, 48, 16), torch.
float32)
triton_poi_fused_2[grid(1024, 9)](primals_8, buf2, 1024, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf3 = empty_strided_cuda((64, 16, 3, 3), (144, 1, 48, 16), torch.
float32)
triton_poi_fused_2[grid(1024, 9)](primals_14, buf3, 1024, 9, XBLOCK
=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_14
buf4 = empty_strided_cuda((128, 32, 3, 3), (288, 1, 96, 32), torch.
float32)
triton_poi_fused_3[grid(4096, 9)](primals_20, buf4, 4096, 9, XBLOCK
=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_20
buf5 = empty_strided_cuda((128, 32, 3, 3), (288, 1, 96, 32), torch.
float32)
triton_poi_fused_3[grid(4096, 9)](primals_26, buf5, 4096, 9, XBLOCK
=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_26
buf6 = empty_strided_cuda((192, 48, 3, 3), (432, 1, 144, 48), torch
.float32)
triton_poi_fused_4[grid(9216, 9)](primals_32, buf6, 9216, 9, XBLOCK
=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_32
buf7 = empty_strided_cuda((192, 48, 3, 3), (432, 1, 144, 48), torch
.float32)
triton_poi_fused_4[grid(9216, 9)](primals_38, buf7, 9216, 9, XBLOCK
=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_38
buf8 = empty_strided_cuda((256, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_5[grid(16384, 9)](primals_44, buf8, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_44
buf9 = empty_strided_cuda((256, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_5[grid(16384, 9)](primals_50, buf9, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_50
buf10 = extern_kernels.convolution(buf1, buf0, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 96, 29, 29), (80736, 1, 2784, 96))
buf11 = buf10
del buf10
triton_poi_fused_convolution_relu_6[grid(322944)](buf11, primals_2,
322944, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf12 = empty_strided_cuda((4, 96, 14, 14), (18816, 1, 1344, 96),
torch.float32)
buf13 = empty_strided_cuda((4, 96, 14, 14), (18816, 1, 1344, 96),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_7[grid(75264)](buf11,
buf12, buf13, 75264, XBLOCK=512, num_warps=8, num_stages=1)
buf14 = extern_kernels.convolution(buf12, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 16, 14, 14), (3136, 1, 224, 16))
buf15 = buf14
del buf14
triton_poi_fused_convolution_relu_8[grid(12544)](buf15, primals_5,
12544, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf16 = extern_kernels.convolution(buf15, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 64, 14, 14), (12544, 1, 896, 64))
buf17 = extern_kernels.convolution(buf15, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 64, 14, 14), (12544, 1, 896, 64))
buf18 = empty_strided_cuda((4, 128, 14, 14), (25088, 1, 1792, 128),
torch.float32)
triton_poi_fused_cat_9[grid(100352)](buf16, primals_7, buf17,
primals_9, buf18, 100352, XBLOCK=512, num_warps=8, num_stages=1)
buf19 = extern_kernels.convolution(buf18, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 16, 14, 14), (3136, 1, 224, 16))
buf20 = buf19
del buf19
triton_poi_fused_convolution_relu_8[grid(12544)](buf20, primals_11,
12544, XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf21 = extern_kernels.convolution(buf20, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf21, (4, 64, 14, 14), (12544, 1, 896, 64))
buf22 = extern_kernels.convolution(buf20, buf3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf22, (4, 64, 14, 14), (12544, 1, 896, 64))
buf23 = empty_strided_cuda((4, 128, 14, 14), (25088, 1, 1792, 128),
torch.float32)
triton_poi_fused_cat_9[grid(100352)](buf21, primals_13, buf22,
primals_15, buf23, 100352, XBLOCK=512, num_warps=8, num_stages=1)
buf24 = extern_kernels.convolution(buf23, primals_16, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf24, (4, 32, 14, 14), (6272, 1, 448, 32))
buf25 = buf24
del buf24
triton_poi_fused_convolution_relu_10[grid(25088)](buf25, primals_17,
25088, XBLOCK=256, num_warps=4, num_stages=1)
del primals_17
buf26 = extern_kernels.convolution(buf25, primals_18, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf26, (4, 128, 14, 14), (25088, 1, 1792, 128))
buf27 = extern_kernels.convolution(buf25, buf4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 128, 14, 14), (25088, 1, 1792, 128))
buf28 = empty_strided_cuda((4, 256, 14, 14), (50176, 1, 3584, 256),
torch.float32)
triton_poi_fused_cat_11[grid(200704)](buf26, primals_19, buf27,
primals_21, buf28, 200704, XBLOCK=512, num_warps=8, num_stages=1)
buf29 = empty_strided_cuda((4, 256, 7, 7), (12544, 1, 1792, 256),
torch.float32)
buf30 = empty_strided_cuda((4, 256, 7, 7), (12544, 1, 1792, 256),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_12[grid(50176)](buf28,
buf29, buf30, 50176, XBLOCK=256, num_warps=4, num_stages=1)
buf31 = extern_kernels.convolution(buf29, primals_22, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf31, (4, 32, 7, 7), (1568, 1, 224, 32))
buf32 = buf31
del buf31
triton_poi_fused_convolution_relu_13[grid(6272)](buf32, primals_23,
6272, XBLOCK=256, num_warps=4, num_stages=1)
del primals_23
buf33 = extern_kernels.convolution(buf32, primals_24, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf33, (4, 128, 7, 7), (6272, 1, 896, 128))
buf34 = extern_kernels.convolution(buf32, buf5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf34, (4, 128, 7, 7), (6272, 1, 896, 128))
buf35 = empty_strided_cuda((4, 256, 7, 7), (12544, 1, 1792, 256),
torch.float32)
triton_poi_fused_cat_14[grid(50176)](buf33, primals_25, buf34,
primals_27, buf35, 50176, XBLOCK=512, num_warps=4, num_stages=1)
buf36 = extern_kernels.convolution(buf35, primals_28, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf36, (4, 48, 7, 7), (2352, 1, 336, 48))
buf37 = buf36
del buf36
triton_poi_fused_convolution_relu_15[grid(9408)](buf37, primals_29,
9408, XBLOCK=256, num_warps=4, num_stages=1)
del primals_29
buf38 = extern_kernels.convolution(buf37, primals_30, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf38, (4, 192, 7, 7), (9408, 1, 1344, 192))
buf39 = extern_kernels.convolution(buf37, buf6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf39, (4, 192, 7, 7), (9408, 1, 1344, 192))
buf40 = empty_strided_cuda((4, 384, 7, 7), (18816, 1, 2688, 384),
torch.float32)
triton_poi_fused_cat_16[grid(75264)](buf38, primals_31, buf39,
primals_33, buf40, 75264, XBLOCK=512, num_warps=8, num_stages=1)
buf41 = extern_kernels.convolution(buf40, primals_34, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf41, (4, 48, 7, 7), (2352, 1, 336, 48))
buf42 = buf41
del buf41
triton_poi_fused_convolution_relu_15[grid(9408)](buf42, primals_35,
9408, XBLOCK=256, num_warps=4, num_stages=1)
del primals_35
buf43 = extern_kernels.convolution(buf42, primals_36, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf43, (4, 192, 7, 7), (9408, 1, 1344, 192))
buf44 = extern_kernels.convolution(buf42, buf7, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf44, (4, 192, 7, 7), (9408, 1, 1344, 192))
buf45 = empty_strided_cuda((4, 384, 7, 7), (18816, 1, 2688, 384),
torch.float32)
triton_poi_fused_cat_16[grid(75264)](buf43, primals_37, buf44,
primals_39, buf45, 75264, XBLOCK=512, num_warps=8, num_stages=1)
buf46 = extern_kernels.convolution(buf45, primals_40, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf46, (4, 64, 7, 7), (3136, 1, 448, 64))
buf47 = buf46
del buf46
triton_poi_fused_convolution_relu_17[grid(12544)](buf47, primals_41,
12544, XBLOCK=256, num_warps=4, num_stages=1)
del primals_41
buf48 = extern_kernels.convolution(buf47, primals_42, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf48, (4, 256, 7, 7), (12544, 1, 1792, 256))
buf49 = extern_kernels.convolution(buf47, buf8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf49, (4, 256, 7, 7), (12544, 1, 1792, 256))
buf50 = empty_strided_cuda((4, 512, 7, 7), (25088, 1, 3584, 512),
torch.float32)
triton_poi_fused_cat_18[grid(100352)](buf48, primals_43, buf49,
primals_45, buf50, 100352, XBLOCK=512, num_warps=8, num_stages=1)
buf51 = empty_strided_cuda((4, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
buf52 = empty_strided_cuda((4, 512, 3, 3), (4608, 1, 1536, 512),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_19[grid(18432)](buf50,
buf51, buf52, 18432, XBLOCK=256, num_warps=4, num_stages=1)
buf53 = extern_kernels.convolution(buf51, primals_46, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf53, (4, 64, 3, 3), (576, 1, 192, 64))
buf54 = buf53
del buf53
triton_poi_fused_convolution_relu_20[grid(2304)](buf54, primals_47,
2304, XBLOCK=256, num_warps=4, num_stages=1)
del primals_47
buf55 = extern_kernels.convolution(buf54, primals_48, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf55, (4, 256, 3, 3), (2304, 1, 768, 256))
buf56 = extern_kernels.convolution(buf54, buf9, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf56, (4, 256, 3, 3), (2304, 1, 768, 256))
buf57 = empty_strided_cuda((4, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_cat_21[grid(18432)](buf55, primals_49, buf56,
primals_51, buf57, 18432, XBLOCK=256, num_warps=4, num_stages=1)
buf58 = extern_kernels.convolution(buf57, primals_52, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf58, (4, 1000, 3, 3), (9000, 1, 3000, 1000))
buf59 = empty_strided_cuda((4, 1000, 1, 1), (1000, 1, 4000, 4000),
torch.float32)
buf60 = reinterpret_tensor(buf59, (4, 1000, 1, 1), (1000, 1, 1, 1), 0)
del buf59
triton_per_fused_convolution_mean_relu_22[grid(4000)](buf60, buf58,
primals_53, 4000, 9, XBLOCK=32, num_warps=4, num_stages=1)
buf61 = empty_strided_cuda((4, 1000, 3, 3), (9000, 1, 3000, 1000),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_23[grid(36000)](
buf58, primals_53, buf61, 36000, XBLOCK=256, num_warps=4,
num_stages=1)
del buf58
del primals_53
buf62 = empty_strided_cuda((4, 256, 3, 3), (2304, 1, 768, 256),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_24[grid(9216)](
buf56, primals_51, buf62, 9216, XBLOCK=128, num_warps=4,
num_stages=1)
del buf56
del primals_51
buf63 = empty_strided_cuda((4, 256, 3, 3), (2304, 1, 768, 256),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_24[grid(9216)](
buf55, primals_49, buf63, 9216, XBLOCK=128, num_warps=4,
num_stages=1)
del buf55
del primals_49
buf64 = empty_strided_cuda((4, 256, 7, 7), (12544, 1, 1792, 256),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_25[grid(50176)](
buf49, primals_45, buf64, 50176, XBLOCK=512, num_warps=4,
num_stages=1)
del buf49
del primals_45
buf65 = empty_strided_cuda((4, 256, 7, 7), (12544, 1, 1792, 256),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_25[grid(50176)](
buf48, primals_43, buf65, 50176, XBLOCK=512, num_warps=4,
num_stages=1)
del buf48
del primals_43
buf66 = empty_strided_cuda((4, 192, 7, 7), (9408, 1, 1344, 192),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_26[grid(37632)](
buf44, primals_39, buf66, 37632, XBLOCK=512, num_warps=4,
num_stages=1)
del buf44
del primals_39
buf67 = empty_strided_cuda((4, 192, 7, 7), (9408, 1, 1344, 192),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_26[grid(37632)](
buf43, primals_37, buf67, 37632, XBLOCK=512, num_warps=4,
num_stages=1)
del buf43
del primals_37
buf68 = empty_strided_cuda((4, 192, 7, 7), (9408, 1, 1344, 192),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_26[grid(37632)](
buf39, primals_33, buf68, 37632, XBLOCK=512, num_warps=4,
num_stages=1)
del buf39
del primals_33
buf69 = empty_strided_cuda((4, 192, 7, 7), (9408, 1, 1344, 192),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_26[grid(37632)](
buf38, primals_31, buf69, 37632, XBLOCK=512, num_warps=4,
num_stages=1)
del buf38
del primals_31
buf70 = empty_strided_cuda((4, 128, 7, 7), (6272, 1, 896, 128),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_27[grid(25088)](
buf34, primals_27, buf70, 25088, XBLOCK=128, num_warps=4,
num_stages=1)
del buf34
del primals_27
buf71 = empty_strided_cuda((4, 128, 7, 7), (6272, 1, 896, 128),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_27[grid(25088)](
buf33, primals_25, buf71, 25088, XBLOCK=128, num_warps=4,
num_stages=1)
del buf33
del primals_25
buf72 = empty_strided_cuda((4, 128, 14, 14), (25088, 1, 1792, 128),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_28[grid(100352)](
buf27, primals_21, buf72, 100352, XBLOCK=1024, num_warps=4,
num_stages=1)
del buf27
del primals_21
buf73 = empty_strided_cuda((4, 128, 14, 14), (25088, 1, 1792, 128),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_28[grid(100352)](
buf26, primals_19, buf73, 100352, XBLOCK=1024, num_warps=4,
num_stages=1)
del buf26
del primals_19
buf74 = empty_strided_cuda((4, 64, 14, 14), (12544, 1, 896, 64),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_29[grid(50176)](
buf22, primals_15, buf74, 50176, XBLOCK=256, num_warps=4,
num_stages=1)
del buf22
del primals_15
buf75 = empty_strided_cuda((4, 64, 14, 14), (12544, 1, 896, 64),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_29[grid(50176)](
buf21, primals_13, buf75, 50176, XBLOCK=256, num_warps=4,
num_stages=1)
del buf21
del primals_13
buf76 = empty_strided_cuda((4, 64, 14, 14), (12544, 1, 896, 64),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_29[grid(50176)](
buf17, primals_9, buf76, 50176, XBLOCK=256, num_warps=4,
num_stages=1)
del buf17
del primals_9
buf77 = empty_strided_cuda((4, 64, 14, 14), (12544, 1, 896, 64),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_29[grid(50176)](
buf16, primals_7, buf77, 50176, XBLOCK=256, num_warps=4,
num_stages=1)
del buf16
del primals_7
return (buf60, buf0, buf1, primals_4, primals_6, buf2, primals_10,
primals_12, buf3, primals_16, primals_18, buf4, primals_22,
primals_24, buf5, primals_28, primals_30, buf6, primals_34,
primals_36, buf7, primals_40, primals_42, buf8, primals_46,
primals_48, buf9, primals_52, buf11, buf12, buf13, buf15, buf18,
buf20, buf23, buf25, buf28, buf29, buf30, buf32, buf35, buf37,
buf40, buf42, buf45, buf47, buf50, buf51, buf52, buf54, buf57,
buf61, buf62, buf63, buf64, buf65, buf66, buf67, buf68, buf69,
buf70, buf71, buf72, buf73, buf74, buf75, buf76, buf77)
class GramMatrix(nn.Module):
def forward(self, x):
b, c, h, w = x.size()
F = x.view(b, c, h * w)
G = torch.bmm(F, F.transpose(1, 2))
G.div_(h * w)
return G
class GramDiag(nn.Module):
"""
docstring for GramDiag
"""
def __init__(self, gram_diagonal_squared=False):
super().__init__()
self.__gram_diagonal_squared = gram_diagonal_squared
def forward(self, x):
b, c, h, w = x.size()
x = x.view(b, c, 1, h * w)
gram_diag = None
for b in range(x.size(0)):
if self.__gram_diagonal_squared:
z = torch.bmm(x[b] * x[b], (x[b] * x[b]).transpose(2, 1))
else:
z = torch.bmm(x[b], x[b].transpose(2, 1))
if isinstance(gram_diag, torch.Tensor):
gram_diag = torch.cat(gram_diag, z)
else:
gram_diag = z
gram_diag = torch.squeeze(gram_diag).unsqueeze(0)
return gram_diag.div_(h * w)
class SqueezeNetNew(nn.Module):
def __init__(self, version=1.0, num_classes=1000, pretrained=False,
layer='', gram=False, gram_diag=False, gram_diagonal_squared=False):
super().__init__()
if version not in [1.0, 1.1]:
raise ValueError(
'Unsupported SqueezeNet version {version}:1.0 or 1.1 expected'
.format(version=version))
self.num_classes = num_classes
if version == 1.0:
pytorch_squeeze = squeezenet1_0(pretrained, num_classes=num_classes
)
features_names = ['conv_1', 'relu_1', 'maxpool_1', 'fire_2',
'fire_3', 'fire_4', 'maxpool_4', 'fire_5', 'fire_6',
'fire_7', 'fire_8', 'maxpool_8', 'fire_9']
else:
pytorch_squeeze = squeezenet1_1(pretrained, num_classes=num_classes
)
features_names = ['conv_1', 'relu_1', 'maxpool_1', 'fire_2',
'fire_3', 'maxpool_3', 'fire_4', 'fire_5', 'maxpool_5',
'fire_6', 'fire_7', 'fire_8', 'fire_9']
classifier_names = ['drop_10', 'conv_10', 'relu_10', 'avgpool_10']
self.features = torch.nn.Sequential()
for name, module in zip(features_names, pytorch_squeeze.features):
self.features.add_module(name, copy.deepcopy(module))
if layer is name:
break
if len(features_names) == len(self.features
) and layer != features_names[-1]:
for name, module in zip(classifier_names, pytorch_squeeze.
classifier):
self.features.add_module(name, copy.deepcopy(module))
if layer is name:
break
del pytorch_squeeze
if gram:
self.features.add_module('gram matrix', GramMatrix())
elif gram_diag:
self.features.add_module('gram diagonal', GramDiag(
gram_diagonal_squared))
def forward(self, input_0):
primals_1 = self.features.conv_1.weight
primals_2 = self.features.conv_1.bias
primals_4 = self.features.fire_2.squeeze.weight
primals_5 = self.features.fire_2.squeeze.bias
primals_6 = self.features.fire_2.expand1x1.weight
primals_7 = self.features.fire_2.expand1x1.bias
primals_8 = self.features.fire_2.expand3x3.weight
primals_9 = self.features.fire_2.expand3x3.bias
primals_10 = self.features.fire_3.squeeze.weight
primals_11 = self.features.fire_3.squeeze.bias
primals_12 = self.features.fire_3.expand1x1.weight
primals_13 = self.features.fire_3.expand1x1.bias
primals_14 = self.features.fire_3.expand3x3.weight
primals_15 = self.features.fire_3.expand3x3.bias
primals_16 = self.features.fire_4.squeeze.weight
primals_17 = self.features.fire_4.squeeze.bias
primals_18 = self.features.fire_4.expand1x1.weight
primals_19 = self.features.fire_4.expand1x1.bias
primals_20 = self.features.fire_4.expand3x3.weight
primals_21 = self.features.fire_4.expand3x3.bias
primals_22 = self.features.fire_5.squeeze.weight
primals_23 = self.features.fire_5.squeeze.bias
primals_24 = self.features.fire_5.expand1x1.weight
primals_25 = self.features.fire_5.expand1x1.bias
primals_26 = self.features.fire_5.expand3x3.weight
primals_27 = self.features.fire_5.expand3x3.bias
primals_28 = self.features.fire_6.squeeze.weight
primals_29 = self.features.fire_6.squeeze.bias
primals_30 = self.features.fire_6.expand1x1.weight
primals_31 = self.features.fire_6.expand1x1.bias
primals_32 = self.features.fire_6.expand3x3.weight
primals_33 = self.features.fire_6.expand3x3.bias
primals_34 = self.features.fire_7.squeeze.weight
primals_35 = self.features.fire_7.squeeze.bias
primals_36 = self.features.fire_7.expand1x1.weight
primals_37 = self.features.fire_7.expand1x1.bias
primals_38 = self.features.fire_7.expand3x3.weight
primals_39 = self.features.fire_7.expand3x3.bias
primals_40 = self.features.fire_8.squeeze.weight
primals_41 = self.features.fire_8.squeeze.bias
primals_42 = self.features.fire_8.expand1x1.weight
primals_43 = self.features.fire_8.expand1x1.bias
primals_44 = self.features.fire_8.expand3x3.weight
primals_45 = self.features.fire_8.expand3x3.bias
primals_46 = self.features.fire_9.squeeze.weight
primals_47 = self.features.fire_9.squeeze.bias
primals_48 = self.features.fire_9.expand1x1.weight
primals_49 = self.features.fire_9.expand1x1.bias
primals_50 = self.features.fire_9.expand3x3.weight
primals_51 = self.features.fire_9.expand3x3.bias
primals_52 = self.features.conv_10.weight
primals_53 = self.features.conv_10.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
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]
|
matherm/ummon3
|
SqueezeNet
| false
| 7,339
|
[
"BSD-3-Clause"
] | 1
|
08476d21ce17cc95180525d48202a1690dfc8a08
|
https://github.com/matherm/ummon3/tree/08476d21ce17cc95180525d48202a1690dfc8a08
|
SequenceClassifier
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def transformer_weights_init(module, std_init_range=0.02, xavier=True):
"""
Initialize different weights in Transformer model.
Args:
module: torch.nn.Module to be initialized
std_init_range: standard deviation of normal initializer
xavier: if True, xavier initializer will be used in Linear layers
as was proposed in AIAYN paper, otherwise normal initializer
will be used (like in BERT paper)
"""
if isinstance(module, nn.Linear):
if xavier:
nn.init.xavier_uniform_(module.weight)
else:
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
if module.bias is not None:
nn.init.constant_(module.bias, 0.0)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
elif isinstance(module, nn.LayerNorm):
nn.init.constant_(module.weight, 1.0)
nn.init.constant_(module.bias, 0.0)
class SelfAttention(nn.Module):
def __init__(self, hidden_size, batch_first=True):
super(SelfAttention, self).__init__()
self.hidden_size = hidden_size
self.batch_first = batch_first
self.register_parameter('att_weights', nn.Parameter(torch.Tensor(1,
hidden_size), requires_grad=True))
nn.init.xavier_uniform_(self.att_weights.data)
def get_mask(self):
pass
def forward(self, hidden_states, attention_mask=None):
if self.batch_first:
batch_size, _max_len = hidden_states.size()[:2]
else:
_max_len, batch_size = hidden_states.size()[:2]
weights = torch.bmm(hidden_states, self.att_weights.permute(1, 0).
unsqueeze(0).repeat(batch_size, 1, 1))
attentions = F.softmax(torch.tanh(weights.squeeze()), dim=-1)
masked = attentions * attention_mask
if len(attentions.shape) == 1:
attentions = attentions.unsqueeze(0)
_sums = masked.sum(-1, keepdim=True).expand(attentions.shape)
attentions = masked.div(_sums)
weighted = torch.mul(hidden_states, attentions.unsqueeze(-1).
expand_as(hidden_states))
representations = weighted.sum(1).squeeze(dim=1)
return representations, attentions
class MultiLayerPerceptron(torch.nn.Module):
"""
A simple MLP that can either be used independently or put on top
of pretrained models (such as BERT) and act as a classifier.
Args:
hidden_size (int): the size of each layer
num_classes (int): number of output classes
num_layers (int): number of layers
activation (str): type of activations for layers in between
log_softmax (bool): whether to add a log_softmax layer before output
"""
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=2, activation: 'str'='relu', log_softmax: 'bool'=True):
super().__init__()
self.layers = 0
activations = {'relu': nn.ReLU(), 'gelu': nn.GELU(), 'sigmoid': nn.
Sigmoid(), 'tanh': nn.Tanh()}
for _ in range(num_layers - 1):
layer = torch.nn.Linear(hidden_size, hidden_size)
setattr(self, f'layer{self.layers}', layer)
setattr(self, f'layer{self.layers + 1}', activations[activation])
self.layers += 2
layer = torch.nn.Linear(hidden_size, num_classes)
setattr(self, f'layer{self.layers}', layer)
self.layers += 1
self.log_softmax = log_softmax
@property
def last_linear_layer(self):
return getattr(self, f'layer{self.layers - 1}')
def forward(self, hidden_states):
output_states = hidden_states[:]
for i in range(self.layers):
output_states = getattr(self, f'layer{i}')(output_states)
if self.log_softmax:
output_states = torch.log_softmax(output_states, dim=-1)
else:
output_states = torch.softmax(output_states, dim=-1)
return output_states
class SequenceClassifier(nn.Module):
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=2, activation: 'str'='relu', log_softmax: 'bool'=True,
dropout: 'float'=0.0, use_transformer_init: 'bool'=True, pooling:
'str'='mean', idx_conditioned_on: 'int'=None):
"""
Initializes the SequenceClassifier module.
Args:
hidden_size: the hidden size of the mlp head on the top of the encoder
num_classes: number of the classes to predict
num_layers: number of the linear layers of the mlp head on the top of the encoder
activation: type of activations between layers of the mlp head
log_softmax: applies the log softmax on the output
dropout: the dropout used for the mlp head
use_transformer_init: initializes the weights with the same approach used in Transformer
idx_conditioned_on: index of the token to use as the sequence representation for the classification task, default is the first token
"""
super().__init__()
self.log_softmax = log_softmax
self._idx_conditioned_on = idx_conditioned_on
self.pooling = pooling
self.mlp = MultiLayerPerceptron(hidden_size=hidden_size * 2 if
pooling == 'mean_max' else hidden_size, num_classes=num_classes,
num_layers=num_layers, activation=activation, log_softmax=
log_softmax)
self.dropout = nn.Dropout(dropout)
if use_transformer_init:
self.apply(lambda module: transformer_weights_init(module,
xavier=False))
if pooling == 'attention':
self.attention = SelfAttention(hidden_size)
def forward(self, hidden_states, attention_mask=None):
hidden_states = self.dropout(hidden_states)
if self.pooling == 'token':
pooled = hidden_states[:, self._idx_conditioned_on]
elif self.pooling == 'attention':
pooled, _att = self.attention(hidden_states, attention_mask)
else:
if attention_mask is None:
ct = hidden_states.shape[1]
else:
hidden_states = hidden_states * attention_mask.unsqueeze(2)
ct = torch.sum(attention_mask, axis=1).unsqueeze(1)
pooled_sum = torch.sum(hidden_states, axis=1)
if self.pooling == 'mean' or self.pooling == 'mean_max':
pooled_mean = torch.div(pooled_sum, ct)
if self.pooling == 'max' or self.pooling == 'mean_max':
pooled_max = torch.max(hidden_states, axis=1)[0]
pooled = (pooled_mean if self.pooling == 'mean' else pooled_max if
self.pooling == 'max' else torch.cat([pooled_mean,
pooled_max], axis=-1))
logits = self.mlp(pooled)
return logits, pooled
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4, 'num_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_div_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 % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, 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)
@triton.jit
def triton_poi_fused__log_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 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
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 = 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_div_sum_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
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(64)](buf2,
primals_3, buf6, 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
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_2[grid(64)](buf3, buf4, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0)
del buf3
triton_poi_fused__log_softmax_3[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf4
return buf5, buf0, reinterpret_tensor(buf0, (16, 4), (4, 1), 0
), reinterpret_tensor(buf2, (16, 4), (4, 1), 0), buf5, primals_4, buf6
def transformer_weights_init(module, std_init_range=0.02, xavier=True):
"""
Initialize different weights in Transformer model.
Args:
module: torch.nn.Module to be initialized
std_init_range: standard deviation of normal initializer
xavier: if True, xavier initializer will be used in Linear layers
as was proposed in AIAYN paper, otherwise normal initializer
will be used (like in BERT paper)
"""
if isinstance(module, nn.Linear):
if xavier:
nn.init.xavier_uniform_(module.weight)
else:
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
if module.bias is not None:
nn.init.constant_(module.bias, 0.0)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=std_init_range)
elif isinstance(module, nn.LayerNorm):
nn.init.constant_(module.weight, 1.0)
nn.init.constant_(module.bias, 0.0)
class SelfAttention(nn.Module):
def __init__(self, hidden_size, batch_first=True):
super(SelfAttention, self).__init__()
self.hidden_size = hidden_size
self.batch_first = batch_first
self.register_parameter('att_weights', nn.Parameter(torch.Tensor(1,
hidden_size), requires_grad=True))
nn.init.xavier_uniform_(self.att_weights.data)
def get_mask(self):
pass
def forward(self, hidden_states, attention_mask=None):
if self.batch_first:
batch_size, _max_len = hidden_states.size()[:2]
else:
_max_len, batch_size = hidden_states.size()[:2]
weights = torch.bmm(hidden_states, self.att_weights.permute(1, 0).
unsqueeze(0).repeat(batch_size, 1, 1))
attentions = F.softmax(torch.tanh(weights.squeeze()), dim=-1)
masked = attentions * attention_mask
if len(attentions.shape) == 1:
attentions = attentions.unsqueeze(0)
_sums = masked.sum(-1, keepdim=True).expand(attentions.shape)
attentions = masked.div(_sums)
weighted = torch.mul(hidden_states, attentions.unsqueeze(-1).
expand_as(hidden_states))
representations = weighted.sum(1).squeeze(dim=1)
return representations, attentions
class MultiLayerPerceptron(torch.nn.Module):
"""
A simple MLP that can either be used independently or put on top
of pretrained models (such as BERT) and act as a classifier.
Args:
hidden_size (int): the size of each layer
num_classes (int): number of output classes
num_layers (int): number of layers
activation (str): type of activations for layers in between
log_softmax (bool): whether to add a log_softmax layer before output
"""
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=2, activation: 'str'='relu', log_softmax: 'bool'=True):
super().__init__()
self.layers = 0
activations = {'relu': nn.ReLU(), 'gelu': nn.GELU(), 'sigmoid': nn.
Sigmoid(), 'tanh': nn.Tanh()}
for _ in range(num_layers - 1):
layer = torch.nn.Linear(hidden_size, hidden_size)
setattr(self, f'layer{self.layers}', layer)
setattr(self, f'layer{self.layers + 1}', activations[activation])
self.layers += 2
layer = torch.nn.Linear(hidden_size, num_classes)
setattr(self, f'layer{self.layers}', layer)
self.layers += 1
self.log_softmax = log_softmax
@property
def last_linear_layer(self):
return getattr(self, f'layer{self.layers - 1}')
def forward(self, hidden_states):
output_states = hidden_states[:]
for i in range(self.layers):
output_states = getattr(self, f'layer{i}')(output_states)
if self.log_softmax:
output_states = torch.log_softmax(output_states, dim=-1)
else:
output_states = torch.softmax(output_states, dim=-1)
return output_states
class SequenceClassifierNew(nn.Module):
def __init__(self, hidden_size: 'int', num_classes: 'int', num_layers:
'int'=2, activation: 'str'='relu', log_softmax: 'bool'=True,
dropout: 'float'=0.0, use_transformer_init: 'bool'=True, pooling:
'str'='mean', idx_conditioned_on: 'int'=None):
"""
Initializes the SequenceClassifier module.
Args:
hidden_size: the hidden size of the mlp head on the top of the encoder
num_classes: number of the classes to predict
num_layers: number of the linear layers of the mlp head on the top of the encoder
activation: type of activations between layers of the mlp head
log_softmax: applies the log softmax on the output
dropout: the dropout used for the mlp head
use_transformer_init: initializes the weights with the same approach used in Transformer
idx_conditioned_on: index of the token to use as the sequence representation for the classification task, default is the first token
"""
super().__init__()
self.log_softmax = log_softmax
self._idx_conditioned_on = idx_conditioned_on
self.pooling = pooling
self.mlp = MultiLayerPerceptron(hidden_size=hidden_size * 2 if
pooling == 'mean_max' else hidden_size, num_classes=num_classes,
num_layers=num_layers, activation=activation, log_softmax=
log_softmax)
self.dropout = nn.Dropout(dropout)
if use_transformer_init:
self.apply(lambda module: transformer_weights_init(module,
xavier=False))
if pooling == 'attention':
self.attention = SelfAttention(hidden_size)
def forward(self, input_0):
primals_2 = self.mlp.layer0.weight
primals_3 = self.mlp.layer0.bias
primals_4 = self.mlp.layer2.weight
primals_5 = self.mlp.layer2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
ngxingyu/Domain-Transfer-for-Punctuation-Retrieval
|
SequenceClassifier
| false
| 7,340
|
[
"Apache-2.0"
] | 1
|
f5aa0ea0946c68aaf7fcf49a5085e6c823766a2f
|
https://github.com/ngxingyu/Domain-Transfer-for-Punctuation-Retrieval/tree/f5aa0ea0946c68aaf7fcf49a5085e6c823766a2f
|
ScaleNorm
|
import math
import torch
import torch.nn as nn
class ScaleNorm(nn.Module):
"""ScaleNorm"""
"""All g’s in SCALE NORM are initialized to sqrt(d)"""
def __init__(self, scale, eps=1e-05):
super(ScaleNorm, self).__init__()
self.scale = nn.Parameter(torch.tensor(math.sqrt(scale)))
self.eps = eps
def forward(self, x):
norm = self.scale / torch.norm(x, dim=-1, keepdim=True).clamp(min=
self.eps)
return x * norm
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'scale': 1.0}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_div_linalg_vector_norm_0(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 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 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = libdevice.sqrt(tmp12)
tmp14 = 1e-05
tmp15 = triton_helpers.maximum(tmp13, tmp14)
tmp16 = tmp1 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
@triton.jit
def triton_poi_fused_clamp_div_linalg_vector_norm_mul_1(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
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 = args
args.clear()
assert_size_stride(primals_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, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_div_linalg_vector_norm_0[grid(64)](primals_1,
primals_2, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clamp_div_linalg_vector_norm_mul_1[grid(256)](
primals_2, buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
return buf1, primals_2
class ScaleNormNew(nn.Module):
"""ScaleNorm"""
"""All g’s in SCALE NORM are initialized to sqrt(d)"""
def __init__(self, scale, eps=1e-05):
super(ScaleNormNew, self).__init__()
self.scale = nn.Parameter(torch.tensor(math.sqrt(scale)))
self.eps = eps
def forward(self, input_0):
primals_1 = self.scale
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
nigelnnk/MATCh-sensitivity
|
ScaleNorm
| false
| 7,341
|
[
"MIT"
] | 1
|
aaf2b924ac98c8c5925bbf431481724d11a102f8
|
https://github.com/nigelnnk/MATCh-sensitivity/tree/aaf2b924ac98c8c5925bbf431481724d11a102f8
|
StyleResidual
|
import torch
from torch import nn
import torch.utils.data
import torch.optim
class StyleResidual(nn.Module):
"""Styling."""
def __init__(self, d_channel: 'int', d_style: 'int', kernel_size: 'int'=1):
super().__init__()
self.rs = nn.Conv1d(in_channels=d_style, out_channels=d_channel,
kernel_size=kernel_size, stride=1, padding=kernel_size // 2)
def forward(self, x: 'torch.Tensor', s: 'torch.Tensor') ->torch.Tensor:
"""`x`: [B,C,T], `s`: [B,S,T] => [B,C,T]."""
return x + self.rs(s)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_channel': 4, 'd_style': 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.data
import torch.optim
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_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
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, 4), (16, 4, 1))
buf1 = reinterpret_tensor(buf0, (4, 4), (4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(16)](buf1, primals_4, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
del primals_4
return buf1, primals_1, reinterpret_tensor(primals_3, (1, 4, 4), (16, 4,
1), 0)
class StyleResidualNew(nn.Module):
"""Styling."""
def __init__(self, d_channel: 'int', d_style: 'int', kernel_size: 'int'=1):
super().__init__()
self.rs = nn.Conv1d(in_channels=d_style, out_channels=d_channel,
kernel_size=kernel_size, stride=1, padding=kernel_size // 2)
def forward(self, input_0, input_1):
primals_1 = self.rs.weight
primals_2 = self.rs.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
niklub/NeMo
|
StyleResidual
| false
| 7,342
|
[
"Apache-2.0"
] | 1
|
4bcb2321cd16835f63afe3dfe993e6d56bcf2c0c
|
https://github.com/niklub/NeMo/tree/4bcb2321cd16835f63afe3dfe993e6d56bcf2c0c
|
CQLAgent
|
import torch
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from scipy import optimize
class CQLAgent(nn.Module):
def __init__(self, input_shape, n_actions, n_opponent_actions,
hidden_dim=64):
super(CQLAgent, self).__init__()
self.fc1 = nn.Linear(input_shape, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, n_actions * n_opponent_actions)
self.n_actions = n_actions
self.n_opponent_actions = n_opponent_actions
def forward(self, inputs):
x = F.relu(self.fc1(inputs))
q = self.fc2(x)
q = q.view(-1, self.n_opponent_actions, self.n_actions)
return q
"""
@param:
inputs: [batch, input_shape]
policy_disc: whether to use the discrete policy
@ retval: problem distributions of the action shape: [batch, n_actions] type:np.array
"""
def get_policy(self, inputs, policy_disc=True):
qvals = self.forward(inputs)
if policy_disc:
qvals = th.min(qvals, axis=1)[0]
actions = th.argmax(qvals, axis=1)
policys = F.one_hot(actions, num_classes=self.n_actions).float(
).detach()
else:
policys = []
qvals = qvals.detach().numpy()
for qval_sample in qvals:
c = np.array([0] * self.n_actions + [-1])
A_ub = np.concatenate((-qval_sample, np.ones((self.
n_opponent_actions, 1))), axis=1)
B_ub = np.zeros(self.n_opponent_actions)
A_eq = np.array([[1] * self.n_actions + [0]])
B_eq = np.array([1])
bounds = []
for a in range(self.n_actions):
bounds.append((0, 1))
bounds.append((None, None))
res = optimize.linprog(c, A_ub, B_ub, A_eq, B_eq, bounds=
tuple(bounds))
policy = res['x']
policys.append(policy[:-1])
policys = th.tensor(policys, dtype=th.float32)
return policys
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_shape': 4, 'n_actions': 4, 'n_opponent_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from scipy import optimize
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (16, 64), (64, 1))
assert_size_stride(primals_5, (16,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1,
primals_2, buf3, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 64),
(64, 1), 0), reinterpret_tensor(primals_4, (64, 16), (1, 64), 0
), alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (64, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 64), (64, 1), 0), primals_4, buf3
class CQLAgentNew(nn.Module):
def __init__(self, input_shape, n_actions, n_opponent_actions,
hidden_dim=64):
super(CQLAgentNew, self).__init__()
self.fc1 = nn.Linear(input_shape, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, n_actions * n_opponent_actions)
self.n_actions = n_actions
self.n_opponent_actions = n_opponent_actions
"""
@param:
inputs: [batch, input_shape]
policy_disc: whether to use the discrete policy
@ retval: problem distributions of the action shape: [batch, n_actions] type:np.array
"""
def get_policy(self, inputs, policy_disc=True):
qvals = self.forward(inputs)
if policy_disc:
qvals = th.min(qvals, axis=1)[0]
actions = th.argmax(qvals, axis=1)
policys = F.one_hot(actions, num_classes=self.n_actions).float(
).detach()
else:
policys = []
qvals = qvals.detach().numpy()
for qval_sample in qvals:
c = np.array([0] * self.n_actions + [-1])
A_ub = np.concatenate((-qval_sample, np.ones((self.
n_opponent_actions, 1))), axis=1)
B_ub = np.zeros(self.n_opponent_actions)
A_eq = np.array([[1] * self.n_actions + [0]])
B_eq = np.array([1])
bounds = []
for a in range(self.n_actions):
bounds.append((0, 1))
bounds.append((None, None))
res = optimize.linprog(c, A_ub, B_ub, A_eq, B_eq, bounds=
tuple(bounds))
policy = res['x']
policys.append(policy[:-1])
policys = th.tensor(policys, dtype=th.float32)
return policys
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
netlab-lcy/CMIX
|
CQLAgent
| false
| 7,343
|
[
"MIT"
] | 1
|
53e2d8794af2b380295efe06dcb05235089953c1
|
https://github.com/netlab-lcy/CMIX/tree/53e2d8794af2b380295efe06dcb05235089953c1
|
MultiHeadAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadAttention(nn.Module):
"""
Applies an multi-head attention mechanism on the output features from the decoder.
Refer to 「State-of-the-art Speech Recognition With Sequence-to-Sequence Models」 Paper
https://arxiv.org/abs/1712.01769
Args:
in_features (int): The number of expected features in the output
n_head (int): number of heads. (default: 4)
dim (int): dimension size of sub heads. (default: 128)
Inputs: query, key
- **query** (batch, output_len, dimensions): tensor containing the output features from the decoder.
- **key** (batch, input_len, dimensions): tensor containing features of the encoded input sequence.
Returns: output
- **output** (batch, output_len, dimensions): tensor containing the attended output features from the decoder.
Examples::
>>> attention = MultiHeadAttention(in_features, n_head=4, dim=128)
>>> output = attention(query, key)
"""
def __init__(self, in_features, n_head=4, dim=128):
super(MultiHeadAttention, self).__init__()
self.in_features = in_features
self.linear_q = nn.Linear(in_features, dim * n_head)
self.linear_k = nn.Linear(in_features, dim * n_head)
self.n_head = n_head
self.dim = dim
self.out = nn.Linear(in_features << 1, in_features)
def forward(self, query, key):
batch_size = key.size(0)
query_length = query.size(1)
key_length = key.size(1)
preserved = query
query = self.linear_q(query).view(batch_size, query_length, self.
n_head, self.dim).permute(2, 0, 1, 3)
key = self.linear_k(key).view(batch_size, key_length, self.n_head,
self.dim).permute(2, 0, 1, 3)
query = query.contiguous().view(-1, query_length, self.dim)
key = key.contiguous().view(-1, key_length, self.dim)
attn_score = torch.bmm(query, key.transpose(1, 2))
attn_distribution = F.softmax(attn_score, dim=2)
context = torch.bmm(attn_distribution, key).view(self.n_head,
batch_size, query_length, self.dim)
context = context.permute(1, 2, 0, 3).contiguous().view(batch_size,
query_length, -1)
combined = torch.cat([context, preserved], dim=2)
output = torch.tanh(self.out(combined.view(-1, 2 * self.in_features))
).view(batch_size, -1, self.in_features)
return output
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, 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 % 128
x1 = xindex // 128 % 16
x2 = xindex // 2048
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x2 + 512 * x1), None)
tmp1 = tl.load(in_ptr1 + (x0 + 128 * x2), None, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 8256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 516
x3 = xindex // 516
x2 = xindex // 2064
x4 = xindex % 2064
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 512, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (128 * x3 + 2048 * (x0 // 128 % 4) + x0 % 128),
tmp4 & xmask, eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 516, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x3 + (-512 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + (x4 + 2080 * x2), tmp10, xmask)
@triton.jit
def triton_poi_fused_cat_view_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 8256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + (2080 * (x0 // 2064) + x0 % 2064), xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused_tanh_tanh_backward_5(in_out_ptr0, in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tmp4 = tmp3 * tmp3
tmp5 = 1.0
tmp6 = tmp5 - tmp4
tl.store(in_out_ptr0 + x2, tmp3, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = 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, (512, 4), (4, 1))
assert_size_stride(primals_4, (512,), (1,))
assert_size_stride(primals_5, (512, 4), (4, 1))
assert_size_stride(primals_6, (512,), (1,))
assert_size_stride(primals_7, (4, 8), (8, 1))
assert_size_stride(primals_8, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 512), (1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((16, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 512), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(8192)](buf0, primals_4, buf2, 8192,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_4
buf3 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(8192)](buf1, primals_6, buf3, 8192,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf2, (16, 4, 128), (512, 128,
1), 0), reinterpret_tensor(buf3, (16, 128, 4), (512, 1, 128), 0
), out=buf4)
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
buf7 = reinterpret_tensor(buf1, (16, 4, 128), (512, 128, 1), 0)
del buf1
extern_kernels.bmm(buf6, reinterpret_tensor(buf3, (16, 4, 128), (
512, 128, 1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 516), (2080, 516, 1), torch.float32)
triton_poi_fused_cat_3[grid(8256)](buf7, primals_2, buf8, 8256,
XBLOCK=256, num_warps=4, num_stages=1)
del buf7
buf9 = empty_strided_cuda((1032, 8), (8, 1), torch.float32)
triton_poi_fused_cat_view_4[grid(8256)](buf8, buf9, 8256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf8
buf10 = empty_strided_cuda((1032, 4), (4, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_7, (8, 4), (1, 8
), 0), out=buf10)
buf11 = buf10
del buf10
buf12 = empty_strided_cuda((1032, 4), (4, 1), torch.float32)
triton_poi_fused_tanh_tanh_backward_5[grid(4128)](buf11, primals_8,
buf12, 4128, XBLOCK=128, num_warps=4, num_stages=1)
del primals_8
return reinterpret_tensor(buf11, (4, 258, 4), (1032, 4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(buf3, (16, 128, 4), (512, 1, 128), 0
), buf6, buf9, buf12, primals_7, reinterpret_tensor(buf2, (16, 128,
4), (512, 1, 128), 0)
class MultiHeadAttentionNew(nn.Module):
"""
Applies an multi-head attention mechanism on the output features from the decoder.
Refer to 「State-of-the-art Speech Recognition With Sequence-to-Sequence Models」 Paper
https://arxiv.org/abs/1712.01769
Args:
in_features (int): The number of expected features in the output
n_head (int): number of heads. (default: 4)
dim (int): dimension size of sub heads. (default: 128)
Inputs: query, key
- **query** (batch, output_len, dimensions): tensor containing the output features from the decoder.
- **key** (batch, input_len, dimensions): tensor containing features of the encoded input sequence.
Returns: output
- **output** (batch, output_len, dimensions): tensor containing the attended output features from the decoder.
Examples::
>>> attention = MultiHeadAttention(in_features, n_head=4, dim=128)
>>> output = attention(query, key)
"""
def __init__(self, in_features, n_head=4, dim=128):
super(MultiHeadAttentionNew, self).__init__()
self.in_features = in_features
self.linear_q = nn.Linear(in_features, dim * n_head)
self.linear_k = nn.Linear(in_features, dim * n_head)
self.n_head = n_head
self.dim = dim
self.out = nn.Linear(in_features << 1, in_features)
def forward(self, input_0, input_1):
primals_3 = self.linear_q.weight
primals_4 = self.linear_q.bias
primals_5 = self.linear_k.weight
primals_6 = self.linear_k.bias
primals_7 = self.out.weight
primals_8 = self.out.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]
|
ngbsLab/Korean-Speech-Recognition
|
MultiHeadAttention
| false
| 7,344
|
[
"Apache-2.0"
] | 1
|
3867bf7d23222da6812c9b98a93d3c6f7b3c80fc
|
https://github.com/ngbsLab/Korean-Speech-Recognition/tree/3867bf7d23222da6812c9b98a93d3c6f7b3c80fc
|
FocalLoss
|
import torch
import torch.nn as nn
import torch.optim
import torch.utils.data
import torch.autograd
class FocalLoss(nn.Module):
def __init__(self, gamma=0, eps=1e-07):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.eps = eps
self.ce = torch.nn.CrossEntropyLoss()
def forward(self, input, target):
logp = self.ce(input, target)
p = torch.exp(-logp)
loss = (1 - p) ** self.gamma * logp
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
import torch.optim
import torch.utils.data
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_div_exp_mean_mul_neg_pow_rsub_sum_1(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + r3, None)
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = -tmp18
tmp20 = 0.015625
tmp21 = tmp19 * tmp20
tmp22 = -tmp21
tmp23 = tl_math.exp(tmp22)
tmp24 = 1.0
tmp24 - tmp23
tmp26 = tmp24 * tmp21
tmp27 = tmp26 / tmp24
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp27, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__log_softmax_div_exp_mean_mul_neg_pow_rsub_sum_1[grid
(1)](buf2, buf0, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class FocalLossNew(nn.Module):
def __init__(self, gamma=0, eps=1e-07):
super(FocalLossNew, self).__init__()
self.gamma = gamma
self.eps = eps
self.ce = torch.nn.CrossEntropyLoss()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nikitajz/google-landmarks
|
FocalLoss
| false
| 7,345
|
[
"MIT"
] | 1
|
2051462be4450c193c98b237fc7ebdae783e2b28
|
https://github.com/nikitajz/google-landmarks/tree/2051462be4450c193c98b237fc7ebdae783e2b28
|
ClassWisePool
|
import sys
from torch.autograd import Function
import torch
from torch import nn
class ClassWisePoolFunction(Function):
@staticmethod
def forward(ctx, input, args):
ctx.num_maps = args
batch_size, num_channels, h, w = input.size()
if num_channels % ctx.num_maps != 0:
None
sys.exit(-1)
num_outputs = int(num_channels / ctx.num_maps)
x = input.view(batch_size, num_outputs, ctx.num_maps, h, w)
output = torch.sum(x, 2)
ctx.save_for_backward(input)
return output.view(batch_size, num_outputs, h, w) / ctx.num_maps
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
batch_size, num_channels, h, w = input.size()
num_outputs = grad_output.size(1)
grad_output = grad_output.view(batch_size, num_outputs, 1, h, w)
grad_input = grad_output.expand(batch_size, num_outputs, ctx.
num_maps, h, w).contiguous()
return grad_input.view(batch_size, num_channels, h, w), None
class ClassWisePool(nn.Module):
def __init__(self, num_maps):
super(ClassWisePool, self).__init__()
self.num_maps = num_maps
def forward(self, input):
return ClassWisePoolFunction.apply(input, self.num_maps)
def __repr__(self):
return self.__class__.__name__ + ' (num_maps={num_maps})'.format(
num_maps=self.num_maps)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_maps': 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 sys
from torch.autograd import Function
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.25
tmp8 = tmp6 * 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, 1, 4, 4), (16, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_sum_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class ClassWisePoolFunction(Function):
@staticmethod
def forward(ctx, input, args):
ctx.num_maps = args
batch_size, num_channels, h, w = input.size()
if num_channels % ctx.num_maps != 0:
None
sys.exit(-1)
num_outputs = int(num_channels / ctx.num_maps)
x = input.view(batch_size, num_outputs, ctx.num_maps, h, w)
output = torch.sum(x, 2)
ctx.save_for_backward(input)
return output.view(batch_size, num_outputs, h, w) / ctx.num_maps
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
batch_size, num_channels, h, w = input.size()
num_outputs = grad_output.size(1)
grad_output = grad_output.view(batch_size, num_outputs, 1, h, w)
grad_input = grad_output.expand(batch_size, num_outputs, ctx.
num_maps, h, w).contiguous()
return grad_input.view(batch_size, num_channels, h, w), None
class ClassWisePoolNew(nn.Module):
def __init__(self, num_maps):
super(ClassWisePoolNew, self).__init__()
self.num_maps = num_maps
def __repr__(self):
return self.__class__.__name__ + ' (num_maps={num_maps})'.format(
num_maps=self.num_maps)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nishanthta/wsl
|
ClassWisePool
| false
| 7,346
|
[
"MIT"
] | 1
|
5fda3b909a314b7f88ffa9ab27a6a142de6b0159
|
https://github.com/nishanthta/wsl/tree/5fda3b909a314b7f88ffa9ab27a6a142de6b0159
|
WassersteinLoss
|
import torch
def torch_cdf_loss(tensor_a, tensor_b, p=1):
tensor_a = tensor_a / (torch.sum(tensor_a, dim=-1, keepdim=True) + 1e-14)
tensor_b = tensor_b / (torch.sum(tensor_b, dim=-1, keepdim=True) + 1e-14)
cdf_tensor_a = torch.cumsum(tensor_a, dim=-1)
cdf_tensor_b = torch.cumsum(tensor_b, dim=-1)
if p == 1:
cdf_distance = torch.sum(torch.abs(cdf_tensor_a - cdf_tensor_b), dim=-1
)
elif p == 2:
cdf_distance = torch.sqrt(torch.sum(torch.pow(cdf_tensor_a -
cdf_tensor_b, 2), dim=-1))
else:
cdf_distance = torch.pow(torch.sum(torch.pow(torch.abs(cdf_tensor_a -
cdf_tensor_b), p), dim=-1), 1 / p)
cdf_loss = cdf_distance.mean()
return cdf_loss
def torch_wasserstein_loss(tensor_a, tensor_b):
return torch_cdf_loss(tensor_a, tensor_b, p=1)
class WassersteinLoss(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, tensor_a, tensor_b):
return torch_wasserstein_loss(tensor_a, tensor_b)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
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_add_cumsum_div_sum_0(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 4 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 1e-14
tmp9 = tmp7 + tmp8
tmp10 = tmp0 / tmp9
tmp11 = tmp10.to(tl.float32)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
tmp13, = tl.associative_scan((tmp12,), 1, _triton_helper_fn_add0)
tl.store(out_ptr0 + (r1 + 4 * x0), tmp13, xmask)
@triton.jit
def triton_per_fused_abs_mean_sub_sum_1(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp6 = tmp4 - tmp5
tmp7 = tl_math.abs(tmp6)
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tl_math.abs(tmp11)
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tl_math.abs(tmp16)
tmp18 = tmp13 + tmp17
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp21 = tl.sum(tmp19, 1)[:, None]
tmp22 = 64.0
tmp23 = tmp21 / tmp22
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp23, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_cumsum_div_sum_0[grid(64)](arg0_1, buf0, 64, 4,
XBLOCK=8, num_warps=2, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused_add_cumsum_div_sum_0[grid(64)](arg1_1, buf1, 64, 4,
XBLOCK=8, num_warps=2, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused_abs_mean_sub_sum_1[grid(1)](buf3, buf0, buf1, 1,
64, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
return buf3,
def torch_cdf_loss(tensor_a, tensor_b, p=1):
tensor_a = tensor_a / (torch.sum(tensor_a, dim=-1, keepdim=True) + 1e-14)
tensor_b = tensor_b / (torch.sum(tensor_b, dim=-1, keepdim=True) + 1e-14)
cdf_tensor_a = torch.cumsum(tensor_a, dim=-1)
cdf_tensor_b = torch.cumsum(tensor_b, dim=-1)
if p == 1:
cdf_distance = torch.sum(torch.abs(cdf_tensor_a - cdf_tensor_b), dim=-1
)
elif p == 2:
cdf_distance = torch.sqrt(torch.sum(torch.pow(cdf_tensor_a -
cdf_tensor_b, 2), dim=-1))
else:
cdf_distance = torch.pow(torch.sum(torch.pow(torch.abs(cdf_tensor_a -
cdf_tensor_b), p), dim=-1), 1 / p)
cdf_loss = cdf_distance.mean()
return cdf_loss
def torch_wasserstein_loss(tensor_a, tensor_b):
return torch_cdf_loss(tensor_a, tensor_b, p=1)
class WassersteinLossNew(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nikitadhawan/SimCLR
|
WassersteinLoss
| false
| 7,347
|
[
"MIT"
] | 1
|
7d87b384b1edb68e7ba86601b26f76e6da214718
|
https://github.com/nikitadhawan/SimCLR/tree/7d87b384b1edb68e7ba86601b26f76e6da214718
|
CoxPHLossSorted
|
import torch
def cox_ph_loss_sorted(log_h, event, eps=1e-07):
"""Requires the input to be sorted by descending duration time.
See DatasetDurationSorted.
We calculate the negative log of $(rac{h_i}{\\sum_{j \\in R_i} h_j})^d$,
where h = exp(log_h) are the hazards and R is the risk set, and d is event.
We just compute a cumulative sum, and not the true Risk sets. This is a
limitation, but simple and fast.
"""
event = event.view(-1)
log_h = log_h.view(-1)
gamma = log_h.max()
log_cumsum_h = log_h.sub(gamma).exp().cumsum(0).add(eps).log().add(gamma)
return -log_h.sub(log_cumsum_h).mul(event).sum().div(event.sum())
class CoxPHLossSorted(torch.nn.Module):
"""Loss for CoxPH.
Requires the input to be sorted by descending duration time.
See DatasetDurationSorted.
We calculate the negative log of $(rac{h_i}{\\sum_{j \\in R_i} h_j})^d$,
where h = exp(log_h) are the hazards and R is the risk set, and d is event.
We just compute a cumulative sum, and not the true Risk sets. This is a
limitation, but simple and fast.
"""
def __init__(self):
super().__init__()
def forward(self, log_h, events):
return cox_ph_loss_sorted(log_h, events)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
tmp0 = arg0_0 + arg1_0
return tmp0
@triton.jit
def triton_per_fused_add_cumsum_div_exp_log_max_mul_neg_sub_sum_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp14 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp1, 0))
tmp4 = tmp0 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp5.to(tl.float32)
tmp7 = tl.broadcast_to(tmp6, [RBLOCK])
tmp8, = tl.associative_scan((tmp7,), 0, _triton_helper_fn_add0)
tmp9 = 1e-07
tmp10 = tmp8 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp11 + tmp3
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = tl.broadcast_to(tmp14, [RBLOCK])
tmp21 = triton_helpers.promote_to_tensor(tl.sum(tmp19, 0))
tmp22 = tmp18 / tmp21
tmp23 = -tmp22
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp23, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((), (), torch.float32)
buf4 = buf2
del buf2
get_raw_stream(0)
triton_per_fused_add_cumsum_div_exp_log_max_mul_neg_sub_sum_0[grid(1)](
buf4, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf4,
def cox_ph_loss_sorted(log_h, event, eps=1e-07):
"""Requires the input to be sorted by descending duration time.
See DatasetDurationSorted.
We calculate the negative log of $(rac{h_i}{\\sum_{j \\in R_i} h_j})^d$,
where h = exp(log_h) are the hazards and R is the risk set, and d is event.
We just compute a cumulative sum, and not the true Risk sets. This is a
limitation, but simple and fast.
"""
event = event.view(-1)
log_h = log_h.view(-1)
gamma = log_h.max()
log_cumsum_h = log_h.sub(gamma).exp().cumsum(0).add(eps).log().add(gamma)
return -log_h.sub(log_cumsum_h).mul(event).sum().div(event.sum())
class CoxPHLossSortedNew(torch.nn.Module):
"""Loss for CoxPH.
Requires the input to be sorted by descending duration time.
See DatasetDurationSorted.
We calculate the negative log of $(rac{h_i}{\\sum_{j \\in R_i} h_j})^d$,
where h = exp(log_h) are the hazards and R is the risk set, and d is event.
We just compute a cumulative sum, and not the true Risk sets. This is a
limitation, but simple and fast.
"""
def __init__(self):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nikolase90/pycox
|
CoxPHLossSorted
| false
| 7,348
|
[
"BSD-2-Clause"
] | 1
|
1c780253da7bab7eba0dc02e1436a68a9b812a66
|
https://github.com/nikolase90/pycox/tree/1c780253da7bab7eba0dc02e1436a68a9b812a66
|
leaky_hardtanh
|
import torch
import torch.nn as nn
class leaky_hardtanh(nn.Module):
def __init__(self, min=-1, max=1, slope=0.01):
super(leaky_hardtanh, self).__init__()
self.min = min
self.max = max
self.slope = slope
def forward(self, x):
x = torch.where(x < self.min, self.min + x * self.slope, x)
x = torch.where(x > self.max, self.max + x * self.slope, x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_gt_lt_mul_where_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 = 0.01
tmp4 = tmp0 * tmp3
tmp5 = tmp4 + tmp1
tmp6 = tl.where(tmp2, tmp5, tmp0)
tmp7 = 1.0
tmp8 = tmp6 > tmp7
tmp9 = tmp6 * tmp3
tmp10 = tmp9 + tmp7
tmp11 = tl.where(tmp8, tmp10, tmp6)
tl.store(out_ptr0 + x0, tmp11, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_gt_lt_mul_where_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class leaky_hardtanhNew(nn.Module):
def __init__(self, min=-1, max=1, slope=0.01):
super(leaky_hardtanhNew, self).__init__()
self.min = min
self.max = max
self.slope = slope
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
nikolasmorshuis/gadolinium_prediction
|
leaky_hardtanh
| false
| 7,349
|
[
"Apache-2.0"
] | 1
|
7d6640df5b62ce578a947d3a9b9c701c3d1ccd79
|
https://github.com/nikolasmorshuis/gadolinium_prediction/tree/7d6640df5b62ce578a947d3a9b9c701c3d1ccd79
|
GlobalAttention
|
import torch
import torch.nn as nn
import torch.cuda
def aeq(*args):
base = args[0]
for a in args[1:]:
assert a == base, str(args)
class Bottle(nn.Module):
def forward(self, input):
if len(input.size()) <= 2:
return super(Bottle, self).forward(input)
size = input.size()[:2]
out = super(Bottle, self).forward(input.view(size[0] * size[1], -1))
return out.contiguous().view(size[0], size[1], -1)
class BottleLinear(Bottle, nn.Linear):
pass
class GlobalAttention(nn.Module):
"""
Luong Attention.
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the input query.
H_1 H_2 H_3 ... H_n
q q q q
| | | |
\\ | | /
.....
\\ | /
a
Constructs a unit mapping.
$$(H_1 + H_n, q) => (a)$$
Where H is of `batch x n x dim` and q is of `batch x dim`.
Loung Attention (dotprod):
$$ anh(W_2 [(softmax((W_1 q + b_1) H) H), q] + b_2)$$.:
Bahdanau Attention (mlp):
$$c = \\sum_{j=1}^{SeqLength}_jh_j$$.
The Alignment-function $$a$$ computes an alignment as:
$$a_j = softmax(v_a^T anh(W_a q + U_a h_j) )$$.
"""
def __init__(self, dim, coverage=False, attn_type='dotprod'):
super(GlobalAttention, self).__init__()
self.dim = dim
self.attn_type = attn_type
assert self.attn_type in ['dotprod', 'mlp'
], 'Please select a valid attention type.'
if self.attn_type == 'dotprod':
self.linear_in = nn.Linear(dim, dim, bias=False)
self.linear_out = nn.Linear(dim * 2, dim, bias=False)
elif self.attn_type == 'mlp':
self.linear_context = BottleLinear(dim, dim, bias=False)
self.linear_query = nn.Linear(dim, dim, bias=False)
self.v = BottleLinear(dim, 1, bias=False)
self.sm = nn.Softmax()
self.tanh = nn.Tanh()
self.mask = None
if coverage:
self.linear_cover = nn.Linear(1, dim, bias=False)
def applyMask(self, mask):
self.mask = mask
def forward(self, input, context, coverage=None):
"""
input (FloatTensor): batch x dim
context (FloatTensor): batch x sourceL x dim
coverage (FloatTensor): batch x sourceL
"""
batch, sourceL, dim = context.size()
batch_, dim_ = input.size()
aeq(batch, batch_)
aeq(dim, dim_)
aeq(self.dim, dim)
if coverage is not None:
batch_, sourceL_ = coverage.size()
aeq(batch, batch_)
aeq(sourceL, sourceL_)
if self.mask is not None:
beam_, batch_, sourceL_ = self.mask.size()
aeq(batch, batch_ * beam_)
aeq(sourceL, sourceL_)
if coverage:
context += self.linear_cover(coverage.view(-1).unsqueeze(1)
).view_as(context)
context = self.tanh(context)
if self.attn_type == 'dotprod':
targetT = self.linear_in(input).unsqueeze(2)
attn = torch.bmm(context, targetT).squeeze(2)
elif self.attn_type == 'mlp':
wq = self.linear_query(input).unsqueeze(1)
uh = self.linear_context(context.contiguous())
wquh = uh + wq.expand_as(uh)
wquh = self.tanh(wquh)
attn = self.v(wquh.contiguous()).squeeze()
if self.mask is not None:
attn.data.masked_fill_(self.mask, -float('inf'))
attn = self.sm(attn)
attn3 = attn.view(attn.size(0), 1, attn.size(1))
weightedContext = torch.bmm(attn3, context).squeeze(1)
if self.attn_type == 'dotprod':
weightedContext = torch.cat((weightedContext, input), 1)
weightedContext = self.linear_out(weightedContext)
weightedContext = self.tanh(weightedContext)
batch_, sourceL_ = attn.size()
aeq(batch, batch_)
aeq(sourceL, sourceL_)
batch_, dim_ = weightedContext.size()
aeq(batch, batch_)
aeq(dim, dim_)
return weightedContext, attn
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.cuda
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_2(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_3(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, 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, 1))
assert_size_stride(primals_4, (4, 8), (8, 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_2, reinterpret_tensor(primals_3, (4, 4),
(1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(primals_1, reinterpret_tensor(buf0, (4, 4, 1), (
4, 1, 1), 0), out=buf1)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](buf1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4), (4, 1), 0)
del buf1
triton_poi_fused__softmax_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 1, 4), (4, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf3, (4, 1, 4), (4, 4, 1), 0
), primals_1, out=buf4)
buf5 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_2[grid(32)](buf4, primals_2, buf5, 32, XBLOCK=
32, num_warps=1, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4), (4, 1), 0)
del buf4
extern_kernels.mm(buf5, reinterpret_tensor(primals_4, (8, 4), (1, 8
), 0), out=buf6)
buf7 = buf6
del buf6
triton_poi_fused_tanh_3[grid(16)](buf7, 16, XBLOCK=16, num_warps=1,
num_stages=1)
return (buf7, buf3, primals_2, buf3, buf5, buf7, primals_4,
reinterpret_tensor(primals_1, (4, 4, 4), (16, 1, 4), 0))
def aeq(*args):
base = args[0]
for a in args[1:]:
assert a == base, str(args)
class Bottle(nn.Module):
def forward(self, input):
if len(input.size()) <= 2:
return super(Bottle, self).forward(input)
size = input.size()[:2]
out = super(Bottle, self).forward(input.view(size[0] * size[1], -1))
return out.contiguous().view(size[0], size[1], -1)
class BottleLinear(Bottle, nn.Linear):
pass
class GlobalAttentionNew(nn.Module):
"""
Luong Attention.
Global attention takes a matrix and a query vector. It
then computes a parameterized convex combination of the matrix
based on the input query.
H_1 H_2 H_3 ... H_n
q q q q
| | | |
\\ | | /
.....
\\ | /
a
Constructs a unit mapping.
$$(H_1 + H_n, q) => (a)$$
Where H is of `batch x n x dim` and q is of `batch x dim`.
Loung Attention (dotprod):
$$ anh(W_2 [(softmax((W_1 q + b_1) H) H), q] + b_2)$$.:
Bahdanau Attention (mlp):
$$c = \\sum_{j=1}^{SeqLength}_jh_j$$.
The Alignment-function $$a$$ computes an alignment as:
$$a_j = softmax(v_a^T anh(W_a q + U_a h_j) )$$.
"""
def __init__(self, dim, coverage=False, attn_type='dotprod'):
super(GlobalAttentionNew, self).__init__()
self.dim = dim
self.attn_type = attn_type
assert self.attn_type in ['dotprod', 'mlp'
], 'Please select a valid attention type.'
if self.attn_type == 'dotprod':
self.linear_in = nn.Linear(dim, dim, bias=False)
self.linear_out = nn.Linear(dim * 2, dim, bias=False)
elif self.attn_type == 'mlp':
self.linear_context = BottleLinear(dim, dim, bias=False)
self.linear_query = nn.Linear(dim, dim, bias=False)
self.v = BottleLinear(dim, 1, bias=False)
self.sm = nn.Softmax()
self.tanh = nn.Tanh()
self.mask = None
if coverage:
self.linear_cover = nn.Linear(1, dim, bias=False)
def applyMask(self, mask):
self.mask = mask
def forward(self, input_0, input_1):
primals_2 = self.linear_in.weight
primals_4 = self.linear_out.weight
primals_3 = input_0
primals_1 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
nikhilweee/syntactic-seq2seq
|
GlobalAttention
| false
| 7,350
|
[
"MIT"
] | 1
|
807e524167b064fc85c91e5e2fa994de6b739455
|
https://github.com/nikhilweee/syntactic-seq2seq/tree/807e524167b064fc85c91e5e2fa994de6b739455
|
NetVLAD
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from sklearn.neighbors import NearestNeighbors
class NetVLAD(nn.Module):
"""NetVLAD layer implementation"""
def __init__(self, num_clusters=64, dim=128, normalize_input=True,
vladv2=False, use_faiss=True):
"""
Args:
num_clusters : int
The number of clusters
dim : int
Dimension of descriptors
normalize_input : bool
If true, descriptor-wise L2 normalization is applied to input.
vladv2 : bool
If true, use vladv2 otherwise use vladv1
"""
super().__init__()
self.num_clusters = num_clusters
self.dim = dim
self.alpha = 0
self.vladv2 = vladv2
self.normalize_input = normalize_input
self.conv = nn.Conv2d(dim, num_clusters, kernel_size=(1, 1), bias=
vladv2)
self.centroids = nn.Parameter(torch.rand(num_clusters, dim))
self.use_faiss = use_faiss
def init_params(self, clsts, traindescs):
if not self.vladv2:
clstsAssign = clsts / np.linalg.norm(clsts, axis=1, keepdims=True)
dots = np.dot(clstsAssign, traindescs.T)
dots.sort(0)
dots = dots[::-1, :]
self.alpha = (-np.log(0.01) / np.mean(dots[0, :] - dots[1, :])
).item()
self.centroids = nn.Parameter(torch.from_numpy(clsts))
self.conv.weight = nn.Parameter(torch.from_numpy(self.alpha *
clstsAssign).unsqueeze(2).unsqueeze(3))
self.conv.bias = None
else:
if not self.use_faiss:
knn = NearestNeighbors(n_jobs=-1)
knn.fit(traindescs)
del traindescs
ds_sq = np.square(knn.kneighbors(clsts, 2)[1])
del knn
else:
index = faiss.IndexFlatL2(traindescs.shape[1])
index.add(traindescs)
del traindescs
ds_sq = np.square(index.search(clsts, 2)[1])
del index
self.alpha = (-np.log(0.01) / np.mean(ds_sq[:, 1] - ds_sq[:, 0])
).item()
self.centroids = nn.Parameter(torch.from_numpy(clsts))
del clsts, ds_sq
self.conv.weight = nn.Parameter((2.0 * self.alpha * self.
centroids).unsqueeze(-1).unsqueeze(-1))
self.conv.bias = nn.Parameter(-self.alpha * self.centroids.norm
(dim=1))
def forward(self, x):
N, C = x.shape[:2]
if self.normalize_input:
x = F.normalize(x, p=2, dim=1)
soft_assign = self.conv(x).view(N, self.num_clusters, -1)
soft_assign = F.softmax(soft_assign, dim=1)
x_flatten = x.view(N, C, -1)
vlad = torch.zeros([N, self.num_clusters, C], dtype=x.dtype, layout
=x.layout, device=x.device)
for C in range(self.num_clusters):
residual = x_flatten.unsqueeze(0).permute(1, 0, 2, 3
) - self.centroids[C:C + 1, :].expand(x_flatten.size(-1), -
1, -1).permute(1, 2, 0).unsqueeze(0)
residual *= soft_assign[:, C:C + 1, :].unsqueeze(2)
vlad[:, C:C + 1, :] = residual.sum(dim=-1)
vlad = F.normalize(vlad, p=2, dim=2)
vlad = vlad.view(x.size(0), -1)
vlad = F.normalize(vlad, p=2, dim=1)
return vlad
def get_inputs():
return [torch.rand([4, 128, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import numpy as np
import torch.nn as nn
from sklearn.neighbors import NearestNeighbors
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_red_fused_linalg_vector_norm_0(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 % 4096
x1 = xindex // 4096
_tmp3 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x3 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 4096 * r2 + 524288 * x1), rmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = _tmp3 + tmp2
_tmp3 = tl.where(rmask, tmp4, _tmp3)
tmp3 = tl.sum(_tmp3, 1)[:, None]
tl.store(out_ptr0 + x3, tmp3, None)
@triton.jit
def triton_poi_fused_div_sub_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6, out_ptr7,
out_ptr8, out_ptr9, out_ptr10, out_ptr11, out_ptr12, out_ptr13,
out_ptr14, out_ptr15, out_ptr16, out_ptr17, out_ptr18, out_ptr19,
out_ptr20, out_ptr21, out_ptr22, out_ptr23, out_ptr24, out_ptr25,
out_ptr26, out_ptr27, out_ptr28, out_ptr29, out_ptr30, out_ptr31,
out_ptr32, out_ptr33, out_ptr34, out_ptr35, out_ptr36, out_ptr37,
out_ptr38, out_ptr39, out_ptr40, out_ptr41, out_ptr42, out_ptr43,
out_ptr44, out_ptr45, out_ptr46, out_ptr47, out_ptr48, out_ptr49,
out_ptr50, out_ptr51, out_ptr52, out_ptr53, out_ptr54, out_ptr55,
out_ptr56, out_ptr57, out_ptr58, out_ptr59, out_ptr60, out_ptr61,
out_ptr62, out_ptr63, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x0 = xindex % 4096
x2 = xindex // 524288
x1 = xindex // 4096 % 128
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + (x0 + 4096 * x2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr2 + (128 + x1), None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + (256 + x1), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr2 + (384 + x1), None, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr2 + (512 + x1), None, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr2 + (640 + x1), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr2 + (768 + x1), None, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr2 + (896 + x1), None, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr2 + (1024 + x1), None, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr2 + (1152 + x1), None, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr2 + (1280 + x1), None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + (1408 + x1), None, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr2 + (1536 + x1), None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + (1664 + x1), None, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr2 + (1792 + x1), None, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr2 + (1920 + x1), None, eviction_policy='evict_last')
tmp36 = tl.load(in_ptr2 + (2048 + x1), None, eviction_policy='evict_last')
tmp38 = tl.load(in_ptr2 + (2176 + x1), None, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr2 + (2304 + x1), None, eviction_policy='evict_last')
tmp42 = tl.load(in_ptr2 + (2432 + x1), None, eviction_policy='evict_last')
tmp44 = tl.load(in_ptr2 + (2560 + x1), None, eviction_policy='evict_last')
tmp46 = tl.load(in_ptr2 + (2688 + x1), None, eviction_policy='evict_last')
tmp48 = tl.load(in_ptr2 + (2816 + x1), None, eviction_policy='evict_last')
tmp50 = tl.load(in_ptr2 + (2944 + x1), None, eviction_policy='evict_last')
tmp52 = tl.load(in_ptr2 + (3072 + x1), None, eviction_policy='evict_last')
tmp54 = tl.load(in_ptr2 + (3200 + x1), None, eviction_policy='evict_last')
tmp56 = tl.load(in_ptr2 + (3328 + x1), None, eviction_policy='evict_last')
tmp58 = tl.load(in_ptr2 + (3456 + x1), None, eviction_policy='evict_last')
tmp60 = tl.load(in_ptr2 + (3584 + x1), None, eviction_policy='evict_last')
tmp62 = tl.load(in_ptr2 + (3712 + x1), None, eviction_policy='evict_last')
tmp64 = tl.load(in_ptr2 + (3840 + x1), None, eviction_policy='evict_last')
tmp66 = tl.load(in_ptr2 + (3968 + x1), None, eviction_policy='evict_last')
tmp68 = tl.load(in_ptr2 + (4096 + x1), None, eviction_policy='evict_last')
tmp70 = tl.load(in_ptr2 + (4224 + x1), None, eviction_policy='evict_last')
tmp72 = tl.load(in_ptr2 + (4352 + x1), None, eviction_policy='evict_last')
tmp74 = tl.load(in_ptr2 + (4480 + x1), None, eviction_policy='evict_last')
tmp76 = tl.load(in_ptr2 + (4608 + x1), None, eviction_policy='evict_last')
tmp78 = tl.load(in_ptr2 + (4736 + x1), None, eviction_policy='evict_last')
tmp80 = tl.load(in_ptr2 + (4864 + x1), None, eviction_policy='evict_last')
tmp82 = tl.load(in_ptr2 + (4992 + x1), None, eviction_policy='evict_last')
tmp84 = tl.load(in_ptr2 + (5120 + x1), None, eviction_policy='evict_last')
tmp86 = tl.load(in_ptr2 + (5248 + x1), None, eviction_policy='evict_last')
tmp88 = tl.load(in_ptr2 + (5376 + x1), None, eviction_policy='evict_last')
tmp90 = tl.load(in_ptr2 + (5504 + x1), None, eviction_policy='evict_last')
tmp92 = tl.load(in_ptr2 + (5632 + x1), None, eviction_policy='evict_last')
tmp94 = tl.load(in_ptr2 + (5760 + x1), None, eviction_policy='evict_last')
tmp96 = tl.load(in_ptr2 + (5888 + x1), None, eviction_policy='evict_last')
tmp98 = tl.load(in_ptr2 + (6016 + x1), None, eviction_policy='evict_last')
tmp100 = tl.load(in_ptr2 + (6144 + x1), None, eviction_policy='evict_last')
tmp102 = tl.load(in_ptr2 + (6272 + x1), None, eviction_policy='evict_last')
tmp104 = tl.load(in_ptr2 + (6400 + x1), None, eviction_policy='evict_last')
tmp106 = tl.load(in_ptr2 + (6528 + x1), None, eviction_policy='evict_last')
tmp108 = tl.load(in_ptr2 + (6656 + x1), None, eviction_policy='evict_last')
tmp110 = tl.load(in_ptr2 + (6784 + x1), None, eviction_policy='evict_last')
tmp112 = tl.load(in_ptr2 + (6912 + x1), None, eviction_policy='evict_last')
tmp114 = tl.load(in_ptr2 + (7040 + x1), None, eviction_policy='evict_last')
tmp116 = tl.load(in_ptr2 + (7168 + x1), None, eviction_policy='evict_last')
tmp118 = tl.load(in_ptr2 + (7296 + x1), None, eviction_policy='evict_last')
tmp120 = tl.load(in_ptr2 + (7424 + x1), None, eviction_policy='evict_last')
tmp122 = tl.load(in_ptr2 + (7552 + x1), None, eviction_policy='evict_last')
tmp124 = tl.load(in_ptr2 + (7680 + x1), None, eviction_policy='evict_last')
tmp126 = tl.load(in_ptr2 + (7808 + x1), None, eviction_policy='evict_last')
tmp128 = tl.load(in_ptr2 + (7936 + x1), None, eviction_policy='evict_last')
tmp130 = tl.load(in_ptr2 + (8064 + x1), None, eviction_policy='evict_last')
tmp2 = libdevice.sqrt(tmp1)
tmp3 = 1e-12
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = tmp0 / tmp4
tmp7 = tmp5 - tmp6
tmp9 = tmp5 - tmp8
tmp11 = tmp5 - tmp10
tmp13 = tmp5 - tmp12
tmp15 = tmp5 - tmp14
tmp17 = tmp5 - tmp16
tmp19 = tmp5 - tmp18
tmp21 = tmp5 - tmp20
tmp23 = tmp5 - tmp22
tmp25 = tmp5 - tmp24
tmp27 = tmp5 - tmp26
tmp29 = tmp5 - tmp28
tmp31 = tmp5 - tmp30
tmp33 = tmp5 - tmp32
tmp35 = tmp5 - tmp34
tmp37 = tmp5 - tmp36
tmp39 = tmp5 - tmp38
tmp41 = tmp5 - tmp40
tmp43 = tmp5 - tmp42
tmp45 = tmp5 - tmp44
tmp47 = tmp5 - tmp46
tmp49 = tmp5 - tmp48
tmp51 = tmp5 - tmp50
tmp53 = tmp5 - tmp52
tmp55 = tmp5 - tmp54
tmp57 = tmp5 - tmp56
tmp59 = tmp5 - tmp58
tmp61 = tmp5 - tmp60
tmp63 = tmp5 - tmp62
tmp65 = tmp5 - tmp64
tmp67 = tmp5 - tmp66
tmp69 = tmp5 - tmp68
tmp71 = tmp5 - tmp70
tmp73 = tmp5 - tmp72
tmp75 = tmp5 - tmp74
tmp77 = tmp5 - tmp76
tmp79 = tmp5 - tmp78
tmp81 = tmp5 - tmp80
tmp83 = tmp5 - tmp82
tmp85 = tmp5 - tmp84
tmp87 = tmp5 - tmp86
tmp89 = tmp5 - tmp88
tmp91 = tmp5 - tmp90
tmp93 = tmp5 - tmp92
tmp95 = tmp5 - tmp94
tmp97 = tmp5 - tmp96
tmp99 = tmp5 - tmp98
tmp101 = tmp5 - tmp100
tmp103 = tmp5 - tmp102
tmp105 = tmp5 - tmp104
tmp107 = tmp5 - tmp106
tmp109 = tmp5 - tmp108
tmp111 = tmp5 - tmp110
tmp113 = tmp5 - tmp112
tmp115 = tmp5 - tmp114
tmp117 = tmp5 - tmp116
tmp119 = tmp5 - tmp118
tmp121 = tmp5 - tmp120
tmp123 = tmp5 - tmp122
tmp125 = tmp5 - tmp124
tmp127 = tmp5 - tmp126
tmp129 = tmp5 - tmp128
tmp131 = tmp5 - tmp130
tl.store(out_ptr0 + x3, tmp5, None)
tl.store(out_ptr1 + x3, tmp7, None)
tl.store(out_ptr2 + x3, tmp9, None)
tl.store(out_ptr3 + x3, tmp11, None)
tl.store(out_ptr4 + x3, tmp13, None)
tl.store(out_ptr5 + x3, tmp15, None)
tl.store(out_ptr6 + x3, tmp17, None)
tl.store(out_ptr7 + x3, tmp19, None)
tl.store(out_ptr8 + x3, tmp21, None)
tl.store(out_ptr9 + x3, tmp23, None)
tl.store(out_ptr10 + x3, tmp25, None)
tl.store(out_ptr11 + x3, tmp27, None)
tl.store(out_ptr12 + x3, tmp29, None)
tl.store(out_ptr13 + x3, tmp31, None)
tl.store(out_ptr14 + x3, tmp33, None)
tl.store(out_ptr15 + x3, tmp35, None)
tl.store(out_ptr16 + x3, tmp37, None)
tl.store(out_ptr17 + x3, tmp39, None)
tl.store(out_ptr18 + x3, tmp41, None)
tl.store(out_ptr19 + x3, tmp43, None)
tl.store(out_ptr20 + x3, tmp45, None)
tl.store(out_ptr21 + x3, tmp47, None)
tl.store(out_ptr22 + x3, tmp49, None)
tl.store(out_ptr23 + x3, tmp51, None)
tl.store(out_ptr24 + x3, tmp53, None)
tl.store(out_ptr25 + x3, tmp55, None)
tl.store(out_ptr26 + x3, tmp57, None)
tl.store(out_ptr27 + x3, tmp59, None)
tl.store(out_ptr28 + x3, tmp61, None)
tl.store(out_ptr29 + x3, tmp63, None)
tl.store(out_ptr30 + x3, tmp65, None)
tl.store(out_ptr31 + x3, tmp67, None)
tl.store(out_ptr32 + x3, tmp69, None)
tl.store(out_ptr33 + x3, tmp71, None)
tl.store(out_ptr34 + x3, tmp73, None)
tl.store(out_ptr35 + x3, tmp75, None)
tl.store(out_ptr36 + x3, tmp77, None)
tl.store(out_ptr37 + x3, tmp79, None)
tl.store(out_ptr38 + x3, tmp81, None)
tl.store(out_ptr39 + x3, tmp83, None)
tl.store(out_ptr40 + x3, tmp85, None)
tl.store(out_ptr41 + x3, tmp87, None)
tl.store(out_ptr42 + x3, tmp89, None)
tl.store(out_ptr43 + x3, tmp91, None)
tl.store(out_ptr44 + x3, tmp93, None)
tl.store(out_ptr45 + x3, tmp95, None)
tl.store(out_ptr46 + x3, tmp97, None)
tl.store(out_ptr47 + x3, tmp99, None)
tl.store(out_ptr48 + x3, tmp101, None)
tl.store(out_ptr49 + x3, tmp103, None)
tl.store(out_ptr50 + x3, tmp105, None)
tl.store(out_ptr51 + x3, tmp107, None)
tl.store(out_ptr52 + x3, tmp109, None)
tl.store(out_ptr53 + x3, tmp111, None)
tl.store(out_ptr54 + x3, tmp113, None)
tl.store(out_ptr55 + x3, tmp115, None)
tl.store(out_ptr56 + x3, tmp117, None)
tl.store(out_ptr57 + x3, tmp119, None)
tl.store(out_ptr58 + x3, tmp121, None)
tl.store(out_ptr59 + x3, tmp123, None)
tl.store(out_ptr60 + x3, tmp125, None)
tl.store(out_ptr61 + x3, tmp127, None)
tl.store(out_ptr62 + x3, tmp129, None)
tl.store(out_ptr63 + x3, tmp131, None)
@triton.jit
def triton_per_fused__softmax_2(in_ptr0, out_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 4096
x1 = xindex // 4096
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4096 * r2 + 262144 * x1), None)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = triton_helpers.max2(tmp1, 1)[:, None]
tmp4 = tmp0 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + x3, tmp3, None)
tl.store(out_ptr1 + x3, tmp8, None)
@triton.jit
def triton_red_fused_mul_sub_sum_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, in_ptr17,
in_ptr18, in_ptr19, in_ptr20, in_ptr21, in_ptr22, in_ptr23, in_ptr24,
in_ptr25, in_ptr26, in_ptr27, in_ptr28, in_ptr29, in_ptr30, in_ptr31,
in_ptr32, out_ptr0, out_ptr1, out_ptr2, out_ptr3, out_ptr4, out_ptr5,
out_ptr6, out_ptr7, out_ptr8, out_ptr9, out_ptr10, out_ptr11, out_ptr12,
out_ptr13, out_ptr14, out_ptr15, out_ptr16, out_ptr17, out_ptr18,
out_ptr19, out_ptr20, out_ptr21, out_ptr22, out_ptr23, out_ptr24,
out_ptr25, out_ptr26, out_ptr27, out_ptr28, xnumel, rnumel, XBLOCK: tl.
constexpr, RBLOCK: tl.constexpr):
xnumel = 512
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x3 = xindex
x0 = xindex % 128
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
x1 = xindex // 128
_tmp11 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp20 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp29 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp38 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp47 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp56 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp65 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp74 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp83 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp92 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp101 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp110 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp119 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp128 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp137 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp146 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp155 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp164 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp173 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp182 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp191 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp200 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp209 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp218 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp227 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp236 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp245 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp254 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp263 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp3 = tl.load(in_ptr2 + (r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp4 = tl.load(in_ptr3 + (r2 + 4096 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp7 = tl.load(in_ptr4 + (r2 + 4096 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp13 = tl.load(in_ptr5 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp14 = tl.load(in_ptr2 + (4096 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp22 = tl.load(in_ptr6 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp23 = tl.load(in_ptr2 + (8192 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp31 = tl.load(in_ptr7 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp32 = tl.load(in_ptr2 + (12288 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp40 = tl.load(in_ptr8 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp41 = tl.load(in_ptr2 + (16384 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp49 = tl.load(in_ptr9 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp50 = tl.load(in_ptr2 + (20480 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp58 = tl.load(in_ptr10 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp59 = tl.load(in_ptr2 + (24576 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp67 = tl.load(in_ptr11 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp68 = tl.load(in_ptr2 + (28672 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp76 = tl.load(in_ptr12 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp77 = tl.load(in_ptr2 + (32768 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp85 = tl.load(in_ptr13 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp86 = tl.load(in_ptr2 + (36864 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp94 = tl.load(in_ptr14 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp95 = tl.load(in_ptr2 + (40960 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp103 = tl.load(in_ptr15 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp104 = tl.load(in_ptr2 + (45056 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp112 = tl.load(in_ptr16 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp113 = tl.load(in_ptr2 + (49152 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp121 = tl.load(in_ptr17 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp122 = tl.load(in_ptr2 + (53248 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp130 = tl.load(in_ptr18 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp131 = tl.load(in_ptr2 + (57344 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp139 = tl.load(in_ptr19 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp140 = tl.load(in_ptr2 + (61440 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp148 = tl.load(in_ptr20 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp149 = tl.load(in_ptr2 + (65536 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp157 = tl.load(in_ptr21 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp158 = tl.load(in_ptr2 + (69632 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp166 = tl.load(in_ptr22 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp167 = tl.load(in_ptr2 + (73728 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp175 = tl.load(in_ptr23 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp176 = tl.load(in_ptr2 + (77824 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp184 = tl.load(in_ptr24 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp185 = tl.load(in_ptr2 + (81920 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp193 = tl.load(in_ptr25 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp194 = tl.load(in_ptr2 + (86016 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp202 = tl.load(in_ptr26 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp203 = tl.load(in_ptr2 + (90112 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp211 = tl.load(in_ptr27 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp212 = tl.load(in_ptr2 + (94208 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp220 = tl.load(in_ptr28 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp221 = tl.load(in_ptr2 + (98304 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp229 = tl.load(in_ptr29 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp230 = tl.load(in_ptr2 + (102400 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp238 = tl.load(in_ptr30 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp239 = tl.load(in_ptr2 + (106496 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp247 = tl.load(in_ptr31 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp248 = tl.load(in_ptr2 + (110592 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp256 = tl.load(in_ptr32 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp257 = tl.load(in_ptr2 + (114688 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp2 = tmp0 - tmp1
tmp5 = tmp3 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 / tmp7
tmp9 = tmp2 * tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = _tmp11 + tmp10
_tmp11 = tl.where(rmask & xmask, tmp12, _tmp11)
tmp15 = tmp14 - tmp4
tmp16 = tl_math.exp(tmp15)
tmp17 = tmp16 / tmp7
tmp18 = tmp13 * tmp17
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp21 = _tmp20 + tmp19
_tmp20 = tl.where(rmask & xmask, tmp21, _tmp20)
tmp24 = tmp23 - tmp4
tmp25 = tl_math.exp(tmp24)
tmp26 = tmp25 / tmp7
tmp27 = tmp22 * tmp26
tmp28 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK])
tmp30 = _tmp29 + tmp28
_tmp29 = tl.where(rmask & xmask, tmp30, _tmp29)
tmp33 = tmp32 - tmp4
tmp34 = tl_math.exp(tmp33)
tmp35 = tmp34 / tmp7
tmp36 = tmp31 * tmp35
tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
tmp39 = _tmp38 + tmp37
_tmp38 = tl.where(rmask & xmask, tmp39, _tmp38)
tmp42 = tmp41 - tmp4
tmp43 = tl_math.exp(tmp42)
tmp44 = tmp43 / tmp7
tmp45 = tmp40 * tmp44
tmp46 = tl.broadcast_to(tmp45, [XBLOCK, RBLOCK])
tmp48 = _tmp47 + tmp46
_tmp47 = tl.where(rmask & xmask, tmp48, _tmp47)
tmp51 = tmp50 - tmp4
tmp52 = tl_math.exp(tmp51)
tmp53 = tmp52 / tmp7
tmp54 = tmp49 * tmp53
tmp55 = tl.broadcast_to(tmp54, [XBLOCK, RBLOCK])
tmp57 = _tmp56 + tmp55
_tmp56 = tl.where(rmask & xmask, tmp57, _tmp56)
tmp60 = tmp59 - tmp4
tmp61 = tl_math.exp(tmp60)
tmp62 = tmp61 / tmp7
tmp63 = tmp58 * tmp62
tmp64 = tl.broadcast_to(tmp63, [XBLOCK, RBLOCK])
tmp66 = _tmp65 + tmp64
_tmp65 = tl.where(rmask & xmask, tmp66, _tmp65)
tmp69 = tmp68 - tmp4
tmp70 = tl_math.exp(tmp69)
tmp71 = tmp70 / tmp7
tmp72 = tmp67 * tmp71
tmp73 = tl.broadcast_to(tmp72, [XBLOCK, RBLOCK])
tmp75 = _tmp74 + tmp73
_tmp74 = tl.where(rmask & xmask, tmp75, _tmp74)
tmp78 = tmp77 - tmp4
tmp79 = tl_math.exp(tmp78)
tmp80 = tmp79 / tmp7
tmp81 = tmp76 * tmp80
tmp82 = tl.broadcast_to(tmp81, [XBLOCK, RBLOCK])
tmp84 = _tmp83 + tmp82
_tmp83 = tl.where(rmask & xmask, tmp84, _tmp83)
tmp87 = tmp86 - tmp4
tmp88 = tl_math.exp(tmp87)
tmp89 = tmp88 / tmp7
tmp90 = tmp85 * tmp89
tmp91 = tl.broadcast_to(tmp90, [XBLOCK, RBLOCK])
tmp93 = _tmp92 + tmp91
_tmp92 = tl.where(rmask & xmask, tmp93, _tmp92)
tmp96 = tmp95 - tmp4
tmp97 = tl_math.exp(tmp96)
tmp98 = tmp97 / tmp7
tmp99 = tmp94 * tmp98
tmp100 = tl.broadcast_to(tmp99, [XBLOCK, RBLOCK])
tmp102 = _tmp101 + tmp100
_tmp101 = tl.where(rmask & xmask, tmp102, _tmp101)
tmp105 = tmp104 - tmp4
tmp106 = tl_math.exp(tmp105)
tmp107 = tmp106 / tmp7
tmp108 = tmp103 * tmp107
tmp109 = tl.broadcast_to(tmp108, [XBLOCK, RBLOCK])
tmp111 = _tmp110 + tmp109
_tmp110 = tl.where(rmask & xmask, tmp111, _tmp110)
tmp114 = tmp113 - tmp4
tmp115 = tl_math.exp(tmp114)
tmp116 = tmp115 / tmp7
tmp117 = tmp112 * tmp116
tmp118 = tl.broadcast_to(tmp117, [XBLOCK, RBLOCK])
tmp120 = _tmp119 + tmp118
_tmp119 = tl.where(rmask & xmask, tmp120, _tmp119)
tmp123 = tmp122 - tmp4
tmp124 = tl_math.exp(tmp123)
tmp125 = tmp124 / tmp7
tmp126 = tmp121 * tmp125
tmp127 = tl.broadcast_to(tmp126, [XBLOCK, RBLOCK])
tmp129 = _tmp128 + tmp127
_tmp128 = tl.where(rmask & xmask, tmp129, _tmp128)
tmp132 = tmp131 - tmp4
tmp133 = tl_math.exp(tmp132)
tmp134 = tmp133 / tmp7
tmp135 = tmp130 * tmp134
tmp136 = tl.broadcast_to(tmp135, [XBLOCK, RBLOCK])
tmp138 = _tmp137 + tmp136
_tmp137 = tl.where(rmask & xmask, tmp138, _tmp137)
tmp141 = tmp140 - tmp4
tmp142 = tl_math.exp(tmp141)
tmp143 = tmp142 / tmp7
tmp144 = tmp139 * tmp143
tmp145 = tl.broadcast_to(tmp144, [XBLOCK, RBLOCK])
tmp147 = _tmp146 + tmp145
_tmp146 = tl.where(rmask & xmask, tmp147, _tmp146)
tmp150 = tmp149 - tmp4
tmp151 = tl_math.exp(tmp150)
tmp152 = tmp151 / tmp7
tmp153 = tmp148 * tmp152
tmp154 = tl.broadcast_to(tmp153, [XBLOCK, RBLOCK])
tmp156 = _tmp155 + tmp154
_tmp155 = tl.where(rmask & xmask, tmp156, _tmp155)
tmp159 = tmp158 - tmp4
tmp160 = tl_math.exp(tmp159)
tmp161 = tmp160 / tmp7
tmp162 = tmp157 * tmp161
tmp163 = tl.broadcast_to(tmp162, [XBLOCK, RBLOCK])
tmp165 = _tmp164 + tmp163
_tmp164 = tl.where(rmask & xmask, tmp165, _tmp164)
tmp168 = tmp167 - tmp4
tmp169 = tl_math.exp(tmp168)
tmp170 = tmp169 / tmp7
tmp171 = tmp166 * tmp170
tmp172 = tl.broadcast_to(tmp171, [XBLOCK, RBLOCK])
tmp174 = _tmp173 + tmp172
_tmp173 = tl.where(rmask & xmask, tmp174, _tmp173)
tmp177 = tmp176 - tmp4
tmp178 = tl_math.exp(tmp177)
tmp179 = tmp178 / tmp7
tmp180 = tmp175 * tmp179
tmp181 = tl.broadcast_to(tmp180, [XBLOCK, RBLOCK])
tmp183 = _tmp182 + tmp181
_tmp182 = tl.where(rmask & xmask, tmp183, _tmp182)
tmp186 = tmp185 - tmp4
tmp187 = tl_math.exp(tmp186)
tmp188 = tmp187 / tmp7
tmp189 = tmp184 * tmp188
tmp190 = tl.broadcast_to(tmp189, [XBLOCK, RBLOCK])
tmp192 = _tmp191 + tmp190
_tmp191 = tl.where(rmask & xmask, tmp192, _tmp191)
tmp195 = tmp194 - tmp4
tmp196 = tl_math.exp(tmp195)
tmp197 = tmp196 / tmp7
tmp198 = tmp193 * tmp197
tmp199 = tl.broadcast_to(tmp198, [XBLOCK, RBLOCK])
tmp201 = _tmp200 + tmp199
_tmp200 = tl.where(rmask & xmask, tmp201, _tmp200)
tmp204 = tmp203 - tmp4
tmp205 = tl_math.exp(tmp204)
tmp206 = tmp205 / tmp7
tmp207 = tmp202 * tmp206
tmp208 = tl.broadcast_to(tmp207, [XBLOCK, RBLOCK])
tmp210 = _tmp209 + tmp208
_tmp209 = tl.where(rmask & xmask, tmp210, _tmp209)
tmp213 = tmp212 - tmp4
tmp214 = tl_math.exp(tmp213)
tmp215 = tmp214 / tmp7
tmp216 = tmp211 * tmp215
tmp217 = tl.broadcast_to(tmp216, [XBLOCK, RBLOCK])
tmp219 = _tmp218 + tmp217
_tmp218 = tl.where(rmask & xmask, tmp219, _tmp218)
tmp222 = tmp221 - tmp4
tmp223 = tl_math.exp(tmp222)
tmp224 = tmp223 / tmp7
tmp225 = tmp220 * tmp224
tmp226 = tl.broadcast_to(tmp225, [XBLOCK, RBLOCK])
tmp228 = _tmp227 + tmp226
_tmp227 = tl.where(rmask & xmask, tmp228, _tmp227)
tmp231 = tmp230 - tmp4
tmp232 = tl_math.exp(tmp231)
tmp233 = tmp232 / tmp7
tmp234 = tmp229 * tmp233
tmp235 = tl.broadcast_to(tmp234, [XBLOCK, RBLOCK])
tmp237 = _tmp236 + tmp235
_tmp236 = tl.where(rmask & xmask, tmp237, _tmp236)
tmp240 = tmp239 - tmp4
tmp241 = tl_math.exp(tmp240)
tmp242 = tmp241 / tmp7
tmp243 = tmp238 * tmp242
tmp244 = tl.broadcast_to(tmp243, [XBLOCK, RBLOCK])
tmp246 = _tmp245 + tmp244
_tmp245 = tl.where(rmask & xmask, tmp246, _tmp245)
tmp249 = tmp248 - tmp4
tmp250 = tl_math.exp(tmp249)
tmp251 = tmp250 / tmp7
tmp252 = tmp247 * tmp251
tmp253 = tl.broadcast_to(tmp252, [XBLOCK, RBLOCK])
tmp255 = _tmp254 + tmp253
_tmp254 = tl.where(rmask & xmask, tmp255, _tmp254)
tmp258 = tmp257 - tmp4
tmp259 = tl_math.exp(tmp258)
tmp260 = tmp259 / tmp7
tmp261 = tmp256 * tmp260
tmp262 = tl.broadcast_to(tmp261, [XBLOCK, RBLOCK])
tmp264 = _tmp263 + tmp262
_tmp263 = tl.where(rmask & xmask, tmp264, _tmp263)
tmp11 = tl.sum(_tmp11, 1)[:, None]
tl.store(out_ptr0 + x3, tmp11, xmask)
tmp20 = tl.sum(_tmp20, 1)[:, None]
tl.store(out_ptr1 + x3, tmp20, xmask)
tmp29 = tl.sum(_tmp29, 1)[:, None]
tl.store(out_ptr2 + x3, tmp29, xmask)
tmp38 = tl.sum(_tmp38, 1)[:, None]
tl.store(out_ptr3 + x3, tmp38, xmask)
tmp47 = tl.sum(_tmp47, 1)[:, None]
tl.store(out_ptr4 + x3, tmp47, xmask)
tmp56 = tl.sum(_tmp56, 1)[:, None]
tl.store(out_ptr5 + x3, tmp56, xmask)
tmp65 = tl.sum(_tmp65, 1)[:, None]
tl.store(out_ptr6 + x3, tmp65, xmask)
tmp74 = tl.sum(_tmp74, 1)[:, None]
tl.store(out_ptr7 + x3, tmp74, xmask)
tmp83 = tl.sum(_tmp83, 1)[:, None]
tl.store(out_ptr8 + x3, tmp83, xmask)
tmp92 = tl.sum(_tmp92, 1)[:, None]
tl.store(out_ptr9 + x3, tmp92, xmask)
tmp101 = tl.sum(_tmp101, 1)[:, None]
tl.store(out_ptr10 + x3, tmp101, xmask)
tmp110 = tl.sum(_tmp110, 1)[:, None]
tl.store(out_ptr11 + x3, tmp110, xmask)
tmp119 = tl.sum(_tmp119, 1)[:, None]
tl.store(out_ptr12 + x3, tmp119, xmask)
tmp128 = tl.sum(_tmp128, 1)[:, None]
tl.store(out_ptr13 + x3, tmp128, xmask)
tmp137 = tl.sum(_tmp137, 1)[:, None]
tl.store(out_ptr14 + x3, tmp137, xmask)
tmp146 = tl.sum(_tmp146, 1)[:, None]
tl.store(out_ptr15 + x3, tmp146, xmask)
tmp155 = tl.sum(_tmp155, 1)[:, None]
tl.store(out_ptr16 + x3, tmp155, xmask)
tmp164 = tl.sum(_tmp164, 1)[:, None]
tl.store(out_ptr17 + x3, tmp164, xmask)
tmp173 = tl.sum(_tmp173, 1)[:, None]
tl.store(out_ptr18 + x3, tmp173, xmask)
tmp182 = tl.sum(_tmp182, 1)[:, None]
tl.store(out_ptr19 + x3, tmp182, xmask)
tmp191 = tl.sum(_tmp191, 1)[:, None]
tl.store(out_ptr20 + x3, tmp191, xmask)
tmp200 = tl.sum(_tmp200, 1)[:, None]
tl.store(out_ptr21 + x3, tmp200, xmask)
tmp209 = tl.sum(_tmp209, 1)[:, None]
tl.store(out_ptr22 + x3, tmp209, xmask)
tmp218 = tl.sum(_tmp218, 1)[:, None]
tl.store(out_ptr23 + x3, tmp218, xmask)
tmp227 = tl.sum(_tmp227, 1)[:, None]
tl.store(out_ptr24 + x3, tmp227, xmask)
tmp236 = tl.sum(_tmp236, 1)[:, None]
tl.store(out_ptr25 + x3, tmp236, xmask)
tmp245 = tl.sum(_tmp245, 1)[:, None]
tl.store(out_ptr26 + x3, tmp245, xmask)
tmp254 = tl.sum(_tmp254, 1)[:, None]
tl.store(out_ptr27 + x3, tmp254, xmask)
tmp263 = tl.sum(_tmp263, 1)[:, None]
tl.store(out_ptr28 + x3, tmp263, xmask)
@triton.jit
def triton_red_fused_mul_sum_4(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, in_ptr24, in_ptr25,
in_ptr26, in_ptr27, in_ptr28, in_ptr29, in_ptr30, out_ptr0, out_ptr1,
out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6, out_ptr7, out_ptr8,
out_ptr9, out_ptr10, out_ptr11, out_ptr12, out_ptr13, out_ptr14,
out_ptr15, out_ptr16, out_ptr17, out_ptr18, out_ptr19, out_ptr20,
out_ptr21, out_ptr22, out_ptr23, out_ptr24, out_ptr25, out_ptr26,
out_ptr27, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 512
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x3 = xindex
x1 = xindex // 128
_tmp9 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp18 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp27 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp36 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp45 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp54 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp63 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp72 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp81 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp90 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp99 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp108 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp117 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp126 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp135 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp144 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp153 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp162 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp171 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp180 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp189 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp198 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp207 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp216 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp225 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp234 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp243 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp252 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp1 = tl.load(in_ptr1 + (118784 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp2 = tl.load(in_ptr2 + (r2 + 4096 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp5 = tl.load(in_ptr3 + (r2 + 4096 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tl.load(in_ptr4 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp12 = tl.load(in_ptr1 + (122880 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp20 = tl.load(in_ptr5 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp21 = tl.load(in_ptr1 + (126976 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp29 = tl.load(in_ptr6 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp30 = tl.load(in_ptr1 + (131072 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp38 = tl.load(in_ptr7 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp39 = tl.load(in_ptr1 + (135168 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp47 = tl.load(in_ptr8 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp48 = tl.load(in_ptr1 + (139264 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp56 = tl.load(in_ptr9 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp57 = tl.load(in_ptr1 + (143360 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp65 = tl.load(in_ptr10 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp66 = tl.load(in_ptr1 + (147456 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp74 = tl.load(in_ptr11 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp75 = tl.load(in_ptr1 + (151552 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp83 = tl.load(in_ptr12 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp84 = tl.load(in_ptr1 + (155648 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp92 = tl.load(in_ptr13 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp93 = tl.load(in_ptr1 + (159744 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp101 = tl.load(in_ptr14 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp102 = tl.load(in_ptr1 + (163840 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp110 = tl.load(in_ptr15 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp111 = tl.load(in_ptr1 + (167936 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp119 = tl.load(in_ptr16 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp120 = tl.load(in_ptr1 + (172032 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp128 = tl.load(in_ptr17 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp129 = tl.load(in_ptr1 + (176128 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp137 = tl.load(in_ptr18 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp138 = tl.load(in_ptr1 + (180224 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp146 = tl.load(in_ptr19 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp147 = tl.load(in_ptr1 + (184320 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp155 = tl.load(in_ptr20 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp156 = tl.load(in_ptr1 + (188416 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp164 = tl.load(in_ptr21 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp165 = tl.load(in_ptr1 + (192512 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp173 = tl.load(in_ptr22 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp174 = tl.load(in_ptr1 + (196608 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp182 = tl.load(in_ptr23 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp183 = tl.load(in_ptr1 + (200704 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp191 = tl.load(in_ptr24 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp192 = tl.load(in_ptr1 + (204800 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp200 = tl.load(in_ptr25 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp201 = tl.load(in_ptr1 + (208896 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp209 = tl.load(in_ptr26 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp210 = tl.load(in_ptr1 + (212992 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp218 = tl.load(in_ptr27 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp219 = tl.load(in_ptr1 + (217088 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp227 = tl.load(in_ptr28 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp228 = tl.load(in_ptr1 + (221184 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp236 = tl.load(in_ptr29 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp237 = tl.load(in_ptr1 + (225280 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp245 = tl.load(in_ptr30 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp246 = tl.load(in_ptr1 + (229376 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp3 = tmp1 - tmp2
tmp4 = tl_math.exp(tmp3)
tmp6 = tmp4 / tmp5
tmp7 = tmp0 * tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = _tmp9 + tmp8
_tmp9 = tl.where(rmask & xmask, tmp10, _tmp9)
tmp13 = tmp12 - tmp2
tmp14 = tl_math.exp(tmp13)
tmp15 = tmp14 / tmp5
tmp16 = tmp11 * tmp15
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = _tmp18 + tmp17
_tmp18 = tl.where(rmask & xmask, tmp19, _tmp18)
tmp22 = tmp21 - tmp2
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp23 / tmp5
tmp25 = tmp20 * tmp24
tmp26 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK])
tmp28 = _tmp27 + tmp26
_tmp27 = tl.where(rmask & xmask, tmp28, _tmp27)
tmp31 = tmp30 - tmp2
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp32 / tmp5
tmp34 = tmp29 * tmp33
tmp35 = tl.broadcast_to(tmp34, [XBLOCK, RBLOCK])
tmp37 = _tmp36 + tmp35
_tmp36 = tl.where(rmask & xmask, tmp37, _tmp36)
tmp40 = tmp39 - tmp2
tmp41 = tl_math.exp(tmp40)
tmp42 = tmp41 / tmp5
tmp43 = tmp38 * tmp42
tmp44 = tl.broadcast_to(tmp43, [XBLOCK, RBLOCK])
tmp46 = _tmp45 + tmp44
_tmp45 = tl.where(rmask & xmask, tmp46, _tmp45)
tmp49 = tmp48 - tmp2
tmp50 = tl_math.exp(tmp49)
tmp51 = tmp50 / tmp5
tmp52 = tmp47 * tmp51
tmp53 = tl.broadcast_to(tmp52, [XBLOCK, RBLOCK])
tmp55 = _tmp54 + tmp53
_tmp54 = tl.where(rmask & xmask, tmp55, _tmp54)
tmp58 = tmp57 - tmp2
tmp59 = tl_math.exp(tmp58)
tmp60 = tmp59 / tmp5
tmp61 = tmp56 * tmp60
tmp62 = tl.broadcast_to(tmp61, [XBLOCK, RBLOCK])
tmp64 = _tmp63 + tmp62
_tmp63 = tl.where(rmask & xmask, tmp64, _tmp63)
tmp67 = tmp66 - tmp2
tmp68 = tl_math.exp(tmp67)
tmp69 = tmp68 / tmp5
tmp70 = tmp65 * tmp69
tmp71 = tl.broadcast_to(tmp70, [XBLOCK, RBLOCK])
tmp73 = _tmp72 + tmp71
_tmp72 = tl.where(rmask & xmask, tmp73, _tmp72)
tmp76 = tmp75 - tmp2
tmp77 = tl_math.exp(tmp76)
tmp78 = tmp77 / tmp5
tmp79 = tmp74 * tmp78
tmp80 = tl.broadcast_to(tmp79, [XBLOCK, RBLOCK])
tmp82 = _tmp81 + tmp80
_tmp81 = tl.where(rmask & xmask, tmp82, _tmp81)
tmp85 = tmp84 - tmp2
tmp86 = tl_math.exp(tmp85)
tmp87 = tmp86 / tmp5
tmp88 = tmp83 * tmp87
tmp89 = tl.broadcast_to(tmp88, [XBLOCK, RBLOCK])
tmp91 = _tmp90 + tmp89
_tmp90 = tl.where(rmask & xmask, tmp91, _tmp90)
tmp94 = tmp93 - tmp2
tmp95 = tl_math.exp(tmp94)
tmp96 = tmp95 / tmp5
tmp97 = tmp92 * tmp96
tmp98 = tl.broadcast_to(tmp97, [XBLOCK, RBLOCK])
tmp100 = _tmp99 + tmp98
_tmp99 = tl.where(rmask & xmask, tmp100, _tmp99)
tmp103 = tmp102 - tmp2
tmp104 = tl_math.exp(tmp103)
tmp105 = tmp104 / tmp5
tmp106 = tmp101 * tmp105
tmp107 = tl.broadcast_to(tmp106, [XBLOCK, RBLOCK])
tmp109 = _tmp108 + tmp107
_tmp108 = tl.where(rmask & xmask, tmp109, _tmp108)
tmp112 = tmp111 - tmp2
tmp113 = tl_math.exp(tmp112)
tmp114 = tmp113 / tmp5
tmp115 = tmp110 * tmp114
tmp116 = tl.broadcast_to(tmp115, [XBLOCK, RBLOCK])
tmp118 = _tmp117 + tmp116
_tmp117 = tl.where(rmask & xmask, tmp118, _tmp117)
tmp121 = tmp120 - tmp2
tmp122 = tl_math.exp(tmp121)
tmp123 = tmp122 / tmp5
tmp124 = tmp119 * tmp123
tmp125 = tl.broadcast_to(tmp124, [XBLOCK, RBLOCK])
tmp127 = _tmp126 + tmp125
_tmp126 = tl.where(rmask & xmask, tmp127, _tmp126)
tmp130 = tmp129 - tmp2
tmp131 = tl_math.exp(tmp130)
tmp132 = tmp131 / tmp5
tmp133 = tmp128 * tmp132
tmp134 = tl.broadcast_to(tmp133, [XBLOCK, RBLOCK])
tmp136 = _tmp135 + tmp134
_tmp135 = tl.where(rmask & xmask, tmp136, _tmp135)
tmp139 = tmp138 - tmp2
tmp140 = tl_math.exp(tmp139)
tmp141 = tmp140 / tmp5
tmp142 = tmp137 * tmp141
tmp143 = tl.broadcast_to(tmp142, [XBLOCK, RBLOCK])
tmp145 = _tmp144 + tmp143
_tmp144 = tl.where(rmask & xmask, tmp145, _tmp144)
tmp148 = tmp147 - tmp2
tmp149 = tl_math.exp(tmp148)
tmp150 = tmp149 / tmp5
tmp151 = tmp146 * tmp150
tmp152 = tl.broadcast_to(tmp151, [XBLOCK, RBLOCK])
tmp154 = _tmp153 + tmp152
_tmp153 = tl.where(rmask & xmask, tmp154, _tmp153)
tmp157 = tmp156 - tmp2
tmp158 = tl_math.exp(tmp157)
tmp159 = tmp158 / tmp5
tmp160 = tmp155 * tmp159
tmp161 = tl.broadcast_to(tmp160, [XBLOCK, RBLOCK])
tmp163 = _tmp162 + tmp161
_tmp162 = tl.where(rmask & xmask, tmp163, _tmp162)
tmp166 = tmp165 - tmp2
tmp167 = tl_math.exp(tmp166)
tmp168 = tmp167 / tmp5
tmp169 = tmp164 * tmp168
tmp170 = tl.broadcast_to(tmp169, [XBLOCK, RBLOCK])
tmp172 = _tmp171 + tmp170
_tmp171 = tl.where(rmask & xmask, tmp172, _tmp171)
tmp175 = tmp174 - tmp2
tmp176 = tl_math.exp(tmp175)
tmp177 = tmp176 / tmp5
tmp178 = tmp173 * tmp177
tmp179 = tl.broadcast_to(tmp178, [XBLOCK, RBLOCK])
tmp181 = _tmp180 + tmp179
_tmp180 = tl.where(rmask & xmask, tmp181, _tmp180)
tmp184 = tmp183 - tmp2
tmp185 = tl_math.exp(tmp184)
tmp186 = tmp185 / tmp5
tmp187 = tmp182 * tmp186
tmp188 = tl.broadcast_to(tmp187, [XBLOCK, RBLOCK])
tmp190 = _tmp189 + tmp188
_tmp189 = tl.where(rmask & xmask, tmp190, _tmp189)
tmp193 = tmp192 - tmp2
tmp194 = tl_math.exp(tmp193)
tmp195 = tmp194 / tmp5
tmp196 = tmp191 * tmp195
tmp197 = tl.broadcast_to(tmp196, [XBLOCK, RBLOCK])
tmp199 = _tmp198 + tmp197
_tmp198 = tl.where(rmask & xmask, tmp199, _tmp198)
tmp202 = tmp201 - tmp2
tmp203 = tl_math.exp(tmp202)
tmp204 = tmp203 / tmp5
tmp205 = tmp200 * tmp204
tmp206 = tl.broadcast_to(tmp205, [XBLOCK, RBLOCK])
tmp208 = _tmp207 + tmp206
_tmp207 = tl.where(rmask & xmask, tmp208, _tmp207)
tmp211 = tmp210 - tmp2
tmp212 = tl_math.exp(tmp211)
tmp213 = tmp212 / tmp5
tmp214 = tmp209 * tmp213
tmp215 = tl.broadcast_to(tmp214, [XBLOCK, RBLOCK])
tmp217 = _tmp216 + tmp215
_tmp216 = tl.where(rmask & xmask, tmp217, _tmp216)
tmp220 = tmp219 - tmp2
tmp221 = tl_math.exp(tmp220)
tmp222 = tmp221 / tmp5
tmp223 = tmp218 * tmp222
tmp224 = tl.broadcast_to(tmp223, [XBLOCK, RBLOCK])
tmp226 = _tmp225 + tmp224
_tmp225 = tl.where(rmask & xmask, tmp226, _tmp225)
tmp229 = tmp228 - tmp2
tmp230 = tl_math.exp(tmp229)
tmp231 = tmp230 / tmp5
tmp232 = tmp227 * tmp231
tmp233 = tl.broadcast_to(tmp232, [XBLOCK, RBLOCK])
tmp235 = _tmp234 + tmp233
_tmp234 = tl.where(rmask & xmask, tmp235, _tmp234)
tmp238 = tmp237 - tmp2
tmp239 = tl_math.exp(tmp238)
tmp240 = tmp239 / tmp5
tmp241 = tmp236 * tmp240
tmp242 = tl.broadcast_to(tmp241, [XBLOCK, RBLOCK])
tmp244 = _tmp243 + tmp242
_tmp243 = tl.where(rmask & xmask, tmp244, _tmp243)
tmp247 = tmp246 - tmp2
tmp248 = tl_math.exp(tmp247)
tmp249 = tmp248 / tmp5
tmp250 = tmp245 * tmp249
tmp251 = tl.broadcast_to(tmp250, [XBLOCK, RBLOCK])
tmp253 = _tmp252 + tmp251
_tmp252 = tl.where(rmask & xmask, tmp253, _tmp252)
tmp9 = tl.sum(_tmp9, 1)[:, None]
tl.store(out_ptr0 + x3, tmp9, xmask)
tmp18 = tl.sum(_tmp18, 1)[:, None]
tl.store(out_ptr1 + x3, tmp18, xmask)
tmp27 = tl.sum(_tmp27, 1)[:, None]
tl.store(out_ptr2 + x3, tmp27, xmask)
tmp36 = tl.sum(_tmp36, 1)[:, None]
tl.store(out_ptr3 + x3, tmp36, xmask)
tmp45 = tl.sum(_tmp45, 1)[:, None]
tl.store(out_ptr4 + x3, tmp45, xmask)
tmp54 = tl.sum(_tmp54, 1)[:, None]
tl.store(out_ptr5 + x3, tmp54, xmask)
tmp63 = tl.sum(_tmp63, 1)[:, None]
tl.store(out_ptr6 + x3, tmp63, xmask)
tmp72 = tl.sum(_tmp72, 1)[:, None]
tl.store(out_ptr7 + x3, tmp72, xmask)
tmp81 = tl.sum(_tmp81, 1)[:, None]
tl.store(out_ptr8 + x3, tmp81, xmask)
tmp90 = tl.sum(_tmp90, 1)[:, None]
tl.store(out_ptr9 + x3, tmp90, xmask)
tmp99 = tl.sum(_tmp99, 1)[:, None]
tl.store(out_ptr10 + x3, tmp99, xmask)
tmp108 = tl.sum(_tmp108, 1)[:, None]
tl.store(out_ptr11 + x3, tmp108, xmask)
tmp117 = tl.sum(_tmp117, 1)[:, None]
tl.store(out_ptr12 + x3, tmp117, xmask)
tmp126 = tl.sum(_tmp126, 1)[:, None]
tl.store(out_ptr13 + x3, tmp126, xmask)
tmp135 = tl.sum(_tmp135, 1)[:, None]
tl.store(out_ptr14 + x3, tmp135, xmask)
tmp144 = tl.sum(_tmp144, 1)[:, None]
tl.store(out_ptr15 + x3, tmp144, xmask)
tmp153 = tl.sum(_tmp153, 1)[:, None]
tl.store(out_ptr16 + x3, tmp153, xmask)
tmp162 = tl.sum(_tmp162, 1)[:, None]
tl.store(out_ptr17 + x3, tmp162, xmask)
tmp171 = tl.sum(_tmp171, 1)[:, None]
tl.store(out_ptr18 + x3, tmp171, xmask)
tmp180 = tl.sum(_tmp180, 1)[:, None]
tl.store(out_ptr19 + x3, tmp180, xmask)
tmp189 = tl.sum(_tmp189, 1)[:, None]
tl.store(out_ptr20 + x3, tmp189, xmask)
tmp198 = tl.sum(_tmp198, 1)[:, None]
tl.store(out_ptr21 + x3, tmp198, xmask)
tmp207 = tl.sum(_tmp207, 1)[:, None]
tl.store(out_ptr22 + x3, tmp207, xmask)
tmp216 = tl.sum(_tmp216, 1)[:, None]
tl.store(out_ptr23 + x3, tmp216, xmask)
tmp225 = tl.sum(_tmp225, 1)[:, None]
tl.store(out_ptr24 + x3, tmp225, xmask)
tmp234 = tl.sum(_tmp234, 1)[:, None]
tl.store(out_ptr25 + x3, tmp234, xmask)
tmp243 = tl.sum(_tmp243, 1)[:, None]
tl.store(out_ptr26 + x3, tmp243, xmask)
tmp252 = tl.sum(_tmp252, 1)[:, None]
tl.store(out_ptr27 + x3, tmp252, xmask)
@triton.jit
def triton_red_fused_mul_sum_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, out_ptr0, out_ptr1,
out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 512
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x3 = xindex
x1 = xindex // 128
_tmp9 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp18 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp27 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp36 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp45 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp54 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
_tmp63 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp1 = tl.load(in_ptr1 + (233472 + r2 + 262144 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp2 = tl.load(in_ptr2 + (r2 + 4096 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp5 = tl.load(in_ptr3 + (r2 + 4096 * x1), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tl.load(in_ptr4 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp12 = tl.load(in_ptr1 + (237568 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp20 = tl.load(in_ptr5 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp21 = tl.load(in_ptr1 + (241664 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp29 = tl.load(in_ptr6 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp30 = tl.load(in_ptr1 + (245760 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp38 = tl.load(in_ptr7 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp39 = tl.load(in_ptr1 + (249856 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp47 = tl.load(in_ptr8 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp48 = tl.load(in_ptr1 + (253952 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp56 = tl.load(in_ptr9 + (r2 + 4096 * x3), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp57 = tl.load(in_ptr1 + (258048 + r2 + 262144 * x1), rmask &
xmask, eviction_policy='evict_last', other=0.0)
tmp3 = tmp1 - tmp2
tmp4 = tl_math.exp(tmp3)
tmp6 = tmp4 / tmp5
tmp7 = tmp0 * tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = _tmp9 + tmp8
_tmp9 = tl.where(rmask & xmask, tmp10, _tmp9)
tmp13 = tmp12 - tmp2
tmp14 = tl_math.exp(tmp13)
tmp15 = tmp14 / tmp5
tmp16 = tmp11 * tmp15
tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
tmp19 = _tmp18 + tmp17
_tmp18 = tl.where(rmask & xmask, tmp19, _tmp18)
tmp22 = tmp21 - tmp2
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp23 / tmp5
tmp25 = tmp20 * tmp24
tmp26 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK])
tmp28 = _tmp27 + tmp26
_tmp27 = tl.where(rmask & xmask, tmp28, _tmp27)
tmp31 = tmp30 - tmp2
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp32 / tmp5
tmp34 = tmp29 * tmp33
tmp35 = tl.broadcast_to(tmp34, [XBLOCK, RBLOCK])
tmp37 = _tmp36 + tmp35
_tmp36 = tl.where(rmask & xmask, tmp37, _tmp36)
tmp40 = tmp39 - tmp2
tmp41 = tl_math.exp(tmp40)
tmp42 = tmp41 / tmp5
tmp43 = tmp38 * tmp42
tmp44 = tl.broadcast_to(tmp43, [XBLOCK, RBLOCK])
tmp46 = _tmp45 + tmp44
_tmp45 = tl.where(rmask & xmask, tmp46, _tmp45)
tmp49 = tmp48 - tmp2
tmp50 = tl_math.exp(tmp49)
tmp51 = tmp50 / tmp5
tmp52 = tmp47 * tmp51
tmp53 = tl.broadcast_to(tmp52, [XBLOCK, RBLOCK])
tmp55 = _tmp54 + tmp53
_tmp54 = tl.where(rmask & xmask, tmp55, _tmp54)
tmp58 = tmp57 - tmp2
tmp59 = tl_math.exp(tmp58)
tmp60 = tmp59 / tmp5
tmp61 = tmp56 * tmp60
tmp62 = tl.broadcast_to(tmp61, [XBLOCK, RBLOCK])
tmp64 = _tmp63 + tmp62
_tmp63 = tl.where(rmask & xmask, tmp64, _tmp63)
tmp9 = tl.sum(_tmp9, 1)[:, None]
tl.store(out_ptr0 + x3, tmp9, xmask)
tmp18 = tl.sum(_tmp18, 1)[:, None]
tl.store(out_ptr1 + x3, tmp18, xmask)
tmp27 = tl.sum(_tmp27, 1)[:, None]
tl.store(out_ptr2 + x3, tmp27, xmask)
tmp36 = tl.sum(_tmp36, 1)[:, None]
tl.store(out_ptr3 + x3, tmp36, xmask)
tmp45 = tl.sum(_tmp45, 1)[:, None]
tl.store(out_ptr4 + x3, tmp45, xmask)
tmp54 = tl.sum(_tmp54, 1)[:, None]
tl.store(out_ptr5 + x3, tmp54, xmask)
tmp63 = tl.sum(_tmp63, 1)[:, None]
tl.store(out_ptr6 + x3, tmp63, xmask)
@triton.jit
def triton_per_fused_copy_linalg_vector_norm_zeros_6(in_out_ptr0,
in_out_ptr1, 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, in_ptr24, in_ptr25, in_ptr26,
in_ptr27, in_ptr28, in_ptr29, in_ptr30, in_ptr31, in_ptr32, in_ptr33,
in_ptr34, in_ptr35, in_ptr36, in_ptr37, in_ptr38, in_ptr39, in_ptr40,
in_ptr41, in_ptr42, in_ptr43, in_ptr44, in_ptr45, in_ptr46, in_ptr47,
in_ptr48, in_ptr49, in_ptr50, in_ptr51, in_ptr52, in_ptr53, in_ptr54,
in_ptr55, in_ptr56, in_ptr57, in_ptr58, in_ptr59, in_ptr60, in_ptr61,
in_ptr62, in_ptr63, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 256
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, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex % 64
r2 = rindex
x1 = xindex // 64
x3 = xindex
tmp0 = x0
tmp1 = tl.full([1, 1], 4, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1, 1], 5, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = tl.load(in_ptr0 + (r2 + 128 * x1), tmp5 & xmask, eviction_policy
='evict_last', other=0.0)
tmp7 = tl.full([1, 1], 3, tl.int64)
tmp8 = tmp0 >= tmp7
tmp9 = tmp0 < tmp1
tmp10 = tmp8 & tmp9
tmp11 = tl.load(in_ptr1 + (r2 + 128 * x1), tmp10 & xmask,
eviction_policy='evict_last', other=0.0)
tmp12 = tl.full([1, 1], 2, tl.int64)
tmp13 = tmp0 >= tmp12
tmp14 = tmp0 < tmp7
tmp15 = tmp13 & tmp14
tmp16 = tl.load(in_ptr2 + (r2 + 128 * x1), tmp15 & xmask,
eviction_policy='evict_last', other=0.0)
tmp17 = tl.full([1, 1], 1, tl.int64)
tmp18 = tmp0 >= tmp17
tmp19 = tmp0 < tmp12
tmp20 = tmp18 & tmp19
tmp21 = tl.load(in_ptr3 + (r2 + 128 * x1), tmp20 & xmask,
eviction_policy='evict_last', other=0.0)
tmp22 = tmp0 < tmp17
tmp23 = tl.load(in_ptr4 + (r2 + 128 * x1), tmp22 & xmask,
eviction_policy='evict_last', other=0.0)
tmp24 = 0.0
tmp25 = tl.where(tmp22, tmp23, tmp24)
tmp26 = tl.where(tmp20, tmp21, tmp25)
tmp27 = tl.where(tmp15, tmp16, tmp26)
tmp28 = tl.where(tmp10, tmp11, tmp27)
tmp29 = tl.where(tmp5, tmp6, tmp28)
tmp30 = tl.full([1, 1], 8, tl.int64)
tmp31 = tmp0 >= tmp30
tmp32 = tl.full([1, 1], 9, tl.int64)
tmp33 = tmp0 < tmp32
tmp34 = tmp31 & tmp33
tmp35 = tl.load(in_ptr5 + (r2 + 128 * x1), tmp34 & xmask,
eviction_policy='evict_last', other=0.0)
tmp36 = tl.full([1, 1], 7, tl.int64)
tmp37 = tmp0 >= tmp36
tmp38 = tmp0 < tmp30
tmp39 = tmp37 & tmp38
tmp40 = tl.load(in_ptr6 + (r2 + 128 * x1), tmp39 & xmask,
eviction_policy='evict_last', other=0.0)
tmp41 = tl.full([1, 1], 6, tl.int64)
tmp42 = tmp0 >= tmp41
tmp43 = tmp0 < tmp36
tmp44 = tmp42 & tmp43
tmp45 = tl.load(in_ptr7 + (r2 + 128 * x1), tmp44 & xmask,
eviction_policy='evict_last', other=0.0)
tmp46 = tmp0 >= tmp3
tmp47 = tmp0 < tmp41
tmp48 = tmp46 & tmp47
tmp49 = tl.load(in_ptr8 + (r2 + 128 * x1), tmp48 & xmask,
eviction_policy='evict_last', other=0.0)
tmp50 = tl.where(tmp48, tmp49, tmp29)
tmp51 = tl.where(tmp44, tmp45, tmp50)
tmp52 = tl.where(tmp39, tmp40, tmp51)
tmp53 = tl.where(tmp34, tmp35, tmp52)
tmp54 = tl.full([1, 1], 12, tl.int64)
tmp55 = tmp0 >= tmp54
tmp56 = tl.full([1, 1], 13, tl.int64)
tmp57 = tmp0 < tmp56
tmp58 = tmp55 & tmp57
tmp59 = tl.load(in_ptr9 + (r2 + 128 * x1), tmp58 & xmask,
eviction_policy='evict_last', other=0.0)
tmp60 = tl.full([1, 1], 11, tl.int64)
tmp61 = tmp0 >= tmp60
tmp62 = tmp0 < tmp54
tmp63 = tmp61 & tmp62
tmp64 = tl.load(in_ptr10 + (r2 + 128 * x1), tmp63 & xmask,
eviction_policy='evict_last', other=0.0)
tmp65 = tl.full([1, 1], 10, tl.int64)
tmp66 = tmp0 >= tmp65
tmp67 = tmp0 < tmp60
tmp68 = tmp66 & tmp67
tmp69 = tl.load(in_ptr11 + (r2 + 128 * x1), tmp68 & xmask,
eviction_policy='evict_last', other=0.0)
tmp70 = tmp0 >= tmp32
tmp71 = tmp0 < tmp65
tmp72 = tmp70 & tmp71
tmp73 = tl.load(in_ptr12 + (r2 + 128 * x1), tmp72 & xmask,
eviction_policy='evict_last', other=0.0)
tmp74 = tl.where(tmp72, tmp73, tmp53)
tmp75 = tl.where(tmp68, tmp69, tmp74)
tmp76 = tl.where(tmp63, tmp64, tmp75)
tmp77 = tl.where(tmp58, tmp59, tmp76)
tmp78 = tl.full([1, 1], 16, tl.int64)
tmp79 = tmp0 >= tmp78
tmp80 = tl.full([1, 1], 17, tl.int64)
tmp81 = tmp0 < tmp80
tmp82 = tmp79 & tmp81
tmp83 = tl.load(in_ptr13 + (r2 + 128 * x1), tmp82 & xmask,
eviction_policy='evict_last', other=0.0)
tmp84 = tl.full([1, 1], 15, tl.int64)
tmp85 = tmp0 >= tmp84
tmp86 = tmp0 < tmp78
tmp87 = tmp85 & tmp86
tmp88 = tl.load(in_ptr14 + (r2 + 128 * x1), tmp87 & xmask,
eviction_policy='evict_last', other=0.0)
tmp89 = tl.full([1, 1], 14, tl.int64)
tmp90 = tmp0 >= tmp89
tmp91 = tmp0 < tmp84
tmp92 = tmp90 & tmp91
tmp93 = tl.load(in_ptr15 + (r2 + 128 * x1), tmp92 & xmask,
eviction_policy='evict_last', other=0.0)
tmp94 = tmp0 >= tmp56
tmp95 = tmp0 < tmp89
tmp96 = tmp94 & tmp95
tmp97 = tl.load(in_ptr16 + (r2 + 128 * x1), tmp96 & xmask,
eviction_policy='evict_last', other=0.0)
tmp98 = tl.where(tmp96, tmp97, tmp77)
tmp99 = tl.where(tmp92, tmp93, tmp98)
tmp100 = tl.where(tmp87, tmp88, tmp99)
tmp101 = tl.where(tmp82, tmp83, tmp100)
tmp102 = tl.full([1, 1], 20, tl.int64)
tmp103 = tmp0 >= tmp102
tmp104 = tl.full([1, 1], 21, tl.int64)
tmp105 = tmp0 < tmp104
tmp106 = tmp103 & tmp105
tmp107 = tl.load(in_ptr17 + (r2 + 128 * x1), tmp106 & xmask,
eviction_policy='evict_last', other=0.0)
tmp108 = tl.full([1, 1], 19, tl.int64)
tmp109 = tmp0 >= tmp108
tmp110 = tmp0 < tmp102
tmp111 = tmp109 & tmp110
tmp112 = tl.load(in_ptr18 + (r2 + 128 * x1), tmp111 & xmask,
eviction_policy='evict_last', other=0.0)
tmp113 = tl.full([1, 1], 18, tl.int64)
tmp114 = tmp0 >= tmp113
tmp115 = tmp0 < tmp108
tmp116 = tmp114 & tmp115
tmp117 = tl.load(in_ptr19 + (r2 + 128 * x1), tmp116 & xmask,
eviction_policy='evict_last', other=0.0)
tmp118 = tmp0 >= tmp80
tmp119 = tmp0 < tmp113
tmp120 = tmp118 & tmp119
tmp121 = tl.load(in_ptr20 + (r2 + 128 * x1), tmp120 & xmask,
eviction_policy='evict_last', other=0.0)
tmp122 = tl.where(tmp120, tmp121, tmp101)
tmp123 = tl.where(tmp116, tmp117, tmp122)
tmp124 = tl.where(tmp111, tmp112, tmp123)
tmp125 = tl.where(tmp106, tmp107, tmp124)
tmp126 = tl.full([1, 1], 24, tl.int64)
tmp127 = tmp0 >= tmp126
tmp128 = tl.full([1, 1], 25, tl.int64)
tmp129 = tmp0 < tmp128
tmp130 = tmp127 & tmp129
tmp131 = tl.load(in_ptr21 + (r2 + 128 * x1), tmp130 & xmask,
eviction_policy='evict_last', other=0.0)
tmp132 = tl.full([1, 1], 23, tl.int64)
tmp133 = tmp0 >= tmp132
tmp134 = tmp0 < tmp126
tmp135 = tmp133 & tmp134
tmp136 = tl.load(in_ptr22 + (r2 + 128 * x1), tmp135 & xmask,
eviction_policy='evict_last', other=0.0)
tmp137 = tl.full([1, 1], 22, tl.int64)
tmp138 = tmp0 >= tmp137
tmp139 = tmp0 < tmp132
tmp140 = tmp138 & tmp139
tmp141 = tl.load(in_ptr23 + (r2 + 128 * x1), tmp140 & xmask,
eviction_policy='evict_last', other=0.0)
tmp142 = tmp0 >= tmp104
tmp143 = tmp0 < tmp137
tmp144 = tmp142 & tmp143
tmp145 = tl.load(in_ptr24 + (r2 + 128 * x1), tmp144 & xmask,
eviction_policy='evict_last', other=0.0)
tmp146 = tl.where(tmp144, tmp145, tmp125)
tmp147 = tl.where(tmp140, tmp141, tmp146)
tmp148 = tl.where(tmp135, tmp136, tmp147)
tmp149 = tl.where(tmp130, tmp131, tmp148)
tmp150 = tl.full([1, 1], 28, tl.int64)
tmp151 = tmp0 >= tmp150
tmp152 = tl.full([1, 1], 29, tl.int64)
tmp153 = tmp0 < tmp152
tmp154 = tmp151 & tmp153
tmp155 = tl.load(in_ptr25 + (r2 + 128 * x1), tmp154 & xmask,
eviction_policy='evict_last', other=0.0)
tmp156 = tl.full([1, 1], 27, tl.int64)
tmp157 = tmp0 >= tmp156
tmp158 = tmp0 < tmp150
tmp159 = tmp157 & tmp158
tmp160 = tl.load(in_ptr26 + (r2 + 128 * x1), tmp159 & xmask,
eviction_policy='evict_last', other=0.0)
tmp161 = tl.full([1, 1], 26, tl.int64)
tmp162 = tmp0 >= tmp161
tmp163 = tmp0 < tmp156
tmp164 = tmp162 & tmp163
tmp165 = tl.load(in_ptr27 + (r2 + 128 * x1), tmp164 & xmask,
eviction_policy='evict_last', other=0.0)
tmp166 = tmp0 >= tmp128
tmp167 = tmp0 < tmp161
tmp168 = tmp166 & tmp167
tmp169 = tl.load(in_ptr28 + (r2 + 128 * x1), tmp168 & xmask,
eviction_policy='evict_last', other=0.0)
tmp170 = tl.where(tmp168, tmp169, tmp149)
tmp171 = tl.where(tmp164, tmp165, tmp170)
tmp172 = tl.where(tmp159, tmp160, tmp171)
tmp173 = tl.where(tmp154, tmp155, tmp172)
tmp174 = tl.full([1, 1], 32, tl.int64)
tmp175 = tmp0 >= tmp174
tmp176 = tl.full([1, 1], 33, tl.int64)
tmp177 = tmp0 < tmp176
tmp178 = tmp175 & tmp177
tmp179 = tl.load(in_ptr29 + (r2 + 128 * x1), tmp178 & xmask,
eviction_policy='evict_last', other=0.0)
tmp180 = tl.full([1, 1], 31, tl.int64)
tmp181 = tmp0 >= tmp180
tmp182 = tmp0 < tmp174
tmp183 = tmp181 & tmp182
tmp184 = tl.load(in_ptr30 + (r2 + 128 * x1), tmp183 & xmask,
eviction_policy='evict_last', other=0.0)
tmp185 = tl.full([1, 1], 30, tl.int64)
tmp186 = tmp0 >= tmp185
tmp187 = tmp0 < tmp180
tmp188 = tmp186 & tmp187
tmp189 = tl.load(in_ptr31 + (r2 + 128 * x1), tmp188 & xmask,
eviction_policy='evict_last', other=0.0)
tmp190 = tmp0 >= tmp152
tmp191 = tmp0 < tmp185
tmp192 = tmp190 & tmp191
tmp193 = tl.load(in_ptr32 + (r2 + 128 * x1), tmp192 & xmask,
eviction_policy='evict_last', other=0.0)
tmp194 = tl.where(tmp192, tmp193, tmp173)
tmp195 = tl.where(tmp188, tmp189, tmp194)
tmp196 = tl.where(tmp183, tmp184, tmp195)
tmp197 = tl.where(tmp178, tmp179, tmp196)
tmp198 = tl.full([1, 1], 36, tl.int64)
tmp199 = tmp0 >= tmp198
tmp200 = tl.full([1, 1], 37, tl.int64)
tmp201 = tmp0 < tmp200
tmp202 = tmp199 & tmp201
tmp203 = tl.load(in_ptr33 + (r2 + 128 * x1), tmp202 & xmask,
eviction_policy='evict_last', other=0.0)
tmp204 = tl.full([1, 1], 35, tl.int64)
tmp205 = tmp0 >= tmp204
tmp206 = tmp0 < tmp198
tmp207 = tmp205 & tmp206
tmp208 = tl.load(in_ptr34 + (r2 + 128 * x1), tmp207 & xmask,
eviction_policy='evict_last', other=0.0)
tmp209 = tl.full([1, 1], 34, tl.int64)
tmp210 = tmp0 >= tmp209
tmp211 = tmp0 < tmp204
tmp212 = tmp210 & tmp211
tmp213 = tl.load(in_ptr35 + (r2 + 128 * x1), tmp212 & xmask,
eviction_policy='evict_last', other=0.0)
tmp214 = tmp0 >= tmp176
tmp215 = tmp0 < tmp209
tmp216 = tmp214 & tmp215
tmp217 = tl.load(in_ptr36 + (r2 + 128 * x1), tmp216 & xmask,
eviction_policy='evict_last', other=0.0)
tmp218 = tl.where(tmp216, tmp217, tmp197)
tmp219 = tl.where(tmp212, tmp213, tmp218)
tmp220 = tl.where(tmp207, tmp208, tmp219)
tmp221 = tl.where(tmp202, tmp203, tmp220)
tmp222 = tl.full([1, 1], 40, tl.int64)
tmp223 = tmp0 >= tmp222
tmp224 = tl.full([1, 1], 41, tl.int64)
tmp225 = tmp0 < tmp224
tmp226 = tmp223 & tmp225
tmp227 = tl.load(in_ptr37 + (r2 + 128 * x1), tmp226 & xmask,
eviction_policy='evict_last', other=0.0)
tmp228 = tl.full([1, 1], 39, tl.int64)
tmp229 = tmp0 >= tmp228
tmp230 = tmp0 < tmp222
tmp231 = tmp229 & tmp230
tmp232 = tl.load(in_ptr38 + (r2 + 128 * x1), tmp231 & xmask,
eviction_policy='evict_last', other=0.0)
tmp233 = tl.full([1, 1], 38, tl.int64)
tmp234 = tmp0 >= tmp233
tmp235 = tmp0 < tmp228
tmp236 = tmp234 & tmp235
tmp237 = tl.load(in_ptr39 + (r2 + 128 * x1), tmp236 & xmask,
eviction_policy='evict_last', other=0.0)
tmp238 = tmp0 >= tmp200
tmp239 = tmp0 < tmp233
tmp240 = tmp238 & tmp239
tmp241 = tl.load(in_ptr40 + (r2 + 128 * x1), tmp240 & xmask,
eviction_policy='evict_last', other=0.0)
tmp242 = tl.where(tmp240, tmp241, tmp221)
tmp243 = tl.where(tmp236, tmp237, tmp242)
tmp244 = tl.where(tmp231, tmp232, tmp243)
tmp245 = tl.where(tmp226, tmp227, tmp244)
tmp246 = tl.full([1, 1], 44, tl.int64)
tmp247 = tmp0 >= tmp246
tmp248 = tl.full([1, 1], 45, tl.int64)
tmp249 = tmp0 < tmp248
tmp250 = tmp247 & tmp249
tmp251 = tl.load(in_ptr41 + (r2 + 128 * x1), tmp250 & xmask,
eviction_policy='evict_last', other=0.0)
tmp252 = tl.full([1, 1], 43, tl.int64)
tmp253 = tmp0 >= tmp252
tmp254 = tmp0 < tmp246
tmp255 = tmp253 & tmp254
tmp256 = tl.load(in_ptr42 + (r2 + 128 * x1), tmp255 & xmask,
eviction_policy='evict_last', other=0.0)
tmp257 = tl.full([1, 1], 42, tl.int64)
tmp258 = tmp0 >= tmp257
tmp259 = tmp0 < tmp252
tmp260 = tmp258 & tmp259
tmp261 = tl.load(in_ptr43 + (r2 + 128 * x1), tmp260 & xmask,
eviction_policy='evict_last', other=0.0)
tmp262 = tmp0 >= tmp224
tmp263 = tmp0 < tmp257
tmp264 = tmp262 & tmp263
tmp265 = tl.load(in_ptr44 + (r2 + 128 * x1), tmp264 & xmask,
eviction_policy='evict_last', other=0.0)
tmp266 = tl.where(tmp264, tmp265, tmp245)
tmp267 = tl.where(tmp260, tmp261, tmp266)
tmp268 = tl.where(tmp255, tmp256, tmp267)
tmp269 = tl.where(tmp250, tmp251, tmp268)
tmp270 = tl.full([1, 1], 48, tl.int64)
tmp271 = tmp0 >= tmp270
tmp272 = tl.full([1, 1], 49, tl.int64)
tmp273 = tmp0 < tmp272
tmp274 = tmp271 & tmp273
tmp275 = tl.load(in_ptr45 + (r2 + 128 * x1), tmp274 & xmask,
eviction_policy='evict_last', other=0.0)
tmp276 = tl.full([1, 1], 47, tl.int64)
tmp277 = tmp0 >= tmp276
tmp278 = tmp0 < tmp270
tmp279 = tmp277 & tmp278
tmp280 = tl.load(in_ptr46 + (r2 + 128 * x1), tmp279 & xmask,
eviction_policy='evict_last', other=0.0)
tmp281 = tl.full([1, 1], 46, tl.int64)
tmp282 = tmp0 >= tmp281
tmp283 = tmp0 < tmp276
tmp284 = tmp282 & tmp283
tmp285 = tl.load(in_ptr47 + (r2 + 128 * x1), tmp284 & xmask,
eviction_policy='evict_last', other=0.0)
tmp286 = tmp0 >= tmp248
tmp287 = tmp0 < tmp281
tmp288 = tmp286 & tmp287
tmp289 = tl.load(in_ptr48 + (r2 + 128 * x1), tmp288 & xmask,
eviction_policy='evict_last', other=0.0)
tmp290 = tl.where(tmp288, tmp289, tmp269)
tmp291 = tl.where(tmp284, tmp285, tmp290)
tmp292 = tl.where(tmp279, tmp280, tmp291)
tmp293 = tl.where(tmp274, tmp275, tmp292)
tmp294 = tl.full([1, 1], 52, tl.int64)
tmp295 = tmp0 >= tmp294
tmp296 = tl.full([1, 1], 53, tl.int64)
tmp297 = tmp0 < tmp296
tmp298 = tmp295 & tmp297
tmp299 = tl.load(in_ptr49 + (r2 + 128 * x1), tmp298 & xmask,
eviction_policy='evict_last', other=0.0)
tmp300 = tl.full([1, 1], 51, tl.int64)
tmp301 = tmp0 >= tmp300
tmp302 = tmp0 < tmp294
tmp303 = tmp301 & tmp302
tmp304 = tl.load(in_ptr50 + (r2 + 128 * x1), tmp303 & xmask,
eviction_policy='evict_last', other=0.0)
tmp305 = tl.full([1, 1], 50, tl.int64)
tmp306 = tmp0 >= tmp305
tmp307 = tmp0 < tmp300
tmp308 = tmp306 & tmp307
tmp309 = tl.load(in_ptr51 + (r2 + 128 * x1), tmp308 & xmask,
eviction_policy='evict_last', other=0.0)
tmp310 = tmp0 >= tmp272
tmp311 = tmp0 < tmp305
tmp312 = tmp310 & tmp311
tmp313 = tl.load(in_ptr52 + (r2 + 128 * x1), tmp312 & xmask,
eviction_policy='evict_last', other=0.0)
tmp314 = tl.where(tmp312, tmp313, tmp293)
tmp315 = tl.where(tmp308, tmp309, tmp314)
tmp316 = tl.where(tmp303, tmp304, tmp315)
tmp317 = tl.where(tmp298, tmp299, tmp316)
tmp318 = tl.full([1, 1], 56, tl.int64)
tmp319 = tmp0 >= tmp318
tmp320 = tl.full([1, 1], 57, tl.int64)
tmp321 = tmp0 < tmp320
tmp322 = tmp319 & tmp321
tmp323 = tl.load(in_ptr53 + (r2 + 128 * x1), tmp322 & xmask,
eviction_policy='evict_last', other=0.0)
tmp324 = tl.full([1, 1], 55, tl.int64)
tmp325 = tmp0 >= tmp324
tmp326 = tmp0 < tmp318
tmp327 = tmp325 & tmp326
tmp328 = tl.load(in_ptr54 + (r2 + 128 * x1), tmp327 & xmask,
eviction_policy='evict_last', other=0.0)
tmp329 = tl.full([1, 1], 54, tl.int64)
tmp330 = tmp0 >= tmp329
tmp331 = tmp0 < tmp324
tmp332 = tmp330 & tmp331
tmp333 = tl.load(in_ptr55 + (r2 + 128 * x1), tmp332 & xmask,
eviction_policy='evict_last', other=0.0)
tmp334 = tmp0 >= tmp296
tmp335 = tmp0 < tmp329
tmp336 = tmp334 & tmp335
tmp337 = tl.load(in_ptr56 + (r2 + 128 * x1), tmp336 & xmask,
eviction_policy='evict_last', other=0.0)
tmp338 = tl.where(tmp336, tmp337, tmp317)
tmp339 = tl.where(tmp332, tmp333, tmp338)
tmp340 = tl.where(tmp327, tmp328, tmp339)
tmp341 = tl.where(tmp322, tmp323, tmp340)
tmp342 = tl.full([1, 1], 60, tl.int64)
tmp343 = tmp0 >= tmp342
tmp344 = tl.full([1, 1], 61, tl.int64)
tmp345 = tmp0 < tmp344
tmp346 = tmp343 & tmp345
tmp347 = tl.load(in_ptr57 + (r2 + 128 * x1), tmp346 & xmask,
eviction_policy='evict_last', other=0.0)
tmp348 = tl.full([1, 1], 59, tl.int64)
tmp349 = tmp0 >= tmp348
tmp350 = tmp0 < tmp342
tmp351 = tmp349 & tmp350
tmp352 = tl.load(in_ptr58 + (r2 + 128 * x1), tmp351 & xmask,
eviction_policy='evict_last', other=0.0)
tmp353 = tl.full([1, 1], 58, tl.int64)
tmp354 = tmp0 >= tmp353
tmp355 = tmp0 < tmp348
tmp356 = tmp354 & tmp355
tmp357 = tl.load(in_ptr59 + (r2 + 128 * x1), tmp356 & xmask,
eviction_policy='evict_last', other=0.0)
tmp358 = tmp0 >= tmp320
tmp359 = tmp0 < tmp353
tmp360 = tmp358 & tmp359
tmp361 = tl.load(in_ptr60 + (r2 + 128 * x1), tmp360 & xmask,
eviction_policy='evict_last', other=0.0)
tmp362 = tl.where(tmp360, tmp361, tmp341)
tmp363 = tl.where(tmp356, tmp357, tmp362)
tmp364 = tl.where(tmp351, tmp352, tmp363)
tmp365 = tl.where(tmp346, tmp347, tmp364)
tmp366 = tl.full([1, 1], 63, tl.int64)
tmp367 = tmp0 >= tmp366
tmp368 = tl.load(in_ptr61 + (r2 + 128 * x1), tmp367 & xmask,
eviction_policy='evict_last', other=0.0)
tmp369 = tl.full([1, 1], 62, tl.int64)
tmp370 = tmp0 >= tmp369
tmp371 = tmp0 < tmp366
tmp372 = tmp370 & tmp371
tmp373 = tl.load(in_ptr62 + (r2 + 128 * x1), tmp372 & xmask,
eviction_policy='evict_last', other=0.0)
tmp374 = tmp0 >= tmp344
tmp375 = tmp0 < tmp369
tmp376 = tmp374 & tmp375
tmp377 = tl.load(in_ptr63 + (r2 + 128 * x1), tmp376 & xmask,
eviction_policy='evict_last', other=0.0)
tmp378 = tl.where(tmp376, tmp377, tmp365)
tmp379 = tl.where(tmp372, tmp373, tmp378)
tmp380 = tl.where(tmp367, tmp368, tmp379)
tmp381 = tmp380 * tmp380
tmp382 = tl.broadcast_to(tmp381, [XBLOCK, RBLOCK])
tmp384 = tl.where(xmask, tmp382, 0)
tmp385 = tl.sum(tmp384, 1)[:, None]
tmp386 = libdevice.sqrt(tmp385)
tl.store(in_out_ptr0 + (r2 + 128 * x3), tmp380, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x3, tmp386, xmask)
@triton.jit
def triton_red_fused_div_linalg_vector_norm_7(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 4
rnumel = 8192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
_tmp7 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (r1 + 8192 * x0), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tl.load(in_ptr1 + (64 * x0 + r1 // 128), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp2 = 1e-12
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp4 = tmp0 / tmp3
tmp5 = tmp4 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = _tmp7 + tmp6
_tmp7 = tl.where(rmask & xmask, tmp8, _tmp7)
tmp7 = tl.sum(_tmp7, 1)[:, None]
tmp9 = libdevice.sqrt(tmp7)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp9, xmask)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp10 = tl.load(in_ptr0 + (r1 + 8192 * x0), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp11 = tl.load(in_ptr1 + (64 * x0 + r1 // 128), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp12 = 1e-12
tmp13 = triton_helpers.maximum(tmp11, tmp12)
tmp14 = tmp10 / tmp13
tmp15 = triton_helpers.maximum(tmp9, tmp12)
tmp16 = tmp14 / tmp15
tl.store(out_ptr0 + (r1 + 8192 * x0), tmp16, rmask & xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 128, 64, 64), (524288, 4096, 64, 1))
assert_size_stride(primals_2, (64, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_3, (64, 128), (128, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 64, 64), (4096, 16384, 64, 1),
torch.float32)
get_raw_stream(0)
triton_red_fused_linalg_vector_norm_0[grid(16384)](primals_1, buf0,
16384, 128, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((4, 128, 64, 64), (524288, 4096, 64, 1),
torch.float32)
buf6 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152, 4096,
1), torch.float32)
buf8 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152, 4096,
1), torch.float32)
buf10 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf12 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf15 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf17 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf19 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf21 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf24 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf26 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf28 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf30 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf33 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf35 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf37 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf39 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf42 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf44 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf46 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf48 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf51 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf53 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf55 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf57 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf60 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf62 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf64 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf66 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf69 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf71 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf73 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf75 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf78 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf80 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf82 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf84 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf87 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf89 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf91 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf93 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf96 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf98 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf100 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf102 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf105 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf107 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf109 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf111 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf114 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf116 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf118 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf120 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf123 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf125 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf127 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf129 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf132 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf134 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf136 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf138 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf141 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf143 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
buf145 = empty_strided_cuda((4, 1, 128, 4096), (524288, 2097152,
4096, 1), torch.float32)
triton_poi_fused_div_sub_1[grid(2097152)](primals_1, buf0,
primals_3, buf1, buf6, buf8, buf10, buf12, buf15, buf17, buf19,
buf21, buf24, buf26, buf28, buf30, buf33, buf35, buf37, buf39,
buf42, buf44, buf46, buf48, buf51, buf53, buf55, buf57, buf60,
buf62, buf64, buf66, buf69, buf71, buf73, buf75, buf78, buf80,
buf82, buf84, buf87, buf89, buf91, buf93, buf96, buf98, buf100,
buf102, buf105, buf107, buf109, buf111, buf114, buf116, buf118,
buf120, buf123, buf125, buf127, buf129, buf132, buf134, buf136,
buf138, buf141, buf143, buf145, 2097152, XBLOCK=512, num_warps=
8, num_stages=1)
del primals_1
buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf3 = reinterpret_tensor(buf0, (4, 1, 4096), (4096, 4096, 1), 0)
del buf0
buf4 = empty_strided_cuda((4, 1, 4096), (4096, 4096, 1), torch.float32)
triton_per_fused__softmax_2[grid(16384)](buf2, buf3, buf4, 16384,
64, XBLOCK=8, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf7 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf9 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf11 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf13 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf16 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf18 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf20 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf22 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf25 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf27 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf29 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf31 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf34 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf36 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf38 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf40 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf43 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf45 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf47 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf49 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf52 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf54 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf56 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf58 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf61 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf63 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf65 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf67 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
triton_red_fused_mul_sub_sum_3[grid(512)](buf1, primals_3, buf2,
buf3, buf4, buf6, buf8, buf10, buf12, buf15, buf17, buf19,
buf21, buf24, buf26, buf28, buf30, buf33, buf35, buf37, buf39,
buf42, buf44, buf46, buf48, buf51, buf53, buf55, buf57, buf60,
buf62, buf64, buf66, buf5, buf7, buf9, buf11, buf13, buf16,
buf18, buf20, buf22, buf25, buf27, buf29, buf31, buf34, buf36,
buf38, buf40, buf43, buf45, buf47, buf49, buf52, buf54, buf56,
buf58, buf61, buf63, buf65, buf67, 512, 4096, XBLOCK=1, RBLOCK=
1024, num_warps=16, num_stages=1)
buf70 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf72 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf74 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf76 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf79 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf81 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf83 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf85 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf88 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf90 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf92 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf94 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf97 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf99 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf101 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf103 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf106 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf108 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf110 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf112 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf115 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf117 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf119 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf121 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf124 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf126 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf128 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf130 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
triton_red_fused_mul_sum_4[grid(512)](buf69, buf2, buf3, buf4,
buf71, buf73, buf75, buf78, buf80, buf82, buf84, buf87, buf89,
buf91, buf93, buf96, buf98, buf100, buf102, buf105, buf107,
buf109, buf111, buf114, buf116, buf118, buf120, buf123, buf125,
buf127, buf129, buf70, buf72, buf74, buf76, buf79, buf81, buf83,
buf85, buf88, buf90, buf92, buf94, buf97, buf99, buf101, buf103,
buf106, buf108, buf110, buf112, buf115, buf117, buf119, buf121,
buf124, buf126, buf128, buf130, 512, 4096, XBLOCK=1, RBLOCK=
1024, num_warps=16, num_stages=1)
buf133 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf135 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf137 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf139 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf142 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf144 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
buf146 = empty_strided_cuda((4, 1, 128), (128, 512, 1), torch.float32)
triton_red_fused_mul_sum_5[grid(512)](buf132, buf2, buf3, buf4,
buf134, buf136, buf138, buf141, buf143, buf145, buf133, buf135,
buf137, buf139, buf142, buf144, buf146, 512, 4096, XBLOCK=1,
RBLOCK=1024, num_warps=16, num_stages=1)
buf14 = empty_strided_cuda((4, 64, 128), (8192, 128, 1), torch.float32)
buf23 = buf14
del buf14
buf32 = buf23
del buf23
buf41 = buf32
del buf32
buf50 = buf41
del buf41
buf59 = buf50
del buf50
buf68 = buf59
del buf59
buf77 = buf68
del buf68
buf86 = buf77
del buf77
buf95 = buf86
del buf86
buf104 = buf95
del buf95
buf113 = buf104
del buf104
buf122 = buf113
del buf113
buf131 = buf122
del buf122
buf140 = buf131
del buf131
buf147 = buf140
del buf140
buf148 = empty_strided_cuda((4, 64, 1), (64, 1, 256), torch.float32)
buf149 = reinterpret_tensor(buf148, (4, 64, 1), (64, 1, 1), 0)
del buf148
triton_per_fused_copy_linalg_vector_norm_zeros_6[grid(256)](buf147,
buf149, buf13, buf11, buf9, buf7, buf5, buf22, buf20, buf18,
buf16, buf31, buf29, buf27, buf25, buf40, buf38, buf36, buf34,
buf49, buf47, buf45, buf43, buf58, buf56, buf54, buf52, buf67,
buf65, buf63, buf61, buf76, buf74, buf72, buf70, buf85, buf83,
buf81, buf79, buf94, buf92, buf90, buf88, buf103, buf101, buf99,
buf97, buf112, buf110, buf108, buf106, buf121, buf119, buf117,
buf115, buf130, buf128, buf126, buf124, buf139, buf137, buf135,
buf133, buf146, buf144, buf142, 256, 128, XBLOCK=1, num_warps=2,
num_stages=1)
del buf101
del buf103
del buf106
del buf108
del buf11
del buf110
del buf112
del buf115
del buf117
del buf119
del buf121
del buf124
del buf126
del buf128
del buf13
del buf130
del buf133
del buf135
del buf137
del buf139
del buf142
del buf144
del buf146
del buf16
del buf18
del buf20
del buf22
del buf25
del buf27
del buf29
del buf31
del buf34
del buf36
del buf38
del buf40
del buf43
del buf45
del buf47
del buf49
del buf5
del buf52
del buf54
del buf56
del buf58
del buf61
del buf63
del buf65
del buf67
del buf7
del buf70
del buf72
del buf74
del buf76
del buf79
del buf81
del buf83
del buf85
del buf88
del buf9
del buf90
del buf92
del buf94
del buf97
del buf99
buf150 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf151 = reinterpret_tensor(buf150, (4, 1), (1, 1), 0)
del buf150
buf152 = empty_strided_cuda((4, 8192), (8192, 1), torch.float32)
triton_red_fused_div_linalg_vector_norm_7[grid(4)](buf151, buf147,
buf149, buf152, 4, 8192, XBLOCK=1, RBLOCK=2048, num_warps=16,
num_stages=1)
return (buf152, primals_2, buf1, buf2, buf3, buf4, reinterpret_tensor(
primals_3, (1, 128), (128, 1), 0), buf6, buf8, buf10, buf12, buf15,
buf17, buf19, buf21, buf24, buf26, buf28, buf30, buf33, buf35,
buf37, buf39, buf42, buf44, buf46, buf48, buf51, buf53, buf55,
buf57, buf60, buf62, buf64, buf66, buf69, buf71, buf73, buf75,
buf78, buf80, buf82, buf84, buf87, buf89, buf91, buf93, buf96,
buf98, buf100, buf102, buf105, buf107, buf109, buf111, buf114,
buf116, buf118, buf120, buf123, buf125, buf127, buf129, buf132,
buf134, buf136, buf138, buf141, buf143, buf145, buf147, buf149, buf151)
class NetVLADNew(nn.Module):
"""NetVLAD layer implementation"""
def __init__(self, num_clusters=64, dim=128, normalize_input=True,
vladv2=False, use_faiss=True):
"""
Args:
num_clusters : int
The number of clusters
dim : int
Dimension of descriptors
normalize_input : bool
If true, descriptor-wise L2 normalization is applied to input.
vladv2 : bool
If true, use vladv2 otherwise use vladv1
"""
super().__init__()
self.num_clusters = num_clusters
self.dim = dim
self.alpha = 0
self.vladv2 = vladv2
self.normalize_input = normalize_input
self.conv = nn.Conv2d(dim, num_clusters, kernel_size=(1, 1), bias=
vladv2)
self.centroids = nn.Parameter(torch.rand(num_clusters, dim))
self.use_faiss = use_faiss
def init_params(self, clsts, traindescs):
if not self.vladv2:
clstsAssign = clsts / np.linalg.norm(clsts, axis=1, keepdims=True)
dots = np.dot(clstsAssign, traindescs.T)
dots.sort(0)
dots = dots[::-1, :]
self.alpha = (-np.log(0.01) / np.mean(dots[0, :] - dots[1, :])
).item()
self.centroids = nn.Parameter(torch.from_numpy(clsts))
self.conv.weight = nn.Parameter(torch.from_numpy(self.alpha *
clstsAssign).unsqueeze(2).unsqueeze(3))
self.conv.bias = None
else:
if not self.use_faiss:
knn = NearestNeighbors(n_jobs=-1)
knn.fit(traindescs)
del traindescs
ds_sq = np.square(knn.kneighbors(clsts, 2)[1])
del knn
else:
index = faiss.IndexFlatL2(traindescs.shape[1])
index.add(traindescs)
del traindescs
ds_sq = np.square(index.search(clsts, 2)[1])
del index
self.alpha = (-np.log(0.01) / np.mean(ds_sq[:, 1] - ds_sq[:, 0])
).item()
self.centroids = nn.Parameter(torch.from_numpy(clsts))
del clsts, ds_sq
self.conv.weight = nn.Parameter((2.0 * self.alpha * self.
centroids).unsqueeze(-1).unsqueeze(-1))
self.conv.bias = nn.Parameter(-self.alpha * self.centroids.norm
(dim=1))
def forward(self, input_0):
primals_3 = self.centroids
primals_2 = self.conv.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
leochien1110/Patch-NetVLAD
|
NetVLAD
| false
| 7,351
|
[
"MIT"
] | 1
|
9282217dd2c9bcf0446a05400fd277e651cecf4e
|
https://github.com/leochien1110/Patch-NetVLAD/tree/9282217dd2c9bcf0446a05400fd277e651cecf4e
|
Net
|
import torch
import torch.nn.functional as F
from torch import nn
import torch.utils.data
class Net(nn.Module):
def __init__(self, in_dim):
super().__init__()
self.fc1 = nn.Linear(in_dim, 120, bias=False)
nn.init.normal_(self.fc1.weight, mean=0, std=1)
self.fc2 = nn.Linear(120, 1, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return self.sigmoid(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 7680
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (120, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 120), (120, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 120), (120, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 120), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 120), (1920, 480, 120, 1), 0)
del buf0
buf4 = empty_strided_cuda((4, 4, 4, 120), (1920, 480, 120, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(7680)](buf1, buf4,
7680, XBLOCK=256, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 120), (120, 1), 0),
reinterpret_tensor(primals_3, (120, 1), (1, 120), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf2
triton_poi_fused_sigmoid_1[grid(64)](buf3, 64, XBLOCK=64, num_warps
=1, num_stages=1)
return buf3, reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 120), (120, 1), 0
), buf3, primals_3, buf4
class NetNew(nn.Module):
def __init__(self, in_dim):
super().__init__()
self.fc1 = nn.Linear(in_dim, 120, bias=False)
nn.init.normal_(self.fc1.weight, mean=0, std=1)
self.fc2 = nn.Linear(120, 1, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_3 = self.fc2.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
nmichlo/msc-research
|
Net
| false
| 7,352
|
[
"MIT"
] | 1
|
625e57eca77bbfbc4728ccebdb0733e1613bd258
|
https://github.com/nmichlo/msc-research/tree/625e57eca77bbfbc4728ccebdb0733e1613bd258
|
StdConv3d
|
import torch
from torch import nn
import torch.jit
import torch.nn.functional as F
import torch.nn.functional
class StdConv3d(nn.Conv3d):
def forward(self, x):
w = self.weight
v, m = torch.var_mean(w, dim=[1, 2, 3, 4], keepdim=True, unbiased=False
)
w = (w - m) / torch.sqrt(v + 1e-05)
return F.conv3d(x, w, self.bias, self.stride, self.padding, self.
dilation, self.groups)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.jit
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_sqrt_sub_var_mean_0(in_out_ptr0, in_ptr0,
out_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 256 * x0), None)
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = tl.broadcast_to(tmp1, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp6 = tl.full([1], 256, tl.int32)
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp5 / tmp7
tmp9 = tmp1 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tl.broadcast_to(tmp10, [RBLOCK])
tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0))
tmp14 = 256.0
tmp15 = tmp13 / tmp14
tmp16 = 1e-05
tmp17 = tmp15 + tmp16
tmp18 = libdevice.sqrt(tmp17)
tmp19 = tmp0 - tmp8
tmp20 = tmp19 / tmp18
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp18, None)
tl.store(out_ptr1 + (r1 + 256 * x0), tmp20, None)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch.
float32)
buf3 = reinterpret_tensor(buf1, (4, 1, 1, 1, 1), (1, 1, 1, 1, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_sqrt_sub_var_mean_0[grid(4)](buf3,
primals_1, buf4, 4, 256, num_warps=2, num_stages=1)
buf5 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), buf4, stride=(1, 1, 1),
padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf5, (1, 4, 1, 1, 1), (4, 1, 1, 1, 1))
buf6 = reinterpret_tensor(buf5, (1, 4, 1, 1, 1), (4, 1, 4, 4, 4), 0)
del buf5
triton_poi_fused_convolution_1[grid(4)](buf6, primals_2, 4, XBLOCK=
4, num_warps=1, num_stages=1)
del primals_2
return reinterpret_tensor(buf6, (4, 1, 1, 1), (1, 1, 1, 1), 0
), primals_1, buf3, buf4, reinterpret_tensor(primals_3, (1, 4, 4, 4,
4), (256, 64, 16, 4, 1), 0)
class StdConv3dNew(nn.Conv3d):
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
nntrongnghia/TDSI21-Shoulder-Muscle-Segmentation
|
StdConv3d
| false
| 7,353
|
[
"Apache-2.0"
] | 1
|
29f0f83d93e4fdd8127261283dcf9242d9914ba6
|
https://github.com/nntrongnghia/TDSI21-Shoulder-Muscle-Segmentation/tree/29f0f83d93e4fdd8127261283dcf9242d9914ba6
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 4, (3, 3), 1)
self.dropout2d_1 = nn.Dropout2d(p=0.5)
self.conv2 = nn.Conv2d(4, 32, (3, 3), 1)
self.dropout2d_2 = nn.Dropout2d(p=0.5)
self.conv3 = nn.Conv2d(32, 64, (3, 3), 1)
random_sample = torch.randn((1, 1, 128, 128))
self.flattened_number = self.get_flattened_number(random_sample)
self.dropout1 = nn.Dropout(p=0.5)
self.fc1 = nn.Linear(self.flattened_number, 64)
self.dropout2 = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 16)
self.fc4 = nn.Linear(16, 2)
def get_flattened_number(self, X):
X = F.max_pool2d(torch.relu(self.conv1(X)), (2, 2))
X = F.max_pool2d(torch.relu(self.conv2(X)), (2, 2))
X = F.max_pool2d(torch.relu(self.conv3(X)), (2, 2))
return X.shape[1] * X.shape[2] * X.shape[3]
def forward(self, X):
X = F.max_pool2d(torch.relu(self.conv1(X)), (2, 2))
X = self.dropout2d_1(X)
X = F.max_pool2d(torch.relu(self.conv2(X)), (2, 2))
X = self.dropout2d_1(X)
X = F.max_pool2d(torch.relu(self.conv3(X)), (2, 2))
X = X.view(-1, self.flattened_number)
X = self.dropout1(X)
X = torch.relu(self.fc1(X))
X = self.dropout2(X)
X = torch.relu(self.fc2(X))
X = torch.relu(self.fc3(X))
X = torch.sigmoid(self.fc4(X))
return X
def get_inputs():
return [torch.rand([4, 1, 128, 128])]
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_convolution_relu_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 254016
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 15876 % 4
x0 = xindex % 15876
x4 = xindex // 15876
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (x0 + 15904 * x4), tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 63504
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 63
x1 = xindex // 63 % 63
x2 = xindex // 3969
x3 = xindex % 3969
tmp0 = tl.load(in_ptr0 + (2 * x0 + 252 * x1 + 15904 * x2), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 252 * x1 + 15904 * x2), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (126 + 2 * x0 + 252 * x1 + 15904 * x2), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (127 + 2 * x0 + 252 * x1 + 15904 * x2), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (x3 + 4000 * x2), tmp6, xmask)
tl.store(out_ptr1 + (x3 + 4096 * x2), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 476288
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3721 % 32
x0 = xindex % 3721
x4 = xindex // 3721
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (x0 + 3744 * x4), tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 115200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 30
x1 = xindex // 30 % 30
x2 = xindex // 900
x3 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 122 * x1 + 3744 * x2), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 122 * x1 + 3744 * x2), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (61 + 2 * x0 + 122 * x1 + 3744 * x2), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (62 + 2 * x0 + 122 * x1 + 3744 * x2), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 784 % 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_5(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 50176
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)
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_relu_6(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_poi_fused_relu_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_8(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 % 16
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_9(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.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, primals_12,
primals_13, primals_14, primals_15) = args
args.clear()
assert_size_stride(primals_1, (4, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 1, 128, 128), (16384, 16384, 128, 1))
assert_size_stride(primals_4, (32, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (64, 12544), (12544, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (32, 64), (64, 1))
assert_size_stride(primals_11, (32,), (1,))
assert_size_stride(primals_12, (16, 32), (32, 1))
assert_size_stride(primals_13, (16,), (1,))
assert_size_stride(primals_14, (2, 16), (16, 1))
assert_size_stride(primals_15, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 126, 126), (63504, 15876, 126, 1))
buf1 = empty_strided_cuda((4, 4, 126, 126), (63616, 15904, 126, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(254016)](buf0, primals_2,
buf1, 254016, XBLOCK=1024, num_warps=4, num_stages=1)
del buf0
del primals_2
buf2 = empty_strided_cuda((4, 4, 63, 63), (16000, 4000, 63, 1),
torch.float32)
buf3 = empty_strided_cuda((4, 4, 63, 63), (16384, 4096, 63, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(63504)](buf1, buf2,
buf3, 63504, XBLOCK=256, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 61, 61), (119072, 3721, 61, 1))
buf5 = empty_strided_cuda((4, 32, 61, 61), (119808, 3744, 61, 1),
torch.float32)
triton_poi_fused_convolution_relu_2[grid(476288)](buf4, primals_5,
buf5, 476288, XBLOCK=1024, num_warps=4, num_stages=1)
del buf4
del primals_5
buf6 = empty_strided_cuda((4, 32, 30, 30), (28800, 900, 30, 1),
torch.float32)
buf7 = empty_strided_cuda((4, 32, 30, 30), (28800, 900, 30, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(115200)](buf5, buf6,
buf7, 115200, XBLOCK=512, num_warps=8, num_stages=1)
buf8 = 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(buf8, (4, 64, 28, 28), (50176, 784, 28, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_4[grid(200704)](buf9, primals_7,
200704, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 64, 14, 14), (12544, 196, 14, 1),
torch.int8)
buf11 = empty_strided_cuda((4, 64, 14, 14), (12544, 196, 14, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_5[grid(50176)](buf9, buf10,
buf11, 50176, XBLOCK=256, num_warps=4, num_stages=1)
buf12 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf11, (4, 12544), (12544, 1),
0), reinterpret_tensor(primals_8, (12544, 64), (1, 12544), 0),
out=buf12)
buf13 = buf12
del buf12
triton_poi_fused_relu_6[grid(256)](buf13, primals_9, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf14 = empty_strided_cuda((4, 32), (32, 1), torch.float32)
extern_kernels.mm(buf13, reinterpret_tensor(primals_10, (64, 32), (
1, 64), 0), out=buf14)
buf15 = buf14
del buf14
triton_poi_fused_relu_7[grid(128)](buf15, primals_11, 128, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_11
buf16 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.mm(buf15, reinterpret_tensor(primals_12, (32, 16), (
1, 32), 0), out=buf16)
buf17 = buf16
del buf16
triton_poi_fused_relu_8[grid(64)](buf17, primals_13, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_13
buf18 = empty_strided_cuda((4, 2), (2, 1), torch.float32)
extern_kernels.mm(buf17, reinterpret_tensor(primals_14, (16, 2), (1,
16), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_sigmoid_9[grid(8)](buf19, primals_15, 8, XBLOCK=8,
num_warps=1, num_stages=1)
del primals_15
return (buf19, primals_1, primals_3, primals_4, primals_6, buf1, buf2,
buf3, buf5, buf6, buf7, buf9, buf10, reinterpret_tensor(buf11, (4,
12544), (12544, 1), 0), buf13, buf15, buf17, buf19, primals_14,
primals_12, primals_10, primals_8)
class NetNew(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 4, (3, 3), 1)
self.dropout2d_1 = nn.Dropout2d(p=0.5)
self.conv2 = nn.Conv2d(4, 32, (3, 3), 1)
self.dropout2d_2 = nn.Dropout2d(p=0.5)
self.conv3 = nn.Conv2d(32, 64, (3, 3), 1)
random_sample = torch.randn((1, 1, 128, 128))
self.flattened_number = self.get_flattened_number(random_sample)
self.dropout1 = nn.Dropout(p=0.5)
self.fc1 = nn.Linear(self.flattened_number, 64)
self.dropout2 = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 16)
self.fc4 = nn.Linear(16, 2)
def get_flattened_number(self, X):
X = F.max_pool2d(torch.relu(self.conv1(X)), (2, 2))
X = F.max_pool2d(torch.relu(self.conv2(X)), (2, 2))
X = F.max_pool2d(torch.relu(self.conv3(X)), (2, 2))
return X.shape[1] * X.shape[2] * X.shape[3]
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_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_14 = self.fc4.weight
primals_15 = self.fc4.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15])
return output[0]
|
nathantau/BigBrain
|
Net
| false
| 7,354
|
[
"MIT"
] | 1
|
b9e81ee3ca91fadeccd59043dcc0062af1e6d365
|
https://github.com/nathantau/BigBrain/tree/b9e81ee3ca91fadeccd59043dcc0062af1e6d365
|
FF
|
import torch
import torch.nn as nn
def conv(in_channels, out_channels, kernel_size, bias=False, stride=1):
return nn.Conv2d(in_channels, out_channels, kernel_size, padding=
kernel_size // 2, bias=bias, stride=stride)
class FF(nn.Module):
def __init__(self, n_feat, kernel_size=3, bias=True):
super(FF, self).__init__()
self.conv1 = conv(n_feat, n_feat, kernel_size, bias=bias)
self.conv2 = conv(n_feat, 1, kernel_size, bias=bias)
self.conv3 = conv(1, n_feat, kernel_size, bias=bias)
def forward(self, x, x_img):
x1 = self.conv1(x)
img = self.conv2(x) + x_img
x2 = torch.sigmoid(self.conv3(img))
x1 = x1 * x2
x1 = x1 + x
return x1, img
def get_inputs():
return [torch.rand([4, 4, 64, 64]), torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {'n_feat': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr1 + x0, None)
tmp3 = tmp0 + tmp2
tmp5 = tmp3 + tmp4
tl.store(in_out_ptr0 + x0, tmp5, None)
@triton.jit
def triton_poi_fused_add_convolution_mul_sigmoid_1(in_out_ptr0, in_out_ptr1,
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)
x3 = xindex
x1 = xindex // 4096 % 4
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr1 + x3, None)
tmp4 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + x3, None)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tl.sigmoid(tmp5)
tmp7 = tmp2 * tmp6
tmp9 = tmp7 + tmp8
tl.store(in_out_ptr0 + x3, tmp2, None)
tl.store(in_out_ptr1 + x3, tmp5, None)
tl.store(out_ptr0 + x3, tmp9, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 64, 64), (16384, 4096, 64, 1))
assert_size_stride(primals_4, (1, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (1,), (1,))
assert_size_stride(primals_6, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_7, (4, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_8, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 64, 64), (16384, 4096, 64, 1))
buf2 = extern_kernels.convolution(primals_3, 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, 1, 64, 64), (4096, 4096, 64, 1))
buf3 = buf2
del buf2
get_raw_stream(0)
triton_poi_fused_add_convolution_0[grid(16384)](buf3, primals_5,
primals_6, 16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
del primals_6
buf4 = extern_kernels.convolution(buf3, primals_7, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 64, 64), (16384, 4096, 64, 1))
buf1 = buf0
del buf0
buf5 = buf4
del buf4
buf6 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.float32)
triton_poi_fused_add_convolution_mul_sigmoid_1[grid(65536)](buf1,
buf5, primals_2, primals_8, primals_3, buf6, 65536, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
del primals_8
return (buf6, buf3, primals_1, primals_3, primals_4, primals_7, buf1,
buf3, buf5)
def conv(in_channels, out_channels, kernel_size, bias=False, stride=1):
return nn.Conv2d(in_channels, out_channels, kernel_size, padding=
kernel_size // 2, bias=bias, stride=stride)
class FFNew(nn.Module):
def __init__(self, n_feat, kernel_size=3, bias=True):
super(FFNew, self).__init__()
self.conv1 = conv(n_feat, n_feat, kernel_size, bias=bias)
self.conv2 = conv(n_feat, 1, kernel_size, bias=bias)
self.conv3 = conv(1, n_feat, kernel_size, bias=bias)
def forward(self, input_0, input_1):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_7 = self.conv3.weight
primals_8 = self.conv3.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0], output[1]
|
noxsine/WTSDNet
|
FF
| false
| 7,355
|
[
"MIT"
] | 1
|
7f25fb62c705c730c4d2fab6c86f9cf3535e6d80
|
https://github.com/noxsine/WTSDNet/tree/7f25fb62c705c730c4d2fab6c86f9cf3535e6d80
|
PSNRLoss
|
import torch
from torch import nn
class PSNRLoss(nn.Module):
def __init__(self):
super(PSNRLoss, self).__init__()
self.criterion = nn.MSELoss(size_average=True)
def __repr__(self):
return 'PSNR'
def forward(self, output, target):
mse = self.criterion(output, target)
loss = 10 * torch.log10(1.0 / mse)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
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_log10_mse_loss_mul_reciprocal_0(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = 256.0
tmp8 = tmp6 / tmp7
tmp9 = tl.full([1], 1, tl.int32)
tmp10 = tmp9 / tmp8
tmp11 = 1.0
tmp12 = tmp10 * tmp11
tmp13 = libdevice.log10(tmp12)
tmp14 = 10.0
tmp15 = tmp13 * tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp15, 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_log10_mse_loss_mul_reciprocal_0[grid(1)](buf1,
arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class PSNRLossNew(nn.Module):
def __init__(self):
super(PSNRLossNew, self).__init__()
self.criterion = nn.MSELoss(size_average=True)
def __repr__(self):
return 'PSNR'
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nthuy190991/geoseg
|
PSNRLoss
| false
| 7,356
|
[
"MIT"
] | 1
|
b679af5dc558720df36dddc7abfd4e6ecb46d7de
|
https://github.com/nthuy190991/geoseg/tree/b679af5dc558720df36dddc7abfd4e6ecb46d7de
|
CELoss
|
import torch
from torch import nn
class CELoss(nn.Module):
def __init__(self):
super(CELoss, self).__init__()
self.criterionBinary = nn.BCELoss(size_average=True)
self.criterionMulti = nn.NLLLoss(size_average=True)
def __repr__(self):
return 'CE'
def forward(self, output, target):
if target.shape[1] == 1:
loss = self.criterionBinary(output, target)
else:
target = torch.argmax(target, dim=1).long()
loss = self.criterionMulti(torch.log(output), target)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_argmax_nll_loss2d_forward_0(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp17 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp32 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 > tmp1
tmp3 = tmp0 == tmp1
tmp4 = tmp0 != tmp0
tmp5 = tmp1 != tmp1
tmp6 = tmp4 > tmp5
tmp7 = tmp2 | tmp6
tmp8 = tmp4 & tmp5
tmp9 = tmp3 | tmp8
tmp10 = tl.full([1, 1], 0, tl.int64)
tmp11 = tl.full([1, 1], 1, tl.int64)
tmp12 = tmp10 < tmp11
tmp13 = tmp9 & tmp12
tmp14 = tmp7 | tmp13
tmp15 = tl.where(tmp14, tmp0, tmp1)
tmp16 = tl.where(tmp14, tmp10, tmp11)
tmp18 = tmp15 > tmp17
tmp19 = tmp15 == tmp17
tmp20 = tmp15 != tmp15
tmp21 = tmp17 != tmp17
tmp22 = tmp20 > tmp21
tmp23 = tmp18 | tmp22
tmp24 = tmp20 & tmp21
tmp25 = tmp19 | tmp24
tmp26 = tl.full([1, 1], 2, tl.int64)
tmp27 = tmp16 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tmp23 | tmp28
tmp30 = tl.where(tmp29, tmp15, tmp17)
tmp31 = tl.where(tmp29, tmp16, tmp26)
tmp33 = tmp30 > tmp32
tmp34 = tmp30 == tmp32
tmp35 = tmp30 != tmp30
tmp36 = tmp32 != tmp32
tmp37 = tmp35 > tmp36
tmp38 = tmp33 | tmp37
tmp39 = tmp35 & tmp36
tmp40 = tmp34 | tmp39
tmp41 = tl.full([1, 1], 3, tl.int64)
tmp42 = tmp31 < tmp41
tmp43 = tmp40 & tmp42
tmp44 = tmp38 | tmp43
tl.where(tmp44, tmp30, tmp32)
tmp46 = tl.where(tmp44, tmp31, tmp41)
tmp47 = tl.full([1, 1], -100, tl.int64)
tmp48 = tmp46 != tmp47
tmp49 = tl.where(tmp48, tmp46, tmp10)
tmp50 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp51 = tmp49 + tmp50
tmp52 = tmp49 < 0
tmp53 = tl.where(tmp52, tmp51, tmp49)
tl.device_assert((0 <= tmp53) & (tmp53 < 4),
'index out of bounds: 0 <= tmp53 < 4')
tmp55 = tl.load(in_ptr1 + (r0 + 16 * tmp53 + 64 * r1), None)
tmp56 = tl_math.log(tmp55)
tmp57 = -tmp56
tmp58 = 0.0
tmp59 = tl.where(tmp48, tmp57, tmp58)
tmp60 = tl.broadcast_to(tmp59, [XBLOCK, RBLOCK])
tmp62 = tl.sum(tmp60, 1)[:, None]
tmp63 = tmp48.to(tl.int64)
tmp64 = tl.broadcast_to(tmp63, [XBLOCK, RBLOCK])
tmp66 = tl.sum(tmp64, 1)[:, None]
tmp67 = tmp66.to(tl.float32)
tmp68 = tmp62 / tmp67
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp68, 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)
buf3 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_argmax_nll_loss2d_forward_0[grid(1)](buf3, arg0_1,
arg1_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf3,
class CELossNew(nn.Module):
def __init__(self):
super(CELossNew, self).__init__()
self.criterionBinary = nn.BCELoss(size_average=True)
self.criterionMulti = nn.NLLLoss(size_average=True)
def __repr__(self):
return 'CE'
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
nthuy190991/geoseg
|
CELoss
| false
| 7,357
|
[
"MIT"
] | 1
|
b679af5dc558720df36dddc7abfd4e6ecb46d7de
|
https://github.com/nthuy190991/geoseg/tree/b679af5dc558720df36dddc7abfd4e6ecb46d7de
|
RatioModel
|
import torch
import torch.nn.functional as F
class RatioModel(torch.nn.Module):
def __init__(self, D_in, hidden_unit_num):
super().__init__()
None
self.l1 = torch.nn.Linear(D_in, hidden_unit_num)
self.l2 = torch.nn.Linear(hidden_unit_num, hidden_unit_num)
self.l3 = torch.nn.Linear(hidden_unit_num, 1)
def forward(self, X):
return F.softplus(self.l3(torch.tanh(self.l2(torch.tanh(self.l1(X))))))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'D_in': 4, 'hidden_unit_num': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_softplus_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 20.0
tmp2 = tmp0 > tmp1
tmp3 = tl_math.exp(tmp0)
tmp4 = libdevice.log1p(tmp3)
tmp5 = tl.where(tmp2, tmp0, tmp4)
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(256)](buf3, primals_5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf5)
del primals_7
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_softplus_1[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf3, buf5, primals_6, primals_4
class RatioModelNew(torch.nn.Module):
def __init__(self, D_in, hidden_unit_num):
super().__init__()
None
self.l1 = torch.nn.Linear(D_in, hidden_unit_num)
self.l2 = torch.nn.Linear(hidden_unit_num, hidden_unit_num)
self.l3 = torch.nn.Linear(hidden_unit_num, 1)
def forward(self, input_0):
primals_1 = self.l1.weight
primals_2 = self.l1.bias
primals_4 = self.l2.weight
primals_5 = self.l2.bias
primals_6 = self.l3.weight
primals_7 = self.l3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
numahha/wmopo
|
RatioModel
| false
| 7,358
|
[
"MIT"
] | 1
|
1557dab2e8168c1f2e53ffbc435b4000680f1d28
|
https://github.com/numahha/wmopo/tree/1557dab2e8168c1f2e53ffbc435b4000680f1d28
|
SchedulerTestNet
|
import torch
from torch import nn as nn
from torch.nn import functional as F
from torch import optim as optim
class SchedulerTestNet(torch.nn.Module):
"""
adapted from: https://github.com/pytorch/pytorch/blob/master/test/test_optim.py
"""
def __init__(self):
super(SchedulerTestNet, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 1, 1)
self.conv2 = torch.nn.Conv2d(1, 1, 1)
def forward(self, x):
return self.conv2(F.relu(self.conv1(x)))
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tl.store(in_out_ptr0 + x0, tmp5, 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)
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 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (1, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(16384)](buf1, primals_2,
16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(16384)](buf3, primals_5, 16384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1
class SchedulerTestNetNew(torch.nn.Module):
"""
adapted from: https://github.com/pytorch/pytorch/blob/master/test/test_optim.py
"""
def __init__(self):
super(SchedulerTestNetNew, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 1, 1)
self.conv2 = torch.nn.Conv2d(1, 1, 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_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
oke-aditya/pytorch-lightning-bolts
|
SchedulerTestNet
| false
| 7,359
|
[
"Apache-2.0"
] | 1
|
268df20bb442e7385b709b1488d37fd2767aba3c
|
https://github.com/oke-aditya/pytorch-lightning-bolts/tree/268df20bb442e7385b709b1488d37fd2767aba3c
|
DynamicsModel
|
import torch
class DynamicsModel(torch.nn.Module):
def __init__(self, D_in, D_out, hidden_unit_num):
None
super(DynamicsModel, self).__init__()
self.l1 = torch.nn.Linear(D_in, hidden_unit_num)
self.l2 = torch.nn.Linear(hidden_unit_num, D_out)
self.logvar = torch.nn.Parameter(torch.zeros(D_out), requires_grad=True
)
def forward(self, X):
mu = self.l2(torch.tanh(self.l1(X)))
return self.l2(torch.tanh(self.l1(X))), self.logvar * torch.ones_like(
mu)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'D_in': 4, 'D_out': 4, 'hidden_unit_num': 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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_mul_ones_like_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_ones_like_1[grid(256)](primals_6, buf3, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_6
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, primals_4
class DynamicsModelNew(torch.nn.Module):
def __init__(self, D_in, D_out, hidden_unit_num):
None
super(DynamicsModelNew, self).__init__()
self.l1 = torch.nn.Linear(D_in, hidden_unit_num)
self.l2 = torch.nn.Linear(hidden_unit_num, D_out)
self.logvar = torch.nn.Parameter(torch.zeros(D_out), requires_grad=True
)
def forward(self, input_0):
primals_2 = self.logvar
primals_1 = self.l1.weight
primals_5 = self.l1.bias
primals_4 = self.l2.weight
primals_6 = self.l2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0], output[1]
|
numahha/wmopo
|
DynamicsModel
| false
| 7,360
|
[
"MIT"
] | 1
|
1557dab2e8168c1f2e53ffbc435b4000680f1d28
|
https://github.com/numahha/wmopo/tree/1557dab2e8168c1f2e53ffbc435b4000680f1d28
|
MultipleInputModel
|
import torch
from torch import nn as nn
from torch import optim as optim
class TemplateModel(nn.Module):
def __init__(self, mix_data=False):
""" Base model for testing. The setting ``mix_data=True`` simulates a wrong implementation. """
super().__init__()
self.mix_data = mix_data
self.linear = nn.Linear(10, 5)
self.input_array = torch.rand(10, 5, 2)
def forward(self, *args, **kwargs):
return self.forward__standard(*args, **kwargs)
def forward__standard(self, x):
if self.mix_data:
x = x.view(10, -1).permute(1, 0).view(-1, 10)
else:
x = x.view(-1, 10)
return self.linear(x)
class MultipleInputModel(TemplateModel):
""" Base model for testing verification when forward accepts multiple arguments. """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.input_array = torch.rand(10, 5, 2), torch.rand(10, 5, 2)
def forward(self, x, y, some_kwarg=True):
out = super().forward(x) + super().forward(y)
return out
def get_inputs():
return [torch.rand([4, 10]), torch.rand([4, 10])]
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 import nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 20
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 5
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp3 + tmp1
tmp5 = tmp2 + tmp4
tl.store(in_out_ptr0 + x2, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 10), (10, 1))
assert_size_stride(primals_2, (5, 10), (10, 1))
assert_size_stride(primals_3, (5,), (1,))
assert_size_stride(primals_4, (4, 10), (10, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 5), (5, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (10, 5),
(1, 10), 0), out=buf0)
buf1 = empty_strided_cuda((4, 5), (5, 1), torch.float32)
extern_kernels.mm(primals_4, reinterpret_tensor(primals_2, (10, 5),
(1, 10), 0), out=buf1)
del primals_2
buf2 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(20)](buf2, primals_3, buf1, 20, XBLOCK=
32, num_warps=1, num_stages=1)
del buf1
del primals_3
return buf2, primals_1, primals_4
class TemplateModel(nn.Module):
def __init__(self, mix_data=False):
""" Base model for testing. The setting ``mix_data=True`` simulates a wrong implementation. """
super().__init__()
self.mix_data = mix_data
self.linear = nn.Linear(10, 5)
self.input_array = torch.rand(10, 5, 2)
def forward(self, *args, **kwargs):
return self.forward__standard(*args, **kwargs)
def forward__standard(self, x):
if self.mix_data:
x = x.view(10, -1).permute(1, 0).view(-1, 10)
else:
x = x.view(-1, 10)
return self.linear(x)
class MultipleInputModelNew(TemplateModel):
""" Base model for testing verification when forward accepts multiple arguments. """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.input_array = torch.rand(10, 5, 2), torch.rand(10, 5, 2)
def forward(self, input_0, input_1):
primals_2 = self.linear.weight
primals_3 = self.linear.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
oke-aditya/pytorch-lightning-bolts
|
MultipleInputModel
| false
| 7,361
|
[
"Apache-2.0"
] | 1
|
268df20bb442e7385b709b1488d37fd2767aba3c
|
https://github.com/oke-aditya/pytorch-lightning-bolts/tree/268df20bb442e7385b709b1488d37fd2767aba3c
|
FakeRKHSConvNet
|
import math
import torch
import numpy as np
from torch import nn as nn
from torch import optim as optim
class MaybeBatchNorm2d(nn.Module):
def __init__(self, n_ftr, affine, use_bn):
super(MaybeBatchNorm2d, self).__init__()
self.bn = nn.BatchNorm2d(n_ftr, affine=affine)
self.use_bn = use_bn
def forward(self, x):
if self.use_bn:
x = self.bn(x)
return x
class FakeRKHSConvNet(nn.Module):
def __init__(self, n_input, n_output, use_bn=False):
super(FakeRKHSConvNet, self).__init__()
self.conv1 = nn.Conv2d(n_input, n_output, kernel_size=1, stride=1,
padding=0, bias=False)
self.bn1 = MaybeBatchNorm2d(n_output, True, use_bn)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(n_output, n_output, kernel_size=1, stride=1,
padding=0, bias=False)
self.bn_out = MaybeBatchNorm2d(n_output, True, True)
self.shortcut = nn.Conv2d(n_input, n_output, kernel_size=1, stride=
1, padding=0, bias=True)
if n_output >= n_input:
eye_mask = np.zeros((n_output, n_input, 1, 1), dtype=np.bool)
for i in range(n_input):
eye_mask[i, i, 0, 0] = 1
self.shortcut.weight.data.uniform_(-0.01, 0.01)
self.shortcut.weight.data.masked_fill_(torch.tensor(eye_mask), 1.0)
def init_weights(self, init_scale=1.0):
nn.init.kaiming_uniform_(self.conv1.weight, a=math.sqrt(5))
self.conv1.weight.data.mul_(init_scale)
nn.init.constant_(self.conv2.weight, 0.0)
def forward(self, x):
h_res = self.conv2(self.relu1(self.bn1(self.conv1(x))))
h = self.bn_out(h_res + self.shortcut(x))
return h
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_input': 4, 'n_output': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import math
import numpy as np
from torch import nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__native_batch_norm_legit_no_training_add_convolution_native_batch_norm_backward_1(
in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr6 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp6 = tmp4 - tmp5
tmp8 = 1e-05
tmp9 = tmp7 + tmp8
tmp10 = libdevice.sqrt(tmp9)
tmp11 = tl.full([1], 1, tl.int32)
tmp12 = tmp11 / tmp10
tmp13 = 1.0
tmp14 = tmp12 * tmp13
tmp15 = tmp6 * tmp14
tmp17 = tmp15 * tmp16
tmp19 = tmp17 + tmp18
tl.store(out_ptr0 + x3, tmp19, xmask)
tl.store(out_ptr1 + x3, tmp6, 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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 1, 1), (4, 1, 1, 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,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](buf1, 256, XBLOCK=256, num_warps
=4, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = extern_kernels.convolution(primals_2, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__native_batch_norm_legit_no_training_add_convolution_native_batch_norm_backward_1[
grid(256)](buf2, buf3, primals_5, primals_6, primals_7,
primals_8, primals_9, buf4, buf5, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del buf3
del primals_5
del primals_6
del primals_9
return (buf4, primals_1, primals_2, primals_3, primals_4, primals_7,
primals_8, buf1, buf5)
class MaybeBatchNorm2d(nn.Module):
def __init__(self, n_ftr, affine, use_bn):
super(MaybeBatchNorm2d, self).__init__()
self.bn = nn.BatchNorm2d(n_ftr, affine=affine)
self.use_bn = use_bn
def forward(self, x):
if self.use_bn:
x = self.bn(x)
return x
class FakeRKHSConvNetNew(nn.Module):
def __init__(self, n_input, n_output, use_bn=False):
super(FakeRKHSConvNetNew, self).__init__()
self.conv1 = nn.Conv2d(n_input, n_output, kernel_size=1, stride=1,
padding=0, bias=False)
self.bn1 = MaybeBatchNorm2d(n_output, True, use_bn)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(n_output, n_output, kernel_size=1, stride=1,
padding=0, bias=False)
self.bn_out = MaybeBatchNorm2d(n_output, True, True)
self.shortcut = nn.Conv2d(n_input, n_output, kernel_size=1, stride=
1, padding=0, bias=True)
if n_output >= n_input:
eye_mask = np.zeros((n_output, n_input, 1, 1), dtype=np.bool)
for i in range(n_input):
eye_mask[i, i, 0, 0] = 1
self.shortcut.weight.data.uniform_(-0.01, 0.01)
self.shortcut.weight.data.masked_fill_(torch.tensor(eye_mask), 1.0)
def init_weights(self, init_scale=1.0):
nn.init.kaiming_uniform_(self.conv1.weight, a=math.sqrt(5))
self.conv1.weight.data.mul_(init_scale)
nn.init.constant_(self.conv2.weight, 0.0)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_5 = self.bn1.bn.weight
primals_6 = self.bn1.bn.bias
primals_3 = self.conv2.weight
primals_7 = self.bn_out.bn.weight
primals_8 = self.bn_out.bn.bias
primals_4 = self.shortcut.weight
primals_9 = self.shortcut.bias
primals_2 = 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]
|
oke-aditya/pytorch-lightning-bolts
|
FakeRKHSConvNet
| false
| 7,362
|
[
"Apache-2.0"
] | 1
|
268df20bb442e7385b709b1488d37fd2767aba3c
|
https://github.com/oke-aditya/pytorch-lightning-bolts/tree/268df20bb442e7385b709b1488d37fd2767aba3c
|
AgentA2C
|
import torch
import torch.nn as nn
class AgentA2C(nn.Module):
def __init__(self, state_shape, n_actions):
super().__init__()
self.name = 'a2c'
self.n_actions = n_actions
self.state_shape = state_shape
self.hidden1 = nn.Linear(self.state_shape, 100)
self.act1 = nn.ReLU()
self.hidden2 = nn.Linear(100, 100)
self.act2 = nn.ReLU()
self.out1 = nn.Linear(100, self.n_actions)
self.out2 = nn.Linear(100, 1)
def forward(self, state_t):
h = self.act1(self.hidden1(state_t))
h = self.act2(self.hidden2(h))
logits = self.out1(h)
value = self.out2(h)
return logits, value
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_shape': 4, 'n_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 100
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, 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, (100, 4), (4, 1))
assert_size_stride(primals_2, (100,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (100, 100), (100, 1))
assert_size_stride(primals_5, (100,), (1,))
assert_size_stride(primals_6, (4, 100), (100, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (1, 100), (100, 1))
assert_size_stride(primals_9, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 100), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf0
buf8 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(6400)](buf1,
primals_2, buf8, 6400, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 100), (100, 1), 0),
reinterpret_tensor(primals_4, (100, 100), (1, 100), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf2
buf7 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(6400)](buf3,
primals_5, buf7, 6400, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 100),
(100, 1), 0), reinterpret_tensor(primals_6, (100, 4), (1, 100),
0), alpha=1, beta=1, out=buf4)
del primals_7
buf6 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf3, (64, 100),
(100, 1), 0), reinterpret_tensor(primals_8, (100, 1), (1, 100),
0), alpha=1, beta=1, out=buf6)
del primals_9
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 100), (100, 1), 0
), reinterpret_tensor(buf3, (64, 100), (100, 1), 0
), primals_8, primals_6, buf7, primals_4, buf8
class AgentA2CNew(nn.Module):
def __init__(self, state_shape, n_actions):
super().__init__()
self.name = 'a2c'
self.n_actions = n_actions
self.state_shape = state_shape
self.hidden1 = nn.Linear(self.state_shape, 100)
self.act1 = nn.ReLU()
self.hidden2 = nn.Linear(100, 100)
self.act2 = nn.ReLU()
self.out1 = nn.Linear(100, self.n_actions)
self.out2 = nn.Linear(100, 1)
def forward(self, input_0):
primals_1 = self.hidden1.weight
primals_2 = self.hidden1.bias
primals_4 = self.hidden2.weight
primals_5 = self.hidden2.bias
primals_6 = self.out1.weight
primals_7 = self.out1.bias
primals_8 = self.out2.weight
primals_9 = self.out2.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], output[1]
|
onimaru/Reinforcement_Learning
|
AgentA2C
| false
| 7,363
|
[
"MIT"
] | 1
|
4c45b51a095cb0cb3c18f6a1542befdcab8a58a4
|
https://github.com/onimaru/Reinforcement_Learning/tree/4c45b51a095cb0cb3c18f6a1542befdcab8a58a4
|
VishalNet
|
import torch
import torch.nn as nn
class VishalNet(nn.Module):
def __init__(self):
super(VishalNet, self).__init__()
self.cnn1 = nn.Conv1d(1, 60, 81, 1, 40)
self.cnn2 = nn.Conv1d(60, 1, 301, 1, 150)
def forward(self, input):
out1 = nn.functional.relu(self.cnn1(input))
out2 = self.cnn2(out1)
return out2
def get_inputs():
return [torch.rand([4, 1, 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
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 15360
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 64 % 60
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (60, 1, 81), (81, 81, 1))
assert_size_stride(primals_2, (60,), (1,))
assert_size_stride(primals_3, (4, 1, 64), (64, 64, 1))
assert_size_stride(primals_4, (1, 60, 301), (18060, 301, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,),
padding=(40,), dilation=(1,), transposed=False, output_padding=
(0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 60, 64), (3840, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(15360)](buf1, primals_2,
15360, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1,),
padding=(150,), dilation=(1,), transposed=False, output_padding
=(0,), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 64), (64, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(256)](buf3, primals_5, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1
class VishalNetNew(nn.Module):
def __init__(self):
super(VishalNetNew, self).__init__()
self.cnn1 = nn.Conv1d(1, 60, 81, 1, 40)
self.cnn2 = nn.Conv1d(60, 1, 301, 1, 150)
def forward(self, input_0):
primals_1 = self.cnn1.weight
primals_2 = self.cnn1.bias
primals_4 = self.cnn2.weight
primals_5 = self.cnn2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
olivesgatech/Geophysics-2021-Joint-learning-for-spatial-context-based-inversion
|
VishalNet
| false
| 7,364
|
[
"MIT"
] | 1
|
56f506dfe62ac3557febb4c8e3c62542b1624a1b
|
https://github.com/olivesgatech/Geophysics-2021-Joint-learning-for-spatial-context-based-inversion/tree/56f506dfe62ac3557febb4c8e3c62542b1624a1b
|
L2Norm
|
import torch
from torch import nn
class L2Norm(nn.Module):
def forward(self, x, eps=1e-06):
norm = x.norm(dim=1, keepdim=True).clamp(min=eps)
return x / norm
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_div_linalg_vector_norm_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')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-06
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x3, tmp15, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_div_linalg_vector_norm_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class L2NormNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
onlyrico/vit-pytorch
|
L2Norm
| false
| 7,365
|
[
"MIT"
] | 1
|
e52ac4195550faa9c3372533d325bf649f7354ad
|
https://github.com/onlyrico/vit-pytorch/tree/e52ac4195550faa9c3372533d325bf649f7354ad
|
AgentReinforce
|
import torch
import torch.nn as nn
class AgentReinforce(nn.Module):
def __init__(self, state_shape, n_actions):
super().__init__()
self.name = 'reinforce'
self.n_actions = n_actions
self.state_shape = state_shape
self.hidden1 = nn.Linear(self.state_shape, 100)
self.act1 = nn.ReLU()
self.hidden2 = nn.Linear(100, 100)
self.act2 = nn.ReLU()
self.out1 = nn.Linear(100, self.n_actions)
def forward(self, state_t):
h = self.act1(self.hidden1(state_t))
h = self.act2(self.hidden2(h))
logits = self.out1(h)
return logits
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_shape': 4, 'n_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 100
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (100, 4), (4, 1))
assert_size_stride(primals_2, (100,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (100, 100), (100, 1))
assert_size_stride(primals_5, (100,), (1,))
assert_size_stride(primals_6, (4, 100), (100, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 100), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(6400)](buf1,
primals_2, buf6, 6400, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 100), (100, 1), 0),
reinterpret_tensor(primals_4, (100, 100), (1, 100), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(6400)](buf3,
primals_5, buf5, 6400, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 100),
(100, 1), 0), reinterpret_tensor(primals_6, (100, 4), (1, 100),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 100), (100, 1), 0
), reinterpret_tensor(buf3, (64, 100), (100, 1), 0
), primals_6, buf5, primals_4, buf6
class AgentReinforceNew(nn.Module):
def __init__(self, state_shape, n_actions):
super().__init__()
self.name = 'reinforce'
self.n_actions = n_actions
self.state_shape = state_shape
self.hidden1 = nn.Linear(self.state_shape, 100)
self.act1 = nn.ReLU()
self.hidden2 = nn.Linear(100, 100)
self.act2 = nn.ReLU()
self.out1 = nn.Linear(100, self.n_actions)
def forward(self, input_0):
primals_1 = self.hidden1.weight
primals_2 = self.hidden1.bias
primals_4 = self.hidden2.weight
primals_5 = self.hidden2.bias
primals_6 = self.out1.weight
primals_7 = self.out1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
onimaru/Reinforcement_Learning
|
AgentReinforce
| false
| 7,366
|
[
"MIT"
] | 1
|
4c45b51a095cb0cb3c18f6a1542befdcab8a58a4
|
https://github.com/onimaru/Reinforcement_Learning/tree/4c45b51a095cb0cb3c18f6a1542befdcab8a58a4
|
AmdimNCELoss
|
import torch
from torch import nn as nn
from torch import optim as optim
def tanh_clip(x, clip_val=10.0):
"""
soft clip values to the range [-clip_val, +clip_val]
"""
if clip_val is not None:
x_clip = clip_val * torch.tanh(1.0 / clip_val * x)
else:
x_clip = x
return x_clip
class AmdimNCELoss(nn.Module):
"""
Compute the NCE scores for predicting r_src->r_trg.
"""
def __init__(self, tclip):
super().__init__()
self.tclip = tclip
def forward(self, anchor_representations, positive_representations,
mask_mat):
"""
Args:
anchor_representations: (batch_size, emb_dim)
positive_representations: (emb_dim, n_batch * w* h) (ie: nb_feat_vectors x embedding_dim)
mask_mat: (n_batch_gpu, n_batch)
Output:
raw_scores: (n_batch_gpu, n_locs)
nce_scores: (n_batch_gpu, n_locs)
lgt_reg : scalar
"""
r_src = anchor_representations
r_trg = positive_representations
batch_size, emb_dim = r_src.size()
nb_feat_vectors = r_trg.size(1) // batch_size
mask_pos = mask_mat.unsqueeze(dim=2).expand(-1, -1, nb_feat_vectors
).float()
mask_neg = 1.0 - mask_pos
raw_scores = torch.mm(r_src, r_trg).float()
raw_scores = raw_scores.reshape(batch_size, batch_size, nb_feat_vectors
)
raw_scores = raw_scores / emb_dim ** 0.5
lgt_reg = 0.05 * (raw_scores ** 2.0).mean()
raw_scores = tanh_clip(raw_scores, clip_val=self.tclip)
"""
pos_scores includes scores for all the positive samples
neg_scores includes scores for all the negative samples, with
scores for positive samples set to the min score (-self.tclip here)
"""
pos_scores = (mask_pos * raw_scores).sum(dim=1)
neg_scores = mask_neg * raw_scores - self.tclip * mask_pos
neg_scores = neg_scores.reshape(batch_size, -1)
mask_neg = mask_neg.reshape(batch_size, -1)
neg_maxes = torch.max(neg_scores, dim=1, keepdim=True)[0]
neg_sumexp = (mask_neg * torch.exp(neg_scores - neg_maxes)).sum(dim
=1, keepdim=True)
all_logsumexp = torch.log(torch.exp(pos_scores - neg_maxes) +
neg_sumexp)
pos_shiftexp = pos_scores - neg_maxes
nce_scores = pos_shiftexp - all_logsumexp
nce_scores = -nce_scores.mean()
return nce_scores, lgt_reg
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'tclip': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch import nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp36 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp38 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = 0.5
tmp5 = tmp3 * tmp4
tmp6 = 0.25
tmp7 = tmp5 * tmp6
tmp8 = libdevice.tanh(tmp7)
tmp9 = 4.0
tmp10 = tmp8 * tmp9
tmp11 = tmp2 * tmp10
tmp12 = tmp0 * tmp9
tmp13 = tmp11 - tmp12
tmp15 = tmp1 - tmp14
tmp17 = tmp16 * tmp4
tmp18 = tmp17 * tmp6
tmp19 = libdevice.tanh(tmp18)
tmp20 = tmp19 * tmp9
tmp21 = tmp15 * tmp20
tmp22 = tmp14 * tmp9
tmp23 = tmp21 - tmp22
tmp24 = triton_helpers.maximum(tmp13, tmp23)
tmp26 = tmp1 - tmp25
tmp28 = tmp27 * tmp4
tmp29 = tmp28 * tmp6
tmp30 = libdevice.tanh(tmp29)
tmp31 = tmp30 * tmp9
tmp32 = tmp26 * tmp31
tmp33 = tmp25 * tmp9
tmp34 = tmp32 - tmp33
tmp35 = triton_helpers.maximum(tmp24, tmp34)
tmp37 = tmp1 - tmp36
tmp39 = tmp38 * tmp4
tmp40 = tmp39 * tmp6
tmp41 = libdevice.tanh(tmp40)
tmp42 = tmp41 * tmp9
tmp43 = tmp37 * tmp42
tmp44 = tmp36 * tmp9
tmp45 = tmp43 - tmp44
tmp46 = triton_helpers.maximum(tmp35, tmp45)
tmp47 = tmp13 - tmp46
tmp48 = tl_math.exp(tmp47)
tmp49 = tmp2 * tmp48
tmp50 = tmp23 - tmp46
tmp51 = tl_math.exp(tmp50)
tmp52 = tmp15 * tmp51
tmp53 = tmp49 + tmp52
tmp54 = tmp34 - tmp46
tmp55 = tl_math.exp(tmp54)
tmp56 = tmp26 * tmp55
tmp57 = tmp53 + tmp56
tmp58 = tmp45 - tmp46
tmp59 = tl_math.exp(tmp58)
tmp60 = tmp37 * tmp59
tmp61 = tmp57 + tmp60
tmp62 = tmp0 * tmp10
tmp63 = tmp14 * tmp20
tmp64 = tmp62 + tmp63
tmp65 = tmp25 * tmp31
tmp66 = tmp64 + tmp65
tmp67 = tmp36 * tmp42
tmp68 = tmp66 + tmp67
tmp69 = tmp68 - tmp46
tmp70 = tl_math.exp(tmp69)
tmp71 = tmp70 + tmp61
tmp72 = tl_math.log(tmp71)
tmp73 = tmp69 - tmp72
tmp74 = tl.broadcast_to(tmp73, [XBLOCK, RBLOCK])
tmp76 = tl.sum(tmp74, 1)[:, None]
tmp77 = tmp76 / tmp9
tmp78 = -tmp77
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp78, None)
@triton.jit
def triton_per_fused_div_mean_mul_pow_1(in_out_ptr0, in_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.sum(tmp4, 1)[:, None]
tmp7 = 16.0
tmp8 = tmp6 / tmp7
tmp9 = 0.05
tmp10 = tmp8 * tmp9
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 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, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg0_1, arg1_1, out=buf0)
del arg0_1
del arg1_1
buf4 = empty_strided_cuda((), (), torch.float32)
buf6 = buf4
del buf4
get_raw_stream(0)
triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0[grid
(1)](buf6, arg2_1, buf0, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg2_1
buf5 = empty_strided_cuda((), (), torch.float32)
buf7 = buf5
del buf5
triton_per_fused_div_mean_mul_pow_1[grid(1)](buf7, buf0, 1, 16,
XBLOCK=1, num_warps=2, num_stages=1)
del buf0
return buf6, buf7
def tanh_clip(x, clip_val=10.0):
"""
soft clip values to the range [-clip_val, +clip_val]
"""
if clip_val is not None:
x_clip = clip_val * torch.tanh(1.0 / clip_val * x)
else:
x_clip = x
return x_clip
class AmdimNCELossNew(nn.Module):
"""
Compute the NCE scores for predicting r_src->r_trg.
"""
def __init__(self, tclip):
super().__init__()
self.tclip = tclip
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0], output[1]
|
oke-aditya/pytorch-lightning-bolts
|
AmdimNCELoss
| false
| 7,367
|
[
"Apache-2.0"
] | 1
|
268df20bb442e7385b709b1488d37fd2767aba3c
|
https://github.com/oke-aditya/pytorch-lightning-bolts/tree/268df20bb442e7385b709b1488d37fd2767aba3c
|
ConditionTime
|
import torch
from torch import nn as nn
def condition_time(x, i=0, size=(12, 16), seq_len=15):
"""create one hot encoded time image-layers, i in [1, seq_len]"""
assert i < seq_len
times = torch.eye(seq_len, dtype=x.dtype, device=x.device)[i].unsqueeze(-1
).unsqueeze(-1)
ones = torch.ones(1, *size, dtype=x.dtype, device=x.device)
return times * ones
class ConditionTime(nn.Module):
"""Condition Time on a stack of images, adds `horizon` channels to image"""
def __init__(self, horizon, ch_dim=2, num_dims=5):
super().__init__()
self.horizon = horizon
self.ch_dim = ch_dim
self.num_dims = num_dims
def forward(self, x, fstep=0):
"""x stack of images, fsteps"""
if self.num_dims == 5:
bs, seq_len, ch, h, w = x.shape
ct = condition_time(x, fstep, (h, w), seq_len=self.horizon).repeat(
bs, seq_len, 1, 1, 1)
else:
bs, h, w, ch = x.shape
ct = condition_time(x, fstep, (h, w), seq_len=self.horizon).repeat(
bs, 1, 1, 1)
ct = ct.permute(0, 2, 3, 1)
x = torch.cat([x, ct], dim=self.ch_dim)
assert x.shape[self.ch_dim] == ch + self.horizon
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4, 4])]
def get_init_inputs():
return [[], {'horizon': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn 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):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = -4 + x1
tmp10 = tmp1 == tmp9
tmp11 = 1.0
tmp12 = 0.0
tmp13 = tl.where(tmp10, tmp11, tmp12)
tmp14 = tmp13 * tmp11
tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype)
tmp16 = tl.where(tmp6, tmp14, tmp15)
tmp17 = tl.where(tmp4, tmp5, tmp16)
tl.store(out_ptr0 + x3, tmp17, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 8, 4, 4), (512, 128, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(2048)](arg0_1, buf0, 2048, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
def condition_time(x, i=0, size=(12, 16), seq_len=15):
"""create one hot encoded time image-layers, i in [1, seq_len]"""
assert i < seq_len
times = torch.eye(seq_len, dtype=x.dtype, device=x.device)[i].unsqueeze(-1
).unsqueeze(-1)
ones = torch.ones(1, *size, dtype=x.dtype, device=x.device)
return times * ones
class ConditionTimeNew(nn.Module):
"""Condition Time on a stack of images, adds `horizon` channels to image"""
def __init__(self, horizon, ch_dim=2, num_dims=5):
super().__init__()
self.horizon = horizon
self.ch_dim = ch_dim
self.num_dims = num_dims
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
openclimatefix/MetNet
|
ConditionTime
| false
| 7,368
|
[
"MIT"
] | 1
|
06eed550e93da6325641958b0d36c15adde1d928
|
https://github.com/openclimatefix/MetNet/tree/06eed550e93da6325641958b0d36c15adde1d928
|
_ImpalaBlock
|
import torch
from torch import nn
class _ImpalaResBlock(nn.Module):
def __init__(self, n_channels: 'int'):
super().__init__()
self.n_channels = n_channels
kernel_size = 3
padding = 1
self.relu = nn.ReLU()
self.relu_inplace = nn.ReLU()
self.conv1 = nn.Conv2d(n_channels, n_channels, kernel_size, padding
=padding)
self.conv2 = nn.Conv2d(n_channels, n_channels, kernel_size, padding
=padding)
def forward(self, inputs):
x = self.relu(inputs)
x = self.conv1(x)
x = self.relu_inplace(x)
x = self.conv2(x)
x += inputs
return x
class _ImpalaBlock(nn.Module):
def __init__(self, n_channels_in: 'int', n_channels_out: 'int'):
super().__init__()
self.n_channels_in = n_channels_in
self.n_channels_out = n_channels_out
kernel_size = 3
padding = 1
self.conv1 = nn.Conv2d(n_channels_in, n_channels_out, kernel_size,
padding=padding)
self.pool = nn.MaxPool2d(kernel_size, stride=2, padding=padding)
self.res1 = _ImpalaResBlock(n_channels_out)
self.res2 = _ImpalaResBlock(n_channels_out)
def forward(self, x):
x = self.conv1(x)
x = self.pool(x)
x = self.res1(x)
x = self.res2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_channels_in': 4, 'n_channels_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_1(in_ptr0, out_ptr0,
out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 2 % 2
x0 = xindex % 2
x4 = xindex // 2
x3 = xindex
tmp0 = -1 + 2 * x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + 2 * x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x4), tmp10 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp12 = 2 * x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x4), tmp16 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + 2 * x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-3 + 2 * x0 + 8 * x4), tmp23 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = 2 * x1
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x4), tmp30 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + (2 * x0 + 8 * x4), tmp33 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x4), tmp36 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = 1 + 2 * x1
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (3 + 2 * x0 + 8 * x4), tmp43 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp38)
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x4), tmp46 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x4), tmp49 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp51 = triton_helpers.maximum(tmp50, tmp48)
tmp52 = tmp17 > tmp11
tmp53 = tl.full([1], 1, tl.int8)
tmp54 = tl.full([1], 0, tl.int8)
tmp55 = tl.where(tmp52, tmp53, tmp54)
tmp56 = tmp24 > tmp18
tmp57 = tl.full([1], 2, tl.int8)
tmp58 = tl.where(tmp56, tmp57, tmp55)
tmp59 = tmp31 > tmp25
tmp60 = tl.full([1], 3, tl.int8)
tmp61 = tl.where(tmp59, tmp60, tmp58)
tmp62 = tmp34 > tmp32
tmp63 = tl.full([1], 4, tl.int8)
tmp64 = tl.where(tmp62, tmp63, tmp61)
tmp65 = tmp37 > tmp35
tmp66 = tl.full([1], 5, tl.int8)
tmp67 = tl.where(tmp65, tmp66, tmp64)
tmp68 = tmp44 > tmp38
tmp69 = tl.full([1], 6, tl.int8)
tmp70 = tl.where(tmp68, tmp69, tmp67)
tmp71 = tmp47 > tmp45
tmp72 = tl.full([1], 7, tl.int8)
tmp73 = tl.where(tmp71, tmp72, tmp70)
tmp74 = tmp50 > tmp48
tmp75 = tl.full([1], 8, tl.int8)
tmp76 = tl.where(tmp74, tmp75, tmp73)
tmp77 = tl.full([1], 0, tl.int32)
tmp78 = triton_helpers.maximum(tmp77, tmp51)
tl.store(out_ptr0 + x3, tmp51, xmask)
tl.store(out_ptr1 + x3, tmp76, xmask)
tl.store(out_ptr2 + x3, tmp78, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_convolution_relu_3(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
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.full([1], 0, tl.int32)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tl.store(out_ptr0 + x3, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_convolution_4(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
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')
tmp6 = tl.load(in_ptr3 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp2 + tmp7
tl.store(in_out_ptr0 + x3, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(256)](buf1, primals_2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.int8)
buf4 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused_max_pool2d_with_indices_relu_1[grid(64)](buf1,
buf2, buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf5 = extern_kernels.convolution(buf4, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 4, 2, 2), (16, 4, 2, 1))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_2[grid(64)](buf6, primals_5, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
buf7 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 4, 2, 2), (16, 4, 2, 1))
buf8 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused_add_convolution_relu_3[grid(64)](buf7, primals_7,
buf2, buf8, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(buf8, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 2, 2), (16, 4, 2, 1))
buf10 = buf9
del buf9
triton_poi_fused_convolution_relu_2[grid(64)](buf10, primals_9, 64,
XBLOCK=64, num_warps=1, 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, 4, 2, 2), (16, 4, 2, 1))
buf12 = buf11
del buf11
triton_poi_fused_add_convolution_4[grid(64)](buf12, primals_11,
buf7, primals_7, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf2
del buf7
del primals_11
del primals_7
return (buf12, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, buf1, buf3, buf4, buf6, buf8, buf10)
class _ImpalaResBlock(nn.Module):
def __init__(self, n_channels: 'int'):
super().__init__()
self.n_channels = n_channels
kernel_size = 3
padding = 1
self.relu = nn.ReLU()
self.relu_inplace = nn.ReLU()
self.conv1 = nn.Conv2d(n_channels, n_channels, kernel_size, padding
=padding)
self.conv2 = nn.Conv2d(n_channels, n_channels, kernel_size, padding
=padding)
def forward(self, inputs):
x = self.relu(inputs)
x = self.conv1(x)
x = self.relu_inplace(x)
x = self.conv2(x)
x += inputs
return x
class _ImpalaBlockNew(nn.Module):
def __init__(self, n_channels_in: 'int', n_channels_out: 'int'):
super().__init__()
self.n_channels_in = n_channels_in
self.n_channels_out = n_channels_out
kernel_size = 3
padding = 1
self.conv1 = nn.Conv2d(n_channels_in, n_channels_out, kernel_size,
padding=padding)
self.pool = nn.MaxPool2d(kernel_size, stride=2, padding=padding)
self.res1 = _ImpalaResBlock(n_channels_out)
self.res2 = _ImpalaResBlock(n_channels_out)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.res1.conv1.weight
primals_5 = self.res1.conv1.bias
primals_6 = self.res1.conv2.weight
primals_7 = self.res1.conv2.bias
primals_8 = self.res2.conv1.weight
primals_9 = self.res2.conv1.bias
primals_10 = self.res2.conv2.weight
primals_11 = self.res2.conv2.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]
|
nrfulton/vsrl-framework
|
_ImpalaBlock
| false
| 7,369
|
[
"MIT"
] | 1
|
c778824b3285e3e994a4c5846c7b1c2ac03c669b
|
https://github.com/nrfulton/vsrl-framework/tree/c778824b3285e3e994a4c5846c7b1c2ac03c669b
|
MILLR
|
import torch
import numpy as np
from torch import nn
import torch as tc
from sklearn.metrics import *
from torch.utils.data import DataLoader
from torch.utils.data import WeightedRandomSampler
class myDataset(torch.utils.data.Dataset):
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
class MILLR(tc.nn.Module):
def __init__(self, input_dim, flight_length, device, aggregation=
'maxpool', output_resize=False):
super(MILLR, self).__init__()
self.fc = nn.Linear(input_dim, 1)
self.sigmoid = nn.Sigmoid()
self.flight_length = flight_length
self.D = input_dim
self.device = device
self.task = 'binary'
self.threshold = 0.5
self.agg = aggregation
self.output_resize = output_resize
def forward(self, x, train=True):
_N, _, _ = x.size()
self.pi = self.sigmoid(self.fc(x)).squeeze()
self.proba_time = self.pi
if self.agg == 'mean':
p = tc.mean(self.pi, axis=-1)
elif self.agg == 'maxpool':
p = tc.max(self.pi, dim=-1)[0]
p = p.view(-1, 1)
return p
def get_feature_importance(self, columns, n_top=5):
coeffs = self.fc.weight.flatten().detach().numpy()
sorted_feat_idx = np.argsort(coeffs)[::-1]
sorted_columns = columns[sorted_feat_idx[:n_top]]
top_values = coeffs[sorted_feat_idx[:n_top]]
return sorted_columns, top_values
def cross_time_steps_loss(self, Pi):
diff = (Pi[:, :-1] - Pi[:, 1:]) ** 2
return tc.mean(tc.mean(diff, axis=-1))
def train_LR(self, X_train, y_train, X_val, y_val, batch_size,
print_every_epochs=5, l2=0.001, learning_rate=0.001,
use_stratified_batch_size=True, verbose=1, num_epochs=100,
optimizer='adam', momentum=0.99):
self.train()
if 'cuda' in self.device:
self
else:
self.cpu()
self.batch_size = batch_size
criterion = nn.BCELoss()
if optimizer == 'adam':
optimizer = tc.optim.Adam(self.parameters(), lr=learning_rate,
weight_decay=l2)
else:
optimizer = tc.optim.SGD(self.parameters(), momentum=momentum,
lr=learning_rate, weight_decay=l2)
hist = np.zeros(num_epochs)
val_hist = np.zeros(num_epochs)
b_acc = np.zeros(num_epochs)
val_b_acc = np.zeros(num_epochs)
f1 = np.zeros(num_epochs)
val_f1 = np.zeros(num_epochs)
if not tc.is_tensor(X_train):
X_train = tc.Tensor(X_train)
if not tc.is_tensor(y_train):
y_train = tc.Tensor(y_train.flatten())
if X_val is not None:
if not tc.is_tensor(X_val):
X_val = tc.Tensor(X_val)
if not tc.is_tensor(y_val):
y_val = tc.Tensor(y_val)
data_val = myDataset(X_val, y_val)
data_train = myDataset(X_train, y_train)
if use_stratified_batch_size is False:
None
dataloader_train = DataLoader(data_train, batch_size=self.
batch_size, shuffle=True)
else:
None
weights = []
for label in tc.unique(y_train):
count = len(tc.where(y_train == label)[0])
weights.append(1 / count)
weights = tc.tensor(weights)
samples_weights = weights[y_train.type(tc.LongTensor)]
sampler = WeightedRandomSampler(samples_weights, len(
samples_weights), replacement=True)
dataloader_train = DataLoader(data_train, batch_size=self.
batch_size, sampler=sampler)
if X_val is not None:
dataloader_val = DataLoader(data_val, batch_size=self.
batch_size, shuffle=False)
try:
for epoch in tqdm(range(num_epochs)):
batch_acc = []
batch_val_acc = []
batch_f1 = []
batch_val_f1 = []
for iteration, (batch_x, batch_y) in enumerate(dataloader_train
):
batch_x, batch_y = batch_x, batch_y
if epoch == 0 and iteration == 0:
for c in tc.unique(y_train):
None
outputs = self.forward(batch_x)
g_loss = self.cross_time_steps_loss(self.pi)
loss = criterion(outputs.flatten(), batch_y.view(-1).
flatten()) + g_loss
hist[epoch] = loss.item()
if 'cuda' in self.device:
temp_outpouts = (outputs.cpu().detach().numpy() >
self.threshold).astype(int)
y_batch = batch_y.view(-1).cpu().detach().numpy()
b_acc[epoch] = balanced_accuracy_score(y_batch,
temp_outpouts)
else:
temp_outpouts = (outputs.detach().numpy() > self.
threshold).astype(int)
y_batch = batch_y.view(-1).detach().numpy()
b_acc[epoch] = balanced_accuracy_score(y_batch,
temp_outpouts)
batch_acc.append(b_acc[epoch])
batch_f1.append(f1_score(y_batch, temp_outpouts,
average='binary'))
optimizer.zero_grad()
loss.backward()
optimizer.step()
if X_val is not None:
with tc.no_grad():
mini_loss = []
for batch_X_val, batch_y_val in dataloader_val:
batch_X_val, batch_y_val = (batch_X_val,
batch_y_val)
self.valYhat = self.forward(batch_X_val)
g_loss_val = self.cross_time_steps_loss(self.pi
)
val_loss = criterion(self.valYhat,
batch_y_val.flatten()) + g_loss_val
mini_loss.append(val_loss.item())
if self.task == 'binary':
if 'cuda' in self.device:
temp_out_y = (self.valYhat.cpu().detach
().numpy() > self.threshold).astype(int
)
y_val_batch = batch_y_val.view(-1).cpu(
).detach().numpy()
val_b_acc[epoch] = balanced_accuracy_score(
y_val_batch, temp_out_y)
else:
temp_out_y = (self.valYhat.detach().
numpy() > self.threshold).astype(int)
y_val_batch = batch_y_val.view(-1).detach(
).numpy()
val_b_acc[epoch] = balanced_accuracy_score(
y_val_batch, temp_out_y)
batch_val_acc.append(val_b_acc[epoch])
batch_val_f1.append(f1_score(
y_val_batch, temp_out_y, average=
'binary'))
val_hist[epoch] = np.mean(mini_loss)
if verbose == 1:
if self.task == 'binary':
if epoch % 10 == 0:
None
None
None
if X_val is not None:
None
None
None
elif epoch % print_every_epochs == 0:
None
if self.task == 'binary':
b_acc[epoch] = np.mean(batch_acc)
val_b_acc[epoch] = np.mean(batch_val_acc)
f1[epoch] = np.mean(batch_f1)
val_f1[epoch] = np.mean(batch_val_f1)
except KeyboardInterrupt:
self.cpu()
self.device = 'cpu'
self.eval()
self.x_train = X_train
self.x_test = X_val
self.hist = hist
self.val_hist = val_hist
except:
raise
self.cpu()
self.device = 'cpu'
self.eval()
self.x_train = X_train
self.x_test = X_val
self.hist = hist
self.val_hist = val_hist
def fit(self, **kw):
self.train_LR(**kw)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'flight_length': 4, 'device': 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
import numpy as np
from torch import nn
import torch as tc
from sklearn.metrics import *
from torch.utils.data import DataLoader
from torch.utils.data import WeightedRandomSampler
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sigmoid_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
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(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (1, 4), (4, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 1), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_sigmoid_0[grid(16)](buf1, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_max_1[grid(4)](buf1, buf2, 4, XBLOCK=4, num_warps=
1, num_stages=1)
return reinterpret_tensor(buf2, (4, 1), (1, 1), 0), reinterpret_tensor(buf1
, (4, 4), (4, 1), 0), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf1
class myDataset(torch.utils.data.Dataset):
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
class MILLRNew(tc.nn.Module):
def __init__(self, input_dim, flight_length, device, aggregation=
'maxpool', output_resize=False):
super(MILLRNew, self).__init__()
self.fc = nn.Linear(input_dim, 1)
self.sigmoid = nn.Sigmoid()
self.flight_length = flight_length
self.D = input_dim
self.device = device
self.task = 'binary'
self.threshold = 0.5
self.agg = aggregation
self.output_resize = output_resize
def get_feature_importance(self, columns, n_top=5):
coeffs = self.fc.weight.flatten().detach().numpy()
sorted_feat_idx = np.argsort(coeffs)[::-1]
sorted_columns = columns[sorted_feat_idx[:n_top]]
top_values = coeffs[sorted_feat_idx[:n_top]]
return sorted_columns, top_values
def cross_time_steps_loss(self, Pi):
diff = (Pi[:, :-1] - Pi[:, 1:]) ** 2
return tc.mean(tc.mean(diff, axis=-1))
def train_LR(self, X_train, y_train, X_val, y_val, batch_size,
print_every_epochs=5, l2=0.001, learning_rate=0.001,
use_stratified_batch_size=True, verbose=1, num_epochs=100,
optimizer='adam', momentum=0.99):
self.train()
if 'cuda' in self.device:
self
else:
self.cpu()
self.batch_size = batch_size
criterion = nn.BCELoss()
if optimizer == 'adam':
optimizer = tc.optim.Adam(self.parameters(), lr=learning_rate,
weight_decay=l2)
else:
optimizer = tc.optim.SGD(self.parameters(), momentum=momentum,
lr=learning_rate, weight_decay=l2)
hist = np.zeros(num_epochs)
val_hist = np.zeros(num_epochs)
b_acc = np.zeros(num_epochs)
val_b_acc = np.zeros(num_epochs)
f1 = np.zeros(num_epochs)
val_f1 = np.zeros(num_epochs)
if not tc.is_tensor(X_train):
X_train = tc.Tensor(X_train)
if not tc.is_tensor(y_train):
y_train = tc.Tensor(y_train.flatten())
if X_val is not None:
if not tc.is_tensor(X_val):
X_val = tc.Tensor(X_val)
if not tc.is_tensor(y_val):
y_val = tc.Tensor(y_val)
data_val = myDataset(X_val, y_val)
data_train = myDataset(X_train, y_train)
if use_stratified_batch_size is False:
None
dataloader_train = DataLoader(data_train, batch_size=self.
batch_size, shuffle=True)
else:
None
weights = []
for label in tc.unique(y_train):
count = len(tc.where(y_train == label)[0])
weights.append(1 / count)
weights = tc.tensor(weights)
samples_weights = weights[y_train.type(tc.LongTensor)]
sampler = WeightedRandomSampler(samples_weights, len(
samples_weights), replacement=True)
dataloader_train = DataLoader(data_train, batch_size=self.
batch_size, sampler=sampler)
if X_val is not None:
dataloader_val = DataLoader(data_val, batch_size=self.
batch_size, shuffle=False)
try:
for epoch in tqdm(range(num_epochs)):
batch_acc = []
batch_val_acc = []
batch_f1 = []
batch_val_f1 = []
for iteration, (batch_x, batch_y) in enumerate(dataloader_train
):
batch_x, batch_y = batch_x, batch_y
if epoch == 0 and iteration == 0:
for c in tc.unique(y_train):
None
outputs = self.forward(batch_x)
g_loss = self.cross_time_steps_loss(self.pi)
loss = criterion(outputs.flatten(), batch_y.view(-1).
flatten()) + g_loss
hist[epoch] = loss.item()
if 'cuda' in self.device:
temp_outpouts = (outputs.cpu().detach().numpy() >
self.threshold).astype(int)
y_batch = batch_y.view(-1).cpu().detach().numpy()
b_acc[epoch] = balanced_accuracy_score(y_batch,
temp_outpouts)
else:
temp_outpouts = (outputs.detach().numpy() > self.
threshold).astype(int)
y_batch = batch_y.view(-1).detach().numpy()
b_acc[epoch] = balanced_accuracy_score(y_batch,
temp_outpouts)
batch_acc.append(b_acc[epoch])
batch_f1.append(f1_score(y_batch, temp_outpouts,
average='binary'))
optimizer.zero_grad()
loss.backward()
optimizer.step()
if X_val is not None:
with tc.no_grad():
mini_loss = []
for batch_X_val, batch_y_val in dataloader_val:
batch_X_val, batch_y_val = (batch_X_val,
batch_y_val)
self.valYhat = self.forward(batch_X_val)
g_loss_val = self.cross_time_steps_loss(self.pi
)
val_loss = criterion(self.valYhat,
batch_y_val.flatten()) + g_loss_val
mini_loss.append(val_loss.item())
if self.task == 'binary':
if 'cuda' in self.device:
temp_out_y = (self.valYhat.cpu().detach
().numpy() > self.threshold).astype(int
)
y_val_batch = batch_y_val.view(-1).cpu(
).detach().numpy()
val_b_acc[epoch] = balanced_accuracy_score(
y_val_batch, temp_out_y)
else:
temp_out_y = (self.valYhat.detach().
numpy() > self.threshold).astype(int)
y_val_batch = batch_y_val.view(-1).detach(
).numpy()
val_b_acc[epoch] = balanced_accuracy_score(
y_val_batch, temp_out_y)
batch_val_acc.append(val_b_acc[epoch])
batch_val_f1.append(f1_score(
y_val_batch, temp_out_y, average=
'binary'))
val_hist[epoch] = np.mean(mini_loss)
if verbose == 1:
if self.task == 'binary':
if epoch % 10 == 0:
None
None
None
if X_val is not None:
None
None
None
elif epoch % print_every_epochs == 0:
None
if self.task == 'binary':
b_acc[epoch] = np.mean(batch_acc)
val_b_acc[epoch] = np.mean(batch_val_acc)
f1[epoch] = np.mean(batch_f1)
val_f1[epoch] = np.mean(batch_val_f1)
except KeyboardInterrupt:
self.cpu()
self.device = 'cpu'
self.eval()
self.x_train = X_train
self.x_test = X_val
self.hist = hist
self.val_hist = val_hist
except:
raise
self.cpu()
self.device = 'cpu'
self.eval()
self.x_train = X_train
self.x_test = X_val
self.hist = hist
self.val_hist = val_hist
def fit(self, **kw):
self.train_LR(**kw)
def forward(self, input_0):
primals_2 = self.fc.weight
primals_3 = self.fc.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
mhbl3/PrecursorAnalysis
|
MILLR
| false
| 7,370
|
[
"MIT"
] | 1
|
aaa2fe0219ad579b9126fef9cc8594a59ae66815
|
https://github.com/mhbl3/PrecursorAnalysis/tree/aaa2fe0219ad579b9126fef9cc8594a59ae66815
|
PEG
|
import torch
from torch import nn
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x, **kwargs):
return self.fn(x, **kwargs) + x
class PEG(nn.Module):
def __init__(self, dim, kernel_size=3):
super().__init__()
self.proj = Residual(nn.Conv2d(dim, dim, kernel_size=kernel_size,
padding=kernel_size // 2, groups=dim, stride=1))
def forward(self, x):
return self.proj(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_add_convolution_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_convolution_0[grid(256)](buf1, primals_2,
primals_3, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x, **kwargs):
return self.fn(x, **kwargs) + x
class PEGNew(nn.Module):
def __init__(self, dim, kernel_size=3):
super().__init__()
self.proj = Residual(nn.Conv2d(dim, dim, kernel_size=kernel_size,
padding=kernel_size // 2, groups=dim, stride=1))
def forward(self, input_0):
primals_1 = self.proj.fn.weight
primals_2 = self.proj.fn.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
onlyrico/vit-pytorch
|
PEG
| false
| 7,371
|
[
"MIT"
] | 1
|
e52ac4195550faa9c3372533d325bf649f7354ad
|
https://github.com/onlyrico/vit-pytorch/tree/e52ac4195550faa9c3372533d325bf649f7354ad
|
SpatialGather_Module
|
import torch
from torchvision.transforms import functional as F
import torch.nn as nn
import torch.nn.functional as F
class SpatialGather_Module(nn.Module):
"""
Aggregate the context features according to the initial predicted probability distribution.
Employ the soft-weighted method to aggregate the context.
"""
def __init__(self, cls_num=0, scale=1):
super(SpatialGather_Module, self).__init__()
self.cls_num = cls_num
self.scale = scale
def forward(self, feats, probs, gt_probs=None):
batch_size, c, _h, _w = probs.size(0), probs.size(1), probs.size(2
), probs.size(3)
probs = probs.view(batch_size, c, -1)
feats = feats.view(batch_size, feats.size(1), -1)
feats = feats.permute(0, 2, 1)
probs = F.softmax(self.scale * probs, dim=2)
ocr_context = torch.matmul(probs, feats).permute(0, 2, 1).unsqueeze(3)
return ocr_context
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__softmax_0(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, float('-inf'))
tmp6 = triton_helpers.max2(tmp5, 1)[:, None]
tmp7 = tmp2 - tmp6
tmp8 = tmp7 * tmp1
tmp9 = tl_math.exp(tmp8)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tmp14 = tmp9 / tmp13
tl.store(out_ptr2 + (r1 + 16 * x0), tmp14, 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)
buf2 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__softmax_0[grid(16)](arg0_1, buf2, 16, 16, XBLOCK=
1, num_warps=2, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf2, reinterpret_tensor(arg1_1, (4, 16, 4), (64,
1, 16), 0), out=buf3)
del arg1_1
del buf2
return reinterpret_tensor(buf3, (4, 4, 4, 1), (16, 1, 4, 1), 0),
class SpatialGather_ModuleNew(nn.Module):
"""
Aggregate the context features according to the initial predicted probability distribution.
Employ the soft-weighted method to aggregate the context.
"""
def __init__(self, cls_num=0, scale=1):
super(SpatialGather_ModuleNew, self).__init__()
self.cls_num = cls_num
self.scale = scale
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
openseg-group/panoptic-deeplab
|
SpatialGather_Module
| false
| 7,372
|
[
"Apache-2.0"
] | 1
|
818887597e75af77ba32185eb67d8aeac47b54fe
|
https://github.com/openseg-group/panoptic-deeplab/tree/818887597e75af77ba32185eb67d8aeac47b54fe
|
Qux
|
import torch
import torch.jit
import torch.onnx
import torch.nn
class Qux(torch.nn.Module):
def __init__(self, x):
super(Qux, self).__init__()
self.x = x
def forward(self, a, b):
return a - b - self.x
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'x': 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.jit
import torch.onnx
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 - tmp1
tmp3 = 4.0
tmp4 = tmp2 - 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 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_sub_0[grid(256)](arg0_1, arg1_1, buf0, 256, XBLOCK
=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class QuxNew(torch.nn.Module):
def __init__(self, x):
super(QuxNew, self).__init__()
self.x = x
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
opti-mix/glow
|
Qux
| false
| 7,373
|
[
"Apache-2.0"
] | 1
|
4ba074df5da9822986a23a6679ab592c22660f6d
|
https://github.com/opti-mix/glow/tree/4ba074df5da9822986a23a6679ab592c22660f6d
|
Discriminator
|
import torch
import numpy as np
from torch import nn as nn
from torch.nn import functional as F
from torch import optim as optim
class Discriminator(nn.Module):
def __init__(self, img_shape, hidden_dim=1024):
super().__init__()
in_dim = int(np.prod(img_shape))
self.fc1 = nn.Linear(in_dim, hidden_dim)
self.fc2 = nn.Linear(self.fc1.out_features, self.fc1.out_features // 2)
self.fc3 = nn.Linear(self.fc2.out_features, self.fc2.out_features // 2)
self.fc4 = nn.Linear(self.fc3.out_features, 1)
def forward(self, img):
x = img.view(img.size(0), -1)
x = F.leaky_relu(self.fc1(x), 0.2)
x = F.dropout(x, 0.3)
x = F.leaky_relu(self.fc2(x), 0.2)
x = F.dropout(x, 0.3)
x = F.leaky_relu(self.fc3(x), 0.2)
x = F.dropout(x, 0.3)
return torch.sigmoid(self.fc4(x))
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'img_shape': 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 numpy as np
from torch import nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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)
x2 = xindex
x0 = xindex % 1024
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, None)
tl.store(out_ptr1 + x2, tmp7, None)
@triton.jit
def triton_poi_fused_leaky_relu_1(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)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, None)
tl.store(out_ptr1 + x2, tmp7, None)
@triton.jit
def triton_poi_fused_leaky_relu_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
@triton.jit
def triton_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, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (1024, 4), (4, 1))
assert_size_stride(primals_3, (1024,), (1,))
assert_size_stride(primals_4, (512, 1024), (1024, 1))
assert_size_stride(primals_5, (512,), (1,))
assert_size_stride(primals_6, (256, 512), (512, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (1, 256), (256, 1))
assert_size_stride(primals_9, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1024), (1024, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 1024
), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 1024), (1024, 1), torch.bool)
buf2 = empty_strided_cuda((4, 1024), (1024, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(4096)](buf0, primals_3, buf1,
buf2, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_3
buf3 = torch.ops.aten.native_dropout.default(buf2, 0.3, True)
del buf2
buf4 = buf3[0]
buf5 = buf3[1]
del buf3
buf6 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_4, (1024, 512),
(1, 1024), 0), out=buf6)
buf7 = empty_strided_cuda((4, 512), (512, 1), torch.bool)
buf8 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
triton_poi_fused_leaky_relu_1[grid(2048)](buf6, primals_5, buf7,
buf8, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del buf6
del primals_5
buf9 = torch.ops.aten.native_dropout.default(buf8, 0.3, True)
del buf8
buf10 = buf9[0]
buf11 = buf9[1]
del buf9
buf12 = empty_strided_cuda((4, 256), (256, 1), torch.float32)
extern_kernels.mm(buf10, reinterpret_tensor(primals_6, (512, 256),
(1, 512), 0), out=buf12)
buf13 = empty_strided_cuda((4, 256), (256, 1), torch.bool)
buf14 = empty_strided_cuda((4, 256), (256, 1), torch.float32)
triton_poi_fused_leaky_relu_2[grid(1024)](buf12, primals_7, buf13,
buf14, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del buf12
del primals_7
buf15 = torch.ops.aten.native_dropout.default(buf14, 0.3, True)
del buf14
buf16 = buf15[0]
buf17 = buf15[1]
del buf15
buf18 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf16, reinterpret_tensor(primals_8, (256, 1), (1,
256), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_sigmoid_3[grid(4)](buf19, primals_9, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_9
return (buf19, primals_1, buf1, buf4, buf5, buf7, buf10, buf11, buf13,
buf16, buf17, buf19, primals_8, primals_6, primals_4)
class DiscriminatorNew(nn.Module):
def __init__(self, img_shape, hidden_dim=1024):
super().__init__()
in_dim = int(np.prod(img_shape))
self.fc1 = nn.Linear(in_dim, hidden_dim)
self.fc2 = nn.Linear(self.fc1.out_features, self.fc1.out_features // 2)
self.fc3 = nn.Linear(self.fc2.out_features, self.fc2.out_features // 2)
self.fc4 = nn.Linear(self.fc3.out_features, 1)
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_8 = self.fc4.weight
primals_9 = 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])
return output[0]
|
oke-aditya/pytorch-lightning-bolts
|
Discriminator
| false
| 7,374
|
[
"Apache-2.0"
] | 1
|
268df20bb442e7385b709b1488d37fd2767aba3c
|
https://github.com/oke-aditya/pytorch-lightning-bolts/tree/268df20bb442e7385b709b1488d37fd2767aba3c
|
ResBlock
|
import torch
from torch import nn
class CausalConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, dilation=1,
bias=False):
super(CausalConv1d, self).__init__()
self.padding = padding = (kernel_size - 1) * dilation
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=padding, dilation=dilation, bias=bias)
def forward(self, x):
x = self.conv(x)
if self.padding != 0:
x = x[:, :, :-self.padding]
return x
class ResBlock(nn.Module):
def __init__(self, dilation, aux_channels, n_channels, skip_channels,
kernel_size, fast_inference=False):
super(ResBlock, self).__init__()
conv_dilation = 1 if fast_inference else dilation
self.filter = CausalConv1d(n_channels, n_channels, kernel_size=
kernel_size, dilation=conv_dilation)
self.gate = CausalConv1d(n_channels, n_channels, kernel_size=
kernel_size, dilation=conv_dilation)
self.aux_filter = nn.Conv1d(aux_channels, n_channels, kernel_size=1)
self.aux_gate = nn.Conv1d(aux_channels, n_channels, kernel_size=1)
if fast_inference:
self.queue = None
self.buffer_size = conv_dilation * 2 * (kernel_size - 1)
self.fast_inference = fast_inference
self.permute = nn.Conv1d(n_channels, n_channels, kernel_size=1)
self.skip = nn.Conv1d(n_channels, skip_channels, kernel_size=1)
def forward(self, x, h):
if self.fast_inference:
pass
else:
out_tanh = torch.tanh(self.filter(x) + self.aux_filter(h))
out_gate = torch.sigmoid(self.gate(x) + self.aux_gate(h))
output = self.permute(out_tanh * out_gate) + x
skip = self.skip(output)
return output, skip
def clear(self):
self.queue = None
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dilation': 1, 'aux_channels': 4, 'n_channels': 4,
'skip_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_convolution_mul_sigmoid_tanh_0(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x4 = xindex // 4
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_ptr0 + (x0 + 7 * x4), xmask)
tmp1 = tl.load(in_out_ptr0 + x3, xmask)
tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr2 + (x0 + 7 * x4), xmask)
tmp7 = tl.load(in_out_ptr1 + x3, xmask)
tmp8 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp11 = tl.sigmoid(tmp10)
tmp12 = tmp5 * tmp11
tl.store(in_out_ptr0 + x3, tmp5, xmask)
tl.store(in_out_ptr1 + x3, tmp11, xmask)
tl.store(out_ptr0 + x3, tmp12, xmask)
@triton.jit
def triton_poi_fused_add_convolution_1(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,),
padding=(3,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 7), (28, 7, 1))
buf1 = extern_kernels.convolution(primals_5, primals_3, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf3 = extern_kernels.convolution(primals_2, primals_6, stride=(1,),
padding=(3,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 7), (28, 7, 1))
buf4 = extern_kernels.convolution(primals_5, primals_7, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 4), (16, 4, 1))
buf2 = buf1
del buf1
buf5 = buf4
del buf4
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_convolution_mul_sigmoid_tanh_0[grid(64)](buf2,
buf5, buf0, primals_4, buf3, primals_8, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf0
del buf3
del primals_4
del primals_8
buf7 = extern_kernels.convolution(buf6, primals_9, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf7, (4, 4, 4), (16, 4, 1))
buf8 = buf7
del buf7
triton_poi_fused_add_convolution_1[grid(64)](buf8, primals_10,
primals_2, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_10
buf9 = extern_kernels.convolution(buf8, primals_11, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 4), (16, 4, 1))
buf10 = buf9
del buf9
triton_poi_fused_convolution_2[grid(64)](buf10, primals_12, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_12
return (buf8, buf10, primals_1, primals_2, primals_3, primals_5,
primals_6, primals_7, primals_9, primals_11, buf2, buf5, buf6, buf8)
class CausalConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, dilation=1,
bias=False):
super(CausalConv1d, self).__init__()
self.padding = padding = (kernel_size - 1) * dilation
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=padding, dilation=dilation, bias=bias)
def forward(self, x):
x = self.conv(x)
if self.padding != 0:
x = x[:, :, :-self.padding]
return x
class ResBlockNew(nn.Module):
def __init__(self, dilation, aux_channels, n_channels, skip_channels,
kernel_size, fast_inference=False):
super(ResBlockNew, self).__init__()
conv_dilation = 1 if fast_inference else dilation
self.filter = CausalConv1d(n_channels, n_channels, kernel_size=
kernel_size, dilation=conv_dilation)
self.gate = CausalConv1d(n_channels, n_channels, kernel_size=
kernel_size, dilation=conv_dilation)
self.aux_filter = nn.Conv1d(aux_channels, n_channels, kernel_size=1)
self.aux_gate = nn.Conv1d(aux_channels, n_channels, kernel_size=1)
if fast_inference:
self.queue = None
self.buffer_size = conv_dilation * 2 * (kernel_size - 1)
self.fast_inference = fast_inference
self.permute = nn.Conv1d(n_channels, n_channels, kernel_size=1)
self.skip = nn.Conv1d(n_channels, skip_channels, kernel_size=1)
def clear(self):
self.queue = None
def forward(self, input_0, input_1):
primals_1 = self.filter.conv.weight
primals_2 = self.gate.conv.weight
primals_3 = self.aux_filter.weight
primals_4 = self.aux_filter.bias
primals_7 = self.aux_gate.weight
primals_8 = self.aux_gate.bias
primals_9 = self.permute.weight
primals_10 = self.permute.bias
primals_11 = self.skip.weight
primals_12 = self.skip.bias
primals_5 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0], output[1]
|
oleges1/TTS
|
ResBlock
| false
| 7,375
|
[
"MIT"
] | 1
|
19b389714078729fae29faf9c23112bdbe4c8dec
|
https://github.com/oleges1/TTS/tree/19b389714078729fae29faf9c23112bdbe4c8dec
|
RepeatModule
|
import torch
import torch.jit
import torch.onnx
import torch.nn
class RepeatModule(torch.nn.Module):
def __init__(self, repeats):
super(RepeatModule, self).__init__()
self.repeats = repeats
def forward(self, tensor):
tensor = tensor + tensor
return tensor.repeat(self.repeats)
def get_inputs():
return [torch.rand([4])]
def get_init_inputs():
return [[], {'repeats': 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.jit
import torch.onnx
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_repeat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0 % 4, xmask)
tmp1 = tmp0 + tmp0
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16,), (1,), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_repeat_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class RepeatModuleNew(torch.nn.Module):
def __init__(self, repeats):
super(RepeatModuleNew, self).__init__()
self.repeats = repeats
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
opti-mix/glow
|
RepeatModule
| false
| 7,376
|
[
"Apache-2.0"
] | 1
|
4ba074df5da9822986a23a6679ab592c22660f6d
|
https://github.com/opti-mix/glow/tree/4ba074df5da9822986a23a6679ab592c22660f6d
|
Grounding
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torch as th
from torchvision.ops.boxes import *
from torchvision.transforms.functional import *
class Grounding(nn.Module):
def __init__(self, cfgT, cfgI, heads=1):
super(Grounding, self).__init__()
projection = cfgI.hidden_size // 2
self.num_attention_heads = heads
self.attention_head_size = int(projection // self.num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.Q = nn.Linear(cfgT.hidden_size, self.all_head_size)
self.K = nn.Linear(cfgI.hidden_size, self.all_head_size)
self.cfgT = cfgT
self.cfgI = cfgI
def transpose(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, encT, encI, mask):
Q = self.Q(encT)
K = self.K(encI)
Q = self.transpose(Q)
K = self.transpose(K)
logits = th.matmul(Q, K.transpose(-1, -2))
logits = logits / math.sqrt(self.attention_head_size)
logits = logits + mask
return logits.squeeze()
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'cfgT': _mock_config(hidden_size=4), 'cfgI': _mock_config(
hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
from torchvision.ops.boxes import *
from torchvision.transforms.functional import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_div_squeeze_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex % 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last')
tmp1 = 0.7071067811865475
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + x4, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (2, 4), (4, 1))
assert_size_stride(primals_2, (2,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (2, 4), (4, 1))
assert_size_stride(primals_5, (2,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (16,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 2), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (16,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 2), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (4, 4, 2), (8, 2, 1), 0
), reinterpret_tensor(buf1, (4, 2, 4), (8, 1, 2), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_squeeze_0[grid(256)](buf2, primals_7, buf3,
256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
del primals_7
return buf3, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), reinterpret_tensor(buf0, (4, 2, 4), (8, 1, 2), 0
), reinterpret_tensor(buf1, (4, 4, 2), (8, 2, 1), 0)
class GroundingNew(nn.Module):
def __init__(self, cfgT, cfgI, heads=1):
super(GroundingNew, self).__init__()
projection = cfgI.hidden_size // 2
self.num_attention_heads = heads
self.attention_head_size = int(projection // self.num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.Q = nn.Linear(cfgT.hidden_size, self.all_head_size)
self.K = nn.Linear(cfgI.hidden_size, self.all_head_size)
self.cfgT = cfgT
self.cfgI = cfgI
def transpose(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, input_0, input_1, input_2):
primals_1 = self.Q.weight
primals_2 = self.Q.bias
primals_4 = self.K.weight
primals_5 = self.K.bias
primals_3 = input_0
primals_6 = input_1
primals_7 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
necla-ml/ML-Vision
|
Grounding
| false
| 7,377
|
[
"BSD-3-Clause"
] | 1
|
66229b29fc0f67c75dbe6304cdb8c5e93fe0bacf
|
https://github.com/necla-ml/ML-Vision/tree/66229b29fc0f67c75dbe6304cdb8c5e93fe0bacf
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.