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
|
|---|---|---|---|---|---|---|---|---|---|---|
ResBlock
|
import torch
from torch import nn
import torch.nn.functional as F
class ResBlock(nn.Module):
def __init__(self, dim, dropout=0):
super(ResBlock, self).__init__()
self.dim = dim
self.dropout = nn.Dropout(dropout)
self.linear1 = nn.Linear(self.dim, self.dim)
self.linear2 = nn.Linear(self.dim, self.dim)
self.layer_norm1 = nn.LayerNorm(self.dim)
self.layer_norm2 = nn.LayerNorm(self.dim)
self.reset_parameters()
def reset_parameters(self):
initScale = 0.1
self.linear1.weight.data.uniform_(-initScale, initScale)
self.linear1.bias.data.zero_()
self.linear2.weight.data.uniform_(-initScale, initScale)
self.linear2.bias.data.zero_()
def forward(self, x):
x_prev = x
x = self.layer_norm1(x)
x = torch.tanh(x)
x = self.linear1(x)
x = self.layer_norm2(x)
x = F.relu(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.linear2(x)
return x_prev + x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_tanh_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
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tmp9 = libdevice.tanh(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_relu_tanh_2(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
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tmp9 = tl.full([1], 0, tl.int32)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp11 = libdevice.tanh(tmp10)
tl.store(out_ptr0 + x2, tmp11, xmask)
@triton.jit
def triton_poi_fused_add_3(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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (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((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(64)](primals_1, buf0,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_tanh_1[grid(256)](primals_1,
buf0, buf1, primals_2, primals_3, buf2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_2
del primals_3
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
buf4 = buf1
del buf1
buf5 = buf0
del buf0
triton_poi_fused_native_layer_norm_0[grid(64)](buf3, buf4, buf5, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_relu_tanh_2[grid(256)](buf3,
buf4, buf5, primals_6, primals_7, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf4
del buf5
buf7 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf7)
buf8 = reinterpret_tensor(buf7, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf7
triton_poi_fused_add_3[grid(256)](buf8, primals_1, primals_9, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
return (buf8, primals_1, primals_6, primals_7, buf2, buf3, buf6,
primals_8, primals_4)
class ResBlockNew(nn.Module):
def __init__(self, dim, dropout=0):
super(ResBlockNew, self).__init__()
self.dim = dim
self.dropout = nn.Dropout(dropout)
self.linear1 = nn.Linear(self.dim, self.dim)
self.linear2 = nn.Linear(self.dim, self.dim)
self.layer_norm1 = nn.LayerNorm(self.dim)
self.layer_norm2 = nn.LayerNorm(self.dim)
self.reset_parameters()
def reset_parameters(self):
initScale = 0.1
self.linear1.weight.data.uniform_(-initScale, initScale)
self.linear1.bias.data.zero_()
self.linear2.weight.data.uniform_(-initScale, initScale)
self.linear2.bias.data.zero_()
def forward(self, input_0):
primals_4 = self.linear1.weight
primals_2 = self.linear1.bias
primals_8 = self.linear2.weight
primals_3 = self.linear2.bias
primals_5 = self.layer_norm1.weight
primals_6 = self.layer_norm1.bias
primals_7 = self.layer_norm2.weight
primals_9 = self.layer_norm2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
JiwanChung/tapm
|
ResBlock
| false
| 8,388
|
[
"MIT"
] | 14
|
ec42b139d1c012daccc55f85e67744488d526476
|
https://github.com/JiwanChung/tapm/tree/ec42b139d1c012daccc55f85e67744488d526476
|
FeatureEncoder
|
import torch
from torch import nn
import torch.nn.functional as F
class FeatureEncoder(nn.Module):
def __init__(self, video_dim, dim):
super(FeatureEncoder, self).__init__()
self.linear = nn.Linear(video_dim, dim)
def forward(self, feature, h=None):
feature = self.linear(feature)
feature = F.leaky_relu(feature)
return feature
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'video_dim': 4, 'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(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 % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(256)](buf0, primals_2, buf1,
buf2, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_2
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf1
class FeatureEncoderNew(nn.Module):
def __init__(self, video_dim, dim):
super(FeatureEncoderNew, self).__init__()
self.linear = nn.Linear(video_dim, dim)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
JiwanChung/tapm
|
FeatureEncoder
| false
| 8,389
|
[
"MIT"
] | 14
|
ec42b139d1c012daccc55f85e67744488d526476
|
https://github.com/JiwanChung/tapm/tree/ec42b139d1c012daccc55f85e67744488d526476
|
net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class net(nn.Module):
def __init__(self, input_dim, output_dim):
super(net, self).__init__()
self.fc1 = nn.Linear(input_dim, 30)
self.fc1.weight.data.normal_(0, 1)
self.fc2 = nn.Linear(30, 20)
self.fc2.weight.data.normal_(0, 1)
self.fc3 = nn.Linear(20, output_dim)
self.fc3.weight.data.normal_(0, 1)
def forward(self, x):
x = F.tanh(self.fc1(x))
x = F.tanh(self.fc2(x))
out = self.fc3(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1920
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 30
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1280
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 20
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (30, 4), (4, 1))
assert_size_stride(primals_2, (30,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (20, 30), (30, 1))
assert_size_stride(primals_5, (20,), (1,))
assert_size_stride(primals_6, (4, 20), (20, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 30), (30, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 30), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 30), (480, 120, 30, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(1920)](buf1, primals_2, 1920, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 20), (20, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 30), (30, 1), 0),
reinterpret_tensor(primals_4, (30, 20), (1, 30), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 20), (320, 80, 20, 1), 0)
del buf2
triton_poi_fused_tanh_1[grid(1280)](buf3, primals_5, 1280, 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, 20),
(20, 1), 0), reinterpret_tensor(primals_6, (20, 4), (1, 20), 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
), buf1, buf3, primals_6, primals_4
class netNew(nn.Module):
def __init__(self, input_dim, output_dim):
super(netNew, self).__init__()
self.fc1 = nn.Linear(input_dim, 30)
self.fc1.weight.data.normal_(0, 1)
self.fc2 = nn.Linear(30, 20)
self.fc2.weight.data.normal_(0, 1)
self.fc3 = nn.Linear(20, output_dim)
self.fc3.weight.data.normal_(0, 1)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
Kernels-K/DDPG-pytorch-
|
net
| false
| 8,390
|
[
"MIT"
] | 26
|
9a80a56f52f2232e5bd197521d3d2d388b48c882
|
https://github.com/Kernels-K/DDPG-pytorch-/tree/9a80a56f52f2232e5bd197521d3d2d388b48c882
|
GraphConvolution
|
import torch
import torch.nn as nn
class GraphConvolution(nn.Module):
def __init__(self, in_dim, out_dim):
super(GraphConvolution, self).__init__()
self.relu = nn.LeakyReLU(0.2)
self.weight = nn.Conv1d(in_dim, out_dim, 1)
def forward(self, adj, nodes):
nodes = torch.matmul(nodes, adj)
nodes = self.relu(nodes)
nodes = self.weight(nodes)
nodes = self.relu(nodes)
return nodes
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 0.2
tmp4 = tmp0 * tmp3
tmp5 = tl.where(tmp2, tmp0, tmp4)
tl.store(in_out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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
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)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_2, primals_1, out=buf0)
del primals_1
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(16)](buf1, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 4
), (0, 4, 1), 0), primals_3, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf2, (1, 4, 4), (16, 4, 1))
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_leaky_relu_1[grid(16)](buf2, primals_4, buf3, buf4,
16, XBLOCK=16, num_warps=1, num_stages=1)
del buf2
del primals_4
return buf4, primals_3, reinterpret_tensor(buf1, (1, 4, 4), (16, 4, 1), 0
), buf3
class GraphConvolutionNew(nn.Module):
def __init__(self, in_dim, out_dim):
super(GraphConvolutionNew, self).__init__()
self.relu = nn.LeakyReLU(0.2)
self.weight = nn.Conv1d(in_dim, out_dim, 1)
def forward(self, input_0, input_1):
primals_3 = self.weight.weight
primals_4 = self.weight.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Kanaricc/TDRG
|
GraphConvolution
| false
| 8,391
|
[
"Apache-2.0"
] | 16
|
91416976c8887877775f516ebee60469449e7e5f
|
https://github.com/Kanaricc/TDRG/tree/91416976c8887877775f516ebee60469449e7e5f
|
ANet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ANet(nn.Module):
def __init__(self, s_dim, a_dim):
super(ANet, self).__init__()
self.fc1 = nn.Linear(s_dim, 30)
self.fc1.weight.data.normal_(0, 0.1)
self.out = nn.Linear(30, a_dim)
self.out.weight.data.normal_(0, 0.1)
def forward(self, x):
x = self.fc1(x)
x = F.relu(x)
x = self.out(x)
x = F.tanh(x)
actions_value = x * 2
return actions_value
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'s_dim': 4, 'a_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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1920
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 30
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_mul_tanh_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp2 = 2.0
tmp3 = tmp1 * tmp2
tl.store(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, (30, 4), (4, 1))
assert_size_stride(primals_2, (30,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 30), (30, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 30), (30, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 30), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 30), (480, 120, 30, 1), 0)
del buf0
buf4 = empty_strided_cuda((4, 4, 4, 30), (480, 120, 30, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(1920)](buf1,
primals_2, buf4, 1920, 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, 30),
(30, 1), 0), reinterpret_tensor(primals_4, (30, 4), (1, 30), 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_tanh_1[grid(256)](buf2, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 30), (30, 1), 0
), buf2, primals_4, buf4
class ANetNew(nn.Module):
def __init__(self, s_dim, a_dim):
super(ANetNew, self).__init__()
self.fc1 = nn.Linear(s_dim, 30)
self.fc1.weight.data.normal_(0, 0.1)
self.out = nn.Linear(30, a_dim)
self.out.weight.data.normal_(0, 0.1)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.out.weight
primals_5 = self.out.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Kernels-K/DDPG-pytorch-
|
ANet
| false
| 8,392
|
[
"MIT"
] | 26
|
9a80a56f52f2232e5bd197521d3d2d388b48c882
|
https://github.com/Kernels-K/DDPG-pytorch-/tree/9a80a56f52f2232e5bd197521d3d2d388b48c882
|
DiceLoss
|
import torch
import torch.nn as nn
import torch.utils.data
def flatten_samples(input_):
"""
Flattens a tensor or a variable such that the channel axis is first and the sample axis
is second. The shapes are transformed as follows:
(N, C, H, W) --> (C, N * H * W)
(N, C, D, H, W) --> (C, N * D * H * W)
(N, C) --> (C, N)
The input must be atleast 2d.
"""
num_channels = input_.size(1)
permute_axes = list(range(input_.dim()))
permute_axes[0], permute_axes[1] = permute_axes[1], permute_axes[0]
permuted = input_.permute(*permute_axes).contiguous()
flattened = permuted.view(num_channels, -1)
return flattened
def dice_score(input_, target, invert=False, channelwise=True, eps=1e-07):
if channelwise:
input_ = flatten_samples(input_)
target = flatten_samples(target)
numerator = (input_ * target).sum(-1)
denominator = (input_ * input_).sum(-1) + (target * target).sum(-1)
channelwise_score = 2 * (numerator / denominator.clamp(min=eps))
if invert:
channelwise_score = 1.0 - channelwise_score
score = channelwise_score.sum()
else:
numerator = (input_ * target).sum()
denominator = (input_ * input_).sum() + (target * target).sum()
score = 2.0 * (numerator / denominator.clamp(min=eps))
if invert:
score = 1.0 - score
return score
class DiceLoss(nn.Module):
def __init__(self, channelwise=True, eps=1e-07):
super().__init__()
self.channelwise = channelwise
self.eps = eps
self.init_kwargs = {'channelwise': channelwise, 'eps': self.eps}
def forward(self, input_, target):
return dice_score(input_, target, invert=True, channelwise=self.
channelwise, eps=self.eps)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (16 * x0 + 64 * (r1 // 16) + r1 % 16), xmask,
other=0.0)
tmp1 = tl.load(in_ptr1 + (16 * x0 + 64 * (r1 // 16) + r1 % 16), xmask,
other=0.0)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
tmp7 = tmp0 * tmp0
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.where(xmask, tmp8, 0)
tmp11 = tl.sum(tmp10, 1)[:, None]
tmp12 = tmp1 * tmp1
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
tl.store(out_ptr2 + x0, tmp16, xmask)
@triton.jit
def triton_per_fused_add_clamp_div_mul_rsub_sum_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tl.load(in_ptr2 + r0, None)
tmp3 = tmp1 + tmp2
tmp4 = 1e-07
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp6 = tmp0 / tmp5
tmp7 = 2.0
tmp8 = tmp6 * tmp7
tmp9 = 1.0
tmp10 = tmp9 - tmp8
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp13 = tl.sum(tmp11, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(4)](arg0_1, arg1_1, buf0, buf1,
buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf3 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_add_clamp_div_mul_rsub_sum_1[grid(1)](buf0, buf1,
buf2, buf3, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf2
return buf3,
def flatten_samples(input_):
"""
Flattens a tensor or a variable such that the channel axis is first and the sample axis
is second. The shapes are transformed as follows:
(N, C, H, W) --> (C, N * H * W)
(N, C, D, H, W) --> (C, N * D * H * W)
(N, C) --> (C, N)
The input must be atleast 2d.
"""
num_channels = input_.size(1)
permute_axes = list(range(input_.dim()))
permute_axes[0], permute_axes[1] = permute_axes[1], permute_axes[0]
permuted = input_.permute(*permute_axes).contiguous()
flattened = permuted.view(num_channels, -1)
return flattened
def dice_score(input_, target, invert=False, channelwise=True, eps=1e-07):
if channelwise:
input_ = flatten_samples(input_)
target = flatten_samples(target)
numerator = (input_ * target).sum(-1)
denominator = (input_ * input_).sum(-1) + (target * target).sum(-1)
channelwise_score = 2 * (numerator / denominator.clamp(min=eps))
if invert:
channelwise_score = 1.0 - channelwise_score
score = channelwise_score.sum()
else:
numerator = (input_ * target).sum()
denominator = (input_ * input_).sum() + (target * target).sum()
score = 2.0 * (numerator / denominator.clamp(min=eps))
if invert:
score = 1.0 - score
return score
class DiceLossNew(nn.Module):
def __init__(self, channelwise=True, eps=1e-07):
super().__init__()
self.channelwise = channelwise
self.eps = eps
self.init_kwargs = {'channelwise': channelwise, 'eps': self.eps}
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
JonasHell/torch-em
|
DiceLoss
| false
| 8,393
|
[
"MIT"
] | 13
|
2e008e0cd2f0ea6681581374fce4f9f47b986d55
|
https://github.com/JonasHell/torch-em/tree/2e008e0cd2f0ea6681581374fce4f9f47b986d55
|
TopKMaxPooling
|
import torch
import torch.nn as nn
class TopKMaxPooling(nn.Module):
def __init__(self, kmax=1.0):
super(TopKMaxPooling, self).__init__()
self.kmax = kmax
@staticmethod
def get_positive_k(k, n):
if k <= 0:
return 0
elif k < 1:
return round(k * n)
elif k > n:
return int(n)
else:
return int(k)
def forward(self, input):
batch_size = input.size(0)
num_channels = input.size(1)
h = input.size(2)
w = input.size(3)
n = h * w
kmax = self.get_positive_k(self.kmax, n)
sorted, _indices = torch.sort(input.view(batch_size, num_channels,
n), dim=2, descending=True)
region_max = sorted.narrow(2, 0, kmax)
output = region_max.sum(2).div_(kmax)
return output.view(batch_size, num_channels)
def __repr__(self):
return self.__class__.__name__ + ' (kmax=' + str(self.kmax) + ')'
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_sort_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = r1
tmp2 = tmp1.to(tl.int16)
tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp4 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5, _tmp6 = triton_helpers.sort_with_index(tmp3, tmp4, None, 1,
stable=False, descending=True)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp5, xmask)
@triton.jit
def triton_poi_fused_div_sum_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_sort_0[grid(16)](arg0_1, buf0, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_div_sum_1[grid(16)](buf0, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf0
return buf2,
class TopKMaxPoolingNew(nn.Module):
def __init__(self, kmax=1.0):
super(TopKMaxPoolingNew, self).__init__()
self.kmax = kmax
@staticmethod
def get_positive_k(k, n):
if k <= 0:
return 0
elif k < 1:
return round(k * n)
elif k > n:
return int(n)
else:
return int(k)
def __repr__(self):
return self.__class__.__name__ + ' (kmax=' + str(self.kmax) + ')'
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Kanaricc/TDRG
|
TopKMaxPooling
| false
| 8,394
|
[
"Apache-2.0"
] | 16
|
91416976c8887877775f516ebee60469449e7e5f
|
https://github.com/Kanaricc/TDRG/tree/91416976c8887877775f516ebee60469449e7e5f
|
HadamardProduct
|
import torch
import torch.nn as nn
class HadamardProduct(nn.Module):
def __init__(self, shape):
super(HadamardProduct, self).__init__()
self.weights = nn.Parameter(torch.rand(shape))
def forward(self, x):
return x * self.weights
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'shape': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_2, primals_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
return buf0, primals_2
class HadamardProductNew(nn.Module):
def __init__(self, shape):
super(HadamardProductNew, self).__init__()
self.weights = nn.Parameter(torch.rand(shape))
def forward(self, input_0):
primals_1 = self.weights
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
KimUyen/LSTM-BCI-Decoder
|
HadamardProduct
| false
| 8,395
|
[
"MIT"
] | 38
|
c7b4bd108335a4d6c7d99c00c263346026186b0b
|
https://github.com/KimUyen/LSTM-BCI-Decoder/tree/c7b4bd108335a4d6c7d99c00c263346026186b0b
|
ResNetBottleneck
|
import torch
from torch import nn
import torch.nn.functional as F
class ResNetBottleneck(nn.Module):
def __init__(self, in_channels, out_channels, bottleneck_channels,
stride, downsample=None):
super(ResNetBottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_channels, bottleneck_channels,
kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(bottleneck_channels, bottleneck_channels,
kernel_size=3, stride=stride, padding=1, bias=False)
self.conv3 = nn.Conv2d(bottleneck_channels, out_channels,
kernel_size=1, bias=False)
self.downsample = downsample
def forward(self, x):
residual = x
out = F.relu(self.conv1(x), inplace=True)
out = F.relu(self.conv2(out), inplace=True)
out = self.conv3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = F.relu(out, inplace=True)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'bottleneck_channels':
4, 'stride': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_relu_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, 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, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_4, (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
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](buf1, 256, XBLOCK=128, num_warps
=4, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_relu_0[grid(256)](buf3, 256, XBLOCK=128, num_warps
=4, num_stages=1)
buf4 = extern_kernels.convolution(buf3, 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, 4, 4, 4), (64, 16, 4, 1))
buf5 = buf4
del buf4
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_1[grid(256)](buf5,
primals_1, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1)
return buf5, primals_1, primals_2, primals_3, primals_4, buf1, buf3, buf6
class ResNetBottleneckNew(nn.Module):
def __init__(self, in_channels, out_channels, bottleneck_channels,
stride, downsample=None):
super(ResNetBottleneckNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels, bottleneck_channels,
kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(bottleneck_channels, bottleneck_channels,
kernel_size=3, stride=stride, padding=1, bias=False)
self.conv3 = nn.Conv2d(bottleneck_channels, out_channels,
kernel_size=1, bias=False)
self.downsample = downsample
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv2.weight
primals_4 = self.conv3.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
KH-Kyle/rmp_nav
|
ResNetBottleneck
| false
| 8,396
|
[
"MIT"
] | 30
|
d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551
|
https://github.com/KH-Kyle/rmp_nav/tree/d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551
|
GlobalAttention_text
|
import torch
import torch.nn as nn
import torch.nn.parallel
class GlobalAttention_text(nn.Module):
def __init__(self, idf, cdf):
super(GlobalAttention_text, self).__init__()
self.conv_context = nn.Conv1d(cdf, idf, kernel_size=1, stride=1,
padding=0)
self.sm = nn.Softmax()
self.mask = None
def applyMask(self, mask):
self.mask = mask
def forward(self, input, context):
"""
input: batch x idf x ih x iw (queryL=ihxiw)
context: batch x cdf x sourceL
"""
ih, iw = input.size(2), input.size(3)
queryL = ih * iw
batch_size, sourceL = context.size(0), context.size(2)
target = input.view(batch_size, -1, queryL)
targetT = torch.transpose(target, 1, 2).contiguous()
sourceT = self.conv_context(context)
attn = torch.bmm(targetT, sourceT)
attn = attn.view(batch_size * queryL, sourceL)
if self.mask is not None:
mask = self.mask.repeat(queryL, 1)
attn.data.masked_fill_(mask.data, -float('inf'))
attn = attn.view(batch_size, queryL, sourceL)
attn = torch.nn.Softmax(dim=1)(attn)
text_weighted = torch.bmm(target, attn)
return text_weighted
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'idf': 4, 'cdf': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_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_transpose_0(in_ptr0, out_ptr0, out_ptr1, 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
y2 = yindex % 4
y3 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x1 + 16 * y0), xmask & ymask)
tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask)
tl.store(out_ptr1 + (y2 + 4 * x1 + 64 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_per_fused__softmax_2(in_ptr0, out_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 4
x1 = xindex // 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused__softmax_3(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
x2 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.exp(tmp2)
tmp5 = tmp3 / tmp4
tl.store(in_out_ptr0 + x3, tmp5, 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), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_3, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4), (16, 4, 1))
buf1 = empty_strided_cuda((4, 16, 4), (64, 1, 16), torch.float32)
buf8 = empty_strided_cuda((4, 4, 16), (64, 1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_transpose_0[grid(16, 16)](primals_1, buf1,
buf8, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
buf2 = buf0
del buf0
triton_poi_fused_convolution_1[grid(64)](buf2, primals_4, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(buf1, buf2, out=buf3)
del buf1
buf4 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
buf5 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
triton_per_fused__softmax_2[grid(16)](buf3, buf4, buf5, 16, 16,
XBLOCK=1, num_warps=2, num_stages=1)
buf6 = buf3
del buf3
triton_poi_fused__softmax_3[grid(256)](buf6, buf4, buf5, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del buf4
del buf5
buf7 = buf2
del buf2
extern_kernels.bmm(reinterpret_tensor(primals_1, (4, 4, 16), (64,
16, 1), 0), buf6, out=buf7)
return buf7, primals_2, primals_3, reinterpret_tensor(primals_1, (4, 16,
4), (64, 1, 16), 0), buf6, buf8
class GlobalAttention_textNew(nn.Module):
def __init__(self, idf, cdf):
super(GlobalAttention_textNew, self).__init__()
self.conv_context = nn.Conv1d(cdf, idf, kernel_size=1, stride=1,
padding=0)
self.sm = nn.Softmax()
self.mask = None
def applyMask(self, mask):
self.mask = mask
def forward(self, input_0, input_1):
primals_3 = self.conv_context.weight
primals_4 = self.conv_context.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
JoonHong-Kim/T2I_CL
|
GlobalAttention_text
| false
| 8,397
|
[
"MIT"
] | 35
|
c52aa73da903d6e4174eeef2663e5bc1163785b1
|
https://github.com/JoonHong-Kim/T2I_CL/tree/c52aa73da903d6e4174eeef2663e5bc1163785b1
|
GRUCell
|
import torch
from torch import nn
class GRUCell(nn.Module):
def __init__(self, input_size, hidden_size, init_scale=1.0,
no_weight_init=False):
super(GRUCell, self).__init__()
self.recurrent = nn.GRUCell(input_size, hidden_size)
if not no_weight_init:
for name, param in self.recurrent.named_parameters():
if 'weight' in name:
nn.init.orthogonal_(param, init_scale)
weight_inited = True
elif 'bias' in name:
with torch.no_grad():
param.zero_()
assert weight_inited
def forward(self, x, h=None):
return self.recurrent(x, h)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch 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_zeros_0(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = 0.0
tl.store(out_ptr0 + x0, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (12, 4), (4, 1))
assert_size_stride(primals_3, (12, 4), (4, 1))
assert_size_stride(primals_4, (12,), (1,))
assert_size_stride(primals_5, (12,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_zeros_0[grid(16)](buf0, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf1 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 12),
(1, 4), 0), out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (4, 12), (1,
4), 0), out=buf2)
del primals_3
buf3 = torch.ops.aten._thnn_fused_gru_cell.default(buf1, buf2, buf0,
primals_4, primals_5)
del buf1
del buf2
del primals_4
del primals_5
buf4 = buf3[0]
buf5 = buf3[1]
del buf3
return buf4, primals_1, buf0, buf5
class GRUCellNew(nn.Module):
def __init__(self, input_size, hidden_size, init_scale=1.0,
no_weight_init=False):
super(GRUCellNew, self).__init__()
self.recurrent = nn.GRUCell(input_size, hidden_size)
if not no_weight_init:
for name, param in self.recurrent.named_parameters():
if 'weight' in name:
nn.init.orthogonal_(param, init_scale)
weight_inited = True
elif 'bias' in name:
with torch.no_grad():
param.zero_()
assert weight_inited
def forward(self, input_0):
primals_2 = self.recurrent.weight_ih
primals_3 = self.recurrent.weight_hh
primals_4 = self.recurrent.bias_ih
primals_5 = self.recurrent.bias_hh
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
KH-Kyle/rmp_nav
|
GRUCell
| false
| 8,398
|
[
"MIT"
] | 30
|
d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551
|
https://github.com/KH-Kyle/rmp_nav/tree/d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551
|
Fusion
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
class Fusion(nn.Module):
""" Crazy multi-modal fusion: negative squared difference minus relu'd sum
"""
def __init__(self):
super().__init__()
def forward(self, x, y):
return -(x - y) ** 2 + F.relu(x + y)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_neg_pow_relu_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 = tmp2 * tmp2
tmp4 = -tmp3
tmp5 = tmp0 + tmp1
tmp6 = tl.full([1], 0, tl.int32)
tmp7 = triton_helpers.maximum(tmp6, tmp5)
tmp8 = tmp4 + tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_neg_pow_relu_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 FusionNew(nn.Module):
""" Crazy multi-modal fusion: negative squared difference minus relu'd sum
"""
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]
|
KaihuaTang/VCTree-Visual-Question-Answering
|
Fusion
| false
| 8,399
|
[
"MIT"
] | 31
|
b6b0a8bdb01d45d36de3bded91db42544ad6a593
|
https://github.com/KaihuaTang/VCTree-Visual-Question-Answering/tree/b6b0a8bdb01d45d36de3bded91db42544ad6a593
|
CommandEmbedding
|
import torch
from torch import Tensor
from torch import nn
class CommandEmbedding(nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.embedding = nn.Linear(input_size, output_size // 2)
self.encoding = nn.Parameter(torch.rand(1, 1, output_size // 2))
def forward(self, command: 'Tensor') ->Tensor:
return torch.cat([self.embedding(command), self.encoding.expand(
command.size(0), command.size(1), -1)], dim=-1)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch 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_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 2, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (2 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 4, tl.int64)
tmp9 = tl.load(in_ptr1 + (-2 + x0), tmp6 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (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, (1, 1, 2), (2, 2, 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((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(64)](buf0, primals_4, buf1, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del buf0
del primals_4
return buf1, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0)
class CommandEmbeddingNew(nn.Module):
def __init__(self, input_size, output_size):
super().__init__()
self.embedding = nn.Linear(input_size, output_size // 2)
self.encoding = nn.Parameter(torch.rand(1, 1, output_size // 2))
def forward(self, input_0):
primals_4 = self.encoding
primals_1 = self.embedding.weight
primals_2 = self.embedding.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Kaixhin/GUDRL
|
CommandEmbedding
| false
| 8,400
|
[
"MIT"
] | 26
|
c13fa605a9ffb4c2932390b0b86e476aec62c142
|
https://github.com/Kaixhin/GUDRL/tree/c13fa605a9ffb4c2932390b0b86e476aec62c142
|
BertLayerNormNoVar
|
import torch
import torch.nn as nn
class BertLayerNormNoVar(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
super(BertLayerNormNoVar, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
x = x - u
return self.weight * x + self.bias
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mean_mul_sub_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp13 = 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
tmp14 = tmp12 + tmp13
tl.store(out_ptr0 + x2, tmp14, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mean_mul_sub_0[grid(256)](primals_2, primals_1,
primals_3, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
del primals_3
return buf0, primals_1
class BertLayerNormNoVarNew(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
super(BertLayerNormNoVarNew, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, input_0):
primals_2 = self.weight
primals_3 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
KaidiXu/LiRPA_Verify
|
BertLayerNormNoVar
| false
| 8,401
|
[
"BSD-2-Clause"
] | 14
|
71f5327a8abf136bcfb3e1ec07604628abf8126e
|
https://github.com/KaidiXu/LiRPA_Verify/tree/71f5327a8abf136bcfb3e1ec07604628abf8126e
|
ConvLSTMCell
|
import torch
import torch.nn as nn
from torch.autograd import Variable
class ConvLSTMCell(nn.Module):
def __init__(self, input_channels, hidden_channels, kernel_size, bias=True
):
super(ConvLSTMCell, self).__init__()
assert hidden_channels % 2 == 0
self.input_channels = input_channels
self.hidden_channels = hidden_channels
self.bias = bias
self.kernel_size = kernel_size
self.padding = int((kernel_size - 1) / 2)
self.Gates = nn.Conv2d(self.input_channels + self.hidden_channels,
4 * self.hidden_channels, self.kernel_size, 1, self.padding,
bias=True)
def forward(self, x, h, c):
stacked_inputs = torch.cat((x, h), 1)
gates = self.Gates(stacked_inputs)
xi, xf, xo, xg = gates.chunk(4, 1)
xi = torch.sigmoid(xi)
xf = torch.sigmoid(xf)
xo = torch.sigmoid(xo)
xg = torch.tanh(xg)
c = xf * c + xi * xg
h = xo * torch.tanh(c)
return h, c
def init_hidden(self, batch_size, hidden, shape):
return Variable(torch.zeros(batch_size, hidden, shape[0], shape[1])
), Variable(torch.zeros(batch_size, hidden, shape[0], shape[1]))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 3, 3])]
def get_init_inputs():
return [[], {'input_channels': 4, 'hidden_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.autograd import Variable
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask,
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_sigmoid_backward_tanh_1(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr2, out_ptr3, out_ptr4,
out_ptr5, xnumel, XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 36
x4 = xindex % 36
x1 = xindex // 9 % 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (72 + x4 + 144 * x2), xmask)
tmp1 = tl.load(in_ptr1 + (8 + x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (x4 + 144 * x2), xmask)
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (108 + x4 + 144 * x2), xmask)
tmp9 = tl.load(in_ptr1 + (12 + x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (36 + x4 + 144 * x2), xmask)
tmp13 = tl.load(in_ptr1 + (4 + x1), xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr2 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp6 = tmp4 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp10 = tmp8 + tmp9
tmp11 = libdevice.tanh(tmp10)
tmp14 = tmp12 + tmp13
tmp15 = tl.sigmoid(tmp14)
tmp17 = tmp15 * tmp16
tmp18 = tmp7 * tmp11
tmp19 = tmp17 + tmp18
tmp20 = 1.0
tmp21 = tmp20 - tmp15
tmp22 = tmp15 * tmp21
tmp23 = libdevice.tanh(tmp19)
tmp24 = tmp3 * tmp23
tl.store(out_ptr0 + x3, tmp3, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
tl.store(out_ptr2 + x3, tmp11, xmask)
tl.store(out_ptr3 + x3, tmp19, xmask)
tl.store(out_ptr4 + x3, tmp22, xmask)
tl.store(out_ptr5 + x3, tmp24, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (16, 8, 4, 4), (128, 16, 4, 1))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](primals_1, primals_2, buf0, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = extern_kernels.convolution(buf0, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 16, 3, 3), (144, 9, 3, 1))
buf3 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
buf7 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_sigmoid_backward_tanh_1[grid(144)](
buf1, primals_4, primals_5, buf3, buf2, buf4, buf5, buf7, buf6,
144, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_4
return buf6, buf5, primals_3, primals_5, buf0, buf2, buf3, buf4, buf5, buf7
class ConvLSTMCellNew(nn.Module):
def __init__(self, input_channels, hidden_channels, kernel_size, bias=True
):
super(ConvLSTMCellNew, self).__init__()
assert hidden_channels % 2 == 0
self.input_channels = input_channels
self.hidden_channels = hidden_channels
self.bias = bias
self.kernel_size = kernel_size
self.padding = int((kernel_size - 1) / 2)
self.Gates = nn.Conv2d(self.input_channels + self.hidden_channels,
4 * self.hidden_channels, self.kernel_size, 1, self.padding,
bias=True)
def init_hidden(self, batch_size, hidden, shape):
return Variable(torch.zeros(batch_size, hidden, shape[0], shape[1])
), Variable(torch.zeros(batch_size, hidden, shape[0], shape[1]))
def forward(self, input_0, input_1, input_2):
primals_3 = self.Gates.weight
primals_4 = self.Gates.bias
primals_1 = input_0
primals_2 = input_1
primals_5 = input_2
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0], output[1]
|
Kwanss/PCLNet
|
ConvLSTMCell
| false
| 8,402
|
[
"MIT"
] | 31
|
d288820975a9daf23eab47c52d7ea6f7dd564725
|
https://github.com/Kwanss/PCLNet/tree/d288820975a9daf23eab47c52d7ea6f7dd564725
|
CAMBlock
|
import torch
class CAMBlock(torch.nn.Module):
def __init__(self, inplanes, redr, pool='full'):
super(CAMBlock, self).__init__()
self.planes = inplanes // redr
self.poolingavg = torch.nn.AdaptiveAvgPool2d((1, 1))
self.poolingmax = torch.nn.AdaptiveMaxPool2d((1, 1))
self.avglinear1 = torch.nn.Conv2d(inplanes, self.planes, (1, 1),
padding=0)
self.maxlinear1 = torch.nn.Conv2d(inplanes, self.planes, (1, 1),
padding=0)
self.relu = torch.nn.ReLU(inplace=True)
self.avglinear2 = torch.nn.Conv2d(self.planes, inplanes, (1, 1),
padding=0)
self.maxlinear2 = torch.nn.Conv2d(self.planes, inplanes, (1, 1),
padding=0)
self.sigmod = torch.nn.Sigmoid()
def forward(self, x):
x1 = self.poolingavg(x)
x2 = self.poolingmax(x)
x1 = self.avglinear1(x1)
x1 = self.relu(x1)
x1 = self.avglinear2(x1)
x2 = self.maxlinear1(x2)
x2 = self.relu(x2)
x2 = self.maxlinear2(x2)
out = x1 + x2
out = self.sigmod(out)
out = x * out
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'redr': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_adaptive_max_pool2d_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp7 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp17 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp20 = triton_helpers.maximum(tmp19, tmp18)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = triton_helpers.maximum(tmp23, tmp22)
tmp26 = triton_helpers.maximum(tmp25, tmp24)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tl.store(out_ptr0 + x0, tmp30, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tl.store(in_out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_convolution_mul_sigmoid_3(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, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp6 = tmp4 + tmp5
tmp7 = tmp3 + tmp6
tmp8 = tl.sigmoid(tmp7)
tmp9 = tmp0 * tmp8
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused_add_convolution_sigmoid_sigmoid_backward_4(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_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')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp8 = 1.0
tmp9 = tmp8 - tmp7
tmp10 = tmp7 * tmp9
tl.store(in_out_ptr0 + x2, tmp10, 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, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (4, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_7, (1,), (1,))
assert_size_stride(primals_8, (4, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
triton_poi_fused_adaptive_max_pool2d_1[grid(16)](primals_1, buf2,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf3 = 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(buf3, (4, 1, 1, 1), (1, 1, 1, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_relu_2[grid(4)](buf4, primals_3, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_3
buf5 = extern_kernels.convolution(buf4, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 4, 1, 1), (4, 1, 1, 1))
buf6 = extern_kernels.convolution(buf2, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 1, 1, 1), (1, 1, 1, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_2[grid(4)](buf7, primals_7, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_7
buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 4, 1, 1), (4, 1, 1, 1))
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_convolution_mul_sigmoid_3[grid(256)](primals_1,
buf5, primals_5, buf8, primals_9, buf9, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf10 = buf5
del buf5
triton_poi_fused_add_convolution_sigmoid_sigmoid_backward_4[grid(16)](
buf10, primals_5, buf8, primals_9, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf8
del primals_5
del primals_9
return (buf9, primals_1, primals_2, primals_4, primals_6, primals_8,
buf1, buf2, buf4, buf7, buf10)
class CAMBlockNew(torch.nn.Module):
def __init__(self, inplanes, redr, pool='full'):
super(CAMBlockNew, self).__init__()
self.planes = inplanes // redr
self.poolingavg = torch.nn.AdaptiveAvgPool2d((1, 1))
self.poolingmax = torch.nn.AdaptiveMaxPool2d((1, 1))
self.avglinear1 = torch.nn.Conv2d(inplanes, self.planes, (1, 1),
padding=0)
self.maxlinear1 = torch.nn.Conv2d(inplanes, self.planes, (1, 1),
padding=0)
self.relu = torch.nn.ReLU(inplace=True)
self.avglinear2 = torch.nn.Conv2d(self.planes, inplanes, (1, 1),
padding=0)
self.maxlinear2 = torch.nn.Conv2d(self.planes, inplanes, (1, 1),
padding=0)
self.sigmod = torch.nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.avglinear1.weight
primals_3 = self.avglinear1.bias
primals_6 = self.maxlinear1.weight
primals_7 = self.maxlinear1.bias
primals_4 = self.avglinear2.weight
primals_5 = self.avglinear2.bias
primals_8 = self.maxlinear2.weight
primals_9 = self.maxlinear2.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]
|
Knight825/models-pytorch
|
CAMBlock
| false
| 8,403
|
[
"Apache-2.0"
] | 16
|
133559eebb8795d78a32fa44d49408d0c5167ae9
|
https://github.com/Knight825/models-pytorch/tree/133559eebb8795d78a32fa44d49408d0c5167ae9
|
Gram
|
import torch
import torch.nn as nn
class Gram(nn.Module):
def __init__(self):
super(Gram, self).__init__()
def forward(self, input):
a, b, c, d = input.size()
feature = input.view(a * b, c * d)
gram = torch.mm(feature, feature.t())
gram /= a * b * c * d
return gram
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_div_0(in_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.00390625
tmp2 = tmp0 * tmp1
tl.store(in_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((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(arg0_1, (16, 16), (16, 1), 0),
reinterpret_tensor(arg0_1, (16, 16), (1, 16), 0), out=buf0)
del arg0_1
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_div_0[grid(256)](buf1, 256, XBLOCK=128, num_warps=
4, num_stages=1)
return buf1,
class GramNew(nn.Module):
def __init__(self):
super(GramNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
L1aoXingyu/neural-transfer
|
Gram
| false
| 8,404
|
[
"MIT"
] | 45
|
bed445791d823872d9a40ea8927681d8cc99e8df
|
https://github.com/L1aoXingyu/neural-transfer/tree/bed445791d823872d9a40ea8927681d8cc99e8df
|
BiLSTM_Encoder
|
import torch
import torch as T
import torch.nn as nn
class BiLSTM_Encoder(nn.Module):
def __init__(self, D: 'int', hidden_size: 'int', dropout: 'float'):
super(BiLSTM_Encoder, self).__init__()
self.D = D
self.hidden_size = hidden_size
self.initial_hidden_f = nn.Parameter(T.randn(1, hidden_size))
self.initial_hidden_b = nn.Parameter(T.randn(1, hidden_size))
self.initial_cell_f = nn.Parameter(T.randn(1, hidden_size))
self.initial_cell_b = nn.Parameter(T.randn(1, hidden_size))
self.dropout = nn.Dropout(dropout)
self.weight_ih = nn.Parameter(T.randn(8, D, hidden_size))
self.weight_hh = nn.Parameter(T.randn(8, hidden_size, hidden_size))
self.bias = nn.Parameter(T.zeros(8, 1, hidden_size))
self.init_weights()
def init_weights(self):
for name, param in self.named_parameters():
if 'bias' in name.lower():
nn.init.zeros_(param.data)
elif 'hidden_state' or 'cell' in name.lower():
nn.init.zeros_(param.data)
else:
nn.init.xavier_uniform_(param.data)
def forward(self, x, mask):
N, S, D = x.size()
mask = mask.view(N, S, 1)
hidden_f = self.initial_hidden_f
hidden_b = self.initial_hidden_b
cell_f = self.initial_cell_f
cell_b = self.initial_cell_b
hidden_states_f = []
hidden_states_b = []
self.dropout(self.weight_ih)
weight_hh = self.dropout(self.weight_hh)
x = x.view(1, N * S, D)
x_h = T.matmul(x, self.weight_ih) + self.bias
x_h = x_h.view(8, N, S, self.hidden_size)
for t in range(S):
hidden_f = hidden_f.view(1, -1, self.hidden_size)
xf = x_h[0:4, :, t]
hf = T.matmul(hidden_f, weight_hh[0:4])
preacts = xf + hf
gates = T.sigmoid(preacts[0:3])
f = gates[0]
i = gates[1]
o = gates[2]
cell_ = T.tanh(preacts[3])
cell_f = f * cell_f + i * cell_
hidden_f_ = o * T.tanh(cell_f)
hidden_f = hidden_f.view(-1, self.hidden_size)
hidden_f = T.where(mask[:, t] == 0.0, hidden_f, hidden_f_)
hidden_states_f.append(hidden_f.view(1, N, self.hidden_size))
hidden_b = hidden_b.view(1, -1, self.hidden_size)
xb = x_h[4:, :, S - t - 1]
hb = T.matmul(hidden_b, weight_hh[4:])
preacts = xb + hb
gates = T.sigmoid(preacts[0:3])
f = gates[0]
i = gates[1]
o = gates[2]
cell_ = T.tanh(preacts[3])
cell_b = f * cell_b + i * cell_
hidden_b_ = o * T.tanh(cell_b)
hidden_b = hidden_b.view(-1, self.hidden_size)
hidden_b = T.where(mask[:, S - t - 1] == 0.0, hidden_b, hidden_b_)
hidden_states_b.append(hidden_b.view(1, N, self.hidden_size))
hidden_states_f = T.cat(hidden_states_f, dim=0)
hidden_states_f = T.transpose(hidden_states_f, 0, 1)
hidden_states_b.reverse()
hidden_states_b = T.cat(hidden_states_b, dim=0)
hidden_states_b = T.transpose(hidden_states_b, 0, 1)
hidden_states = T.cat([hidden_states_f, hidden_states_b], dim=-1
) * mask
final_state = T.cat([hidden_states_f[:, -1, :], hidden_states_b[:,
0, :]], dim=-1)
return hidden_states, final_state
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 1])]
def get_init_inputs():
return [[], {'D': 4, 'hidden_size': 4, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch as T
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 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_sigmoid_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x3 = xindex // 4
x2 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x3), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + x4, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_eq_mul_tanh_where_2(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, out_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (192 + x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + 4 * x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr5 + (32 + x2), xmask)
tmp11 = tl.load(in_ptr5 + x2, xmask)
tmp12 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr5 + (16 + x2), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp7 = 0.0
tmp8 = tmp6 == tmp7
tmp13 = tmp11 * tmp12
tmp15 = tmp14 * tmp5
tmp16 = tmp13 + tmp15
tmp17 = libdevice.tanh(tmp16)
tmp18 = tmp10 * tmp17
tmp19 = tl.where(tmp8, tmp9, tmp18)
tl.store(out_ptr0 + x2, tmp5, xmask)
tl.store(out_ptr1 + x2, tmp19, 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 + (64 + 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_sigmoid_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x3 = xindex // 4
x2 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + (268 + x0 + 16 * x3), xmask)
tmp1 = tl.load(in_ptr1 + (16 + x0 + 4 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + x4, tmp5, xmask)
@triton.jit
def triton_poi_fused_add_eq_mul_tanh_where_5(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, out_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (460 + x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (28 + x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr5 + (32 + x2), xmask)
tmp11 = tl.load(in_ptr5 + x2, xmask)
tmp12 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr5 + (16 + x2), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp7 = 0.0
tmp8 = tmp6 == tmp7
tmp13 = tmp11 * tmp12
tmp15 = tmp14 * tmp5
tmp16 = tmp13 + tmp15
tmp17 = libdevice.tanh(tmp16)
tmp18 = tmp10 * tmp17
tmp19 = tl.where(tmp8, tmp9, tmp18)
tl.store(out_ptr0 + x2, tmp5, xmask)
tl.store(out_ptr1 + x2, tmp19, xmask)
@triton.jit
def triton_poi_fused_sigmoid_6(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (4 + x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x2 + 4 * y1), xmask & ymask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_add_eq_mul_tanh_where_7(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, out_ptr0,
out_ptr1, out_ptr2, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (196 + x1 + 16 * y0), xmask & ymask)
tmp1 = tl.load(in_ptr1 + (12 + x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (48 + y0 + 4 * x1), xmask & ymask)
tmp6 = tl.load(in_ptr3 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr4 + (x1 + 4 * y0), xmask & ymask)
tmp8 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + (16 + x1 + 4 * y0), xmask & ymask)
tmp11 = tl.load(in_ptr6 + (x1 + 4 * y0), xmask & ymask)
tmp15 = tl.load(in_ptr3 + (16 + x1 + 4 * y0), xmask & ymask)
tmp18 = tl.load(in_ptr7 + (1 + 4 * y0), ymask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr8 + (x1 + 4 * y0), xmask & ymask)
tmp22 = tl.load(in_ptr3 + (32 + x1 + 4 * y0), xmask & ymask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp9 = tmp7 * tmp8
tmp12 = tmp10 * tmp11
tmp13 = tmp9 + tmp12
tmp14 = tmp6 * tmp13
tmp16 = tmp15 * tmp5
tmp17 = tmp14 + tmp16
tmp19 = 0.0
tmp20 = tmp18 == tmp19
tmp23 = libdevice.tanh(tmp17)
tmp24 = tmp22 * tmp23
tmp25 = tl.where(tmp20, tmp21, tmp24)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp5, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp17, xmask & ymask)
tl.store(out_ptr2 + (x1 + 4 * y0), tmp25, xmask & ymask)
@triton.jit
def triton_poi_fused_sigmoid_8(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (264 + x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (16 + x2 + 4 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_sigmoid_9(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (8 + x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x2 + 4 * y1), xmask & ymask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_add_eq_mul_tanh_where_10(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10,
in_ptr11, in_ptr12, out_ptr0, out_ptr1, out_ptr2, out_ptr3, out_ptr4,
out_ptr5, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (456 + x1 + 16 * y0), xmask & ymask)
tmp1 = tl.load(in_ptr1 + (28 + x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (48 + y0 + 4 * x1), xmask & ymask)
tmp6 = tl.load(in_ptr3 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr4 + (x1 + 4 * y0), xmask & ymask)
tmp8 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + (16 + x1 + 4 * y0), xmask & ymask)
tmp11 = tl.load(in_ptr6 + (x1 + 4 * y0), xmask & ymask)
tmp15 = tl.load(in_ptr3 + (16 + x1 + 4 * y0), xmask & ymask)
tmp18 = tl.load(in_ptr7 + (2 + 4 * y0), ymask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr8 + (x1 + 4 * y0), xmask & ymask)
tmp22 = tl.load(in_ptr3 + (32 + x1 + 4 * y0), xmask & ymask)
tmp26 = tl.load(in_ptr0 + (200 + x1 + 16 * y0), xmask & ymask)
tmp27 = tl.load(in_ptr1 + (12 + x1), xmask, eviction_policy='evict_last')
tmp29 = tl.load(in_ptr9 + (48 + y0 + 4 * x1), xmask & ymask)
tmp32 = tl.load(in_ptr10 + (x1 + 4 * y0), xmask & ymask)
tmp33 = tl.load(in_ptr11 + (x1 + 4 * y0), xmask & ymask)
tmp35 = tl.load(in_ptr10 + (16 + x1 + 4 * y0), xmask & ymask)
tmp38 = tl.load(in_ptr12 + (x1 + 4 * y0), xmask & ymask)
tmp39 = tl.load(in_ptr10 + (32 + x1 + 4 * y0), xmask & ymask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp9 = tmp7 * tmp8
tmp12 = tmp10 * tmp11
tmp13 = tmp9 + tmp12
tmp14 = tmp6 * tmp13
tmp16 = tmp15 * tmp5
tmp17 = tmp14 + tmp16
tmp19 = 0.0
tmp20 = tmp18 == tmp19
tmp23 = libdevice.tanh(tmp17)
tmp24 = tmp22 * tmp23
tmp25 = tl.where(tmp20, tmp21, tmp24)
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp31 = libdevice.tanh(tmp30)
tmp34 = tmp32 * tmp33
tmp36 = tmp35 * tmp31
tmp37 = tmp34 + tmp36
tmp40 = libdevice.tanh(tmp37)
tmp41 = tmp39 * tmp40
tmp42 = tl.where(tmp20, tmp38, tmp41)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp5, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp17, xmask & ymask)
tl.store(out_ptr2 + (x1 + 4 * y0), tmp25, xmask & ymask)
tl.store(out_ptr3 + (x1 + 4 * y0), tmp31, xmask & ymask)
tl.store(out_ptr4 + (x1 + 4 * y0), tmp37, xmask & ymask)
tl.store(out_ptr5 + (x1 + 4 * y0), tmp42, xmask & ymask)
@triton.jit
def triton_poi_fused_sigmoid_11(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (260 + x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (16 + x2 + 4 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_add_eq_mul_tanh_where_12(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, out_ptr1, out_ptr2,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (452 + x1 + 16 * y0), xmask & ymask)
tmp1 = tl.load(in_ptr1 + (28 + x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (48 + y0 + 4 * x1), xmask & ymask)
tmp6 = tl.load(in_ptr3 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr4 + (x1 + 4 * y0), xmask & ymask)
tmp9 = tl.load(in_ptr3 + (16 + x1 + 4 * y0), xmask & ymask)
tmp12 = tl.load(in_ptr5 + (1 + 4 * y0), ymask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr6 + (x1 + 4 * y0), xmask & ymask)
tmp16 = tl.load(in_ptr3 + (32 + x1 + 4 * y0), xmask & ymask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 * tmp7
tmp10 = tmp9 * tmp5
tmp11 = tmp8 + tmp10
tmp13 = 0.0
tmp14 = tmp12 == tmp13
tmp17 = libdevice.tanh(tmp11)
tmp18 = tmp16 * tmp17
tmp19 = tl.where(tmp14, tmp15, tmp18)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp5, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp11, xmask & ymask)
tl.store(out_ptr2 + (x1 + 4 * y0), tmp19, xmask & ymask)
@triton.jit
def triton_poi_fused_sigmoid_13(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (12 + x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x2 + 4 * y1), xmask & ymask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mul_tanh_14(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr,
XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (204 + x1 + 16 * y0), xmask & ymask)
tmp1 = tl.load(in_ptr1 + (12 + x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (48 + y0 + 4 * x1), xmask & ymask)
tmp6 = tl.load(in_ptr3 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr4 + (x1 + 4 * y0), xmask & ymask)
tmp9 = tl.load(in_ptr3 + (16 + x1 + 4 * y0), xmask & ymask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 * tmp7
tmp10 = tmp9 * tmp5
tmp11 = tmp8 + tmp10
tmp12 = libdevice.tanh(tmp11)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp5, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp12, xmask & ymask)
@triton.jit
def triton_poi_fused_sigmoid_15(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4
y0 = yindex % 4
tmp0 = tl.load(in_ptr0 + (256 + x2 + 16 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (16 + x2 + 4 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = tl.sigmoid(tmp4)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp5, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mul_tanh_16(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr,
XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (448 + x1 + 16 * y0), xmask & ymask)
tmp1 = tl.load(in_ptr1 + (28 + x1), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (48 + y0 + 4 * x1), xmask & ymask)
tmp6 = tl.load(in_ptr3 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr4 + (x1 + 4 * y0), xmask & ymask)
tmp9 = tl.load(in_ptr3 + (16 + x1 + 4 * y0), xmask & ymask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp5 = libdevice.tanh(tmp4)
tmp8 = tmp6 * tmp7
tmp10 = tmp9 * tmp5
tmp11 = tmp8 + tmp10
tmp12 = libdevice.tanh(tmp11)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp5, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp12, xmask & ymask)
@triton.jit
def triton_poi_fused_cat_17(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + x3, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 2, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + x3, tmp9 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 3, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr2 + x3, tmp14 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 4, tl.int64)
tmp19 = tl.load(in_ptr3 + (3 + 4 * x1), tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = 0.0
tmp21 = tmp19 == tmp20
tmp22 = tl.load(in_ptr2 + x3, tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp23 = tl.load(in_ptr4 + (32 + x3), tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp24 = tl.load(in_ptr5 + x3, tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp25 = tmp23 * tmp24
tmp26 = tl.where(tmp21, tmp22, tmp25)
tmp27 = tl.full(tmp26.shape, 0.0, tmp26.dtype)
tmp28 = tl.where(tmp16, tmp26, tmp27)
tmp29 = tl.where(tmp14, tmp15, tmp28)
tmp30 = tl.where(tmp9, tmp10, tmp29)
tmp31 = tl.where(tmp4, tmp5, tmp30)
tl.store(out_ptr0 + x4, tmp31, xmask)
@triton.jit
def triton_poi_fused_cat_18(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x1 = xindex // 4 % 4
x3 = xindex % 16
x4 = xindex
tmp0 = x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + 4 * x1, tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = 0.0
tmp7 = tmp5 == tmp6
tmp8 = tl.load(in_ptr1 + x3, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp9 = tl.load(in_ptr2 + (32 + x3), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp10 = tl.load(in_ptr3 + x3, tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp11 = tmp9 * tmp10
tmp12 = tl.where(tmp7, tmp8, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tmp16 = tl.full([1], 2, tl.int64)
tmp17 = tmp0 < tmp16
tmp18 = tmp15 & tmp17
tmp19 = tl.load(in_ptr1 + x3, tmp18 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = tmp0 >= tmp16
tmp21 = tl.full([1], 3, tl.int64)
tmp22 = tmp0 < tmp21
tmp23 = tmp20 & tmp22
tmp24 = tl.load(in_ptr4 + x3, tmp23 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp25 = tmp0 >= tmp21
tl.full([1], 4, tl.int64)
tmp28 = tl.load(in_ptr5 + x3, tmp25 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp29 = tl.where(tmp23, tmp24, tmp28)
tmp30 = tl.where(tmp18, tmp19, tmp29)
tmp31 = tl.where(tmp4, tmp14, tmp30)
tl.store(out_ptr0 + x4, tmp31, xmask)
@triton.jit
def triton_poi_fused_cat_mul_19(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8 % 4
x2 = xindex // 32
x3 = xindex // 8
x4 = xindex
tmp11 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x2 + 16 * 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 * x2 + 16 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tmp12 = tmp10 * tmp11
tl.store(out_ptr0 + x4, tmp12, xmask)
@triton.jit
def triton_poi_fused_cat_20(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 + (48 + 4 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
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, 1), (4, 1, 1))
assert_size_stride(primals_3, (1, 4), (4, 1))
assert_size_stride(primals_4, (1, 4), (4, 1))
assert_size_stride(primals_5, (1, 4), (4, 1))
assert_size_stride(primals_6, (1, 4), (4, 1))
assert_size_stride(primals_7, (8, 4, 4), (16, 4, 1))
assert_size_stride(primals_8, (8, 4, 4), (16, 4, 1))
assert_size_stride(primals_9, (8, 1, 4), (4, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((8, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (8, 16, 4), (0, 4,
1), 0), primals_7, out=buf0)
del primals_7
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](primals_8, buf1, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 1), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_1[grid(48)](buf0, primals_9, buf2, buf3,
48, XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_eq_mul_tanh_where_2[grid(16)](buf0, primals_9,
buf2, primals_2, primals_3, buf3, primals_5, buf4, buf5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](primals_8, buf6, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_8
buf7 = buf2
del buf2
extern_kernels.mm(reinterpret_tensor(buf6, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 1), (1, 4), 0), out=buf7)
buf8 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_4[grid(48)](buf0, primals_9, buf7, buf8,
48, XBLOCK=64, num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_eq_mul_tanh_where_5[grid(16)](buf0, primals_9,
buf7, primals_2, primals_4, buf8, primals_6, buf9, buf10, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(buf5, (4, 4), (1, 4), 0), out=buf11)
buf12 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_6[grid(12, 4)](buf0, primals_9, buf11,
buf12, 12, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
buf13 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
del buf7
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf19 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_eq_mul_tanh_where_7[grid(4, 4)](buf0,
primals_9, buf11, buf12, buf3, primals_5, buf4, primals_2, buf5,
buf13, buf14, buf19, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1,
num_stages=1)
buf15 = buf11
del buf11
extern_kernels.mm(reinterpret_tensor(buf6, (16, 4), (4, 1), 0),
reinterpret_tensor(buf10, (4, 4), (1, 4), 0), out=buf15)
buf16 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_8[grid(12, 4)](buf0, primals_9, buf15,
buf16, 12, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf20 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(buf19, (4, 4), (1, 4), 0), out=buf20)
buf21 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_9[grid(12, 4)](buf0, primals_9, buf20,
buf21, 12, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf24 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf22 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf23 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf29 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_eq_mul_tanh_where_10[grid(4, 4)](buf0,
primals_9, buf15, buf16, buf8, primals_6, buf9, primals_2,
buf10, buf20, buf21, buf14, buf19, buf17, buf18, buf24, buf22,
buf23, buf29, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
buf25 = buf20
del buf20
extern_kernels.mm(reinterpret_tensor(buf6, (16, 4), (4, 1), 0),
reinterpret_tensor(buf24, (4, 4), (1, 4), 0), out=buf25)
buf26 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_11[grid(12, 4)](buf0, primals_9, buf25,
buf26, 12, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf27 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf28 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf34 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_eq_mul_tanh_where_12[grid(4, 4)](buf0,
primals_9, buf25, buf26, buf18, primals_2, buf24, buf27, buf28,
buf34, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
buf30 = buf25
del buf25
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(buf29, (4, 4), (1, 4), 0), out=buf30)
buf31 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_13[grid(12, 4)](buf0, primals_9, buf30,
buf31, 12, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
buf32 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf33 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_tanh_14[grid(4, 4)](buf0, primals_9, buf30,
buf31, buf23, buf32, buf33, 4, 4, XBLOCK=4, YBLOCK=4, num_warps
=1, num_stages=1)
buf35 = buf30
del buf30
extern_kernels.mm(reinterpret_tensor(buf6, (16, 4), (4, 1), 0),
reinterpret_tensor(buf34, (4, 4), (1, 4), 0), out=buf35)
buf36 = empty_strided_cuda((3, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sigmoid_15[grid(12, 4)](buf0, primals_9, buf35,
buf36, 12, 4, XBLOCK=4, YBLOCK=8, num_warps=1, num_stages=1)
buf37 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf38 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_mul_tanh_16[grid(4, 4)](buf0, primals_9, buf35,
buf36, buf28, buf37, buf38, 4, 4, XBLOCK=4, YBLOCK=4, num_warps
=1, num_stages=1)
del buf0
del primals_9
buf39 = reinterpret_tensor(buf35, (4, 4, 4), (16, 4, 1), 0)
del buf35
triton_poi_fused_cat_17[grid(64)](buf5, buf19, buf29, primals_2,
buf31, buf33, buf39, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf40 = reinterpret_tensor(buf15, (4, 4, 4), (16, 4, 1), 0)
del buf15
triton_poi_fused_cat_18[grid(64)](primals_2, buf34, buf36, buf38,
buf24, buf10, buf40, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf41 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_cat_mul_19[grid(128)](buf39, buf40, primals_2,
buf41, 128, XBLOCK=128, num_warps=4, num_stages=1)
buf42 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_20[grid(32)](buf39, buf40, buf42, 32, XBLOCK=
32, num_warps=1, num_stages=1)
del buf39
del buf40
return (buf41, buf42, primals_1, primals_2, primals_5, primals_6,
reinterpret_tensor(buf1, (16, 4), (4, 1), 0), buf3, buf4,
reinterpret_tensor(buf6, (16, 4), (4, 1), 0), buf8, buf9, buf12,
buf13, buf14, buf16, buf17, buf18, buf21, buf22, buf23, buf26,
buf27, buf28, buf31, buf32, buf33, buf36, buf37, buf38, buf34,
buf29, buf24, buf19, buf10, buf5, primals_4, primals_3)
class BiLSTM_EncoderNew(nn.Module):
def __init__(self, D: 'int', hidden_size: 'int', dropout: 'float'):
super(BiLSTM_EncoderNew, self).__init__()
self.D = D
self.hidden_size = hidden_size
self.initial_hidden_f = nn.Parameter(T.randn(1, hidden_size))
self.initial_hidden_b = nn.Parameter(T.randn(1, hidden_size))
self.initial_cell_f = nn.Parameter(T.randn(1, hidden_size))
self.initial_cell_b = nn.Parameter(T.randn(1, hidden_size))
self.dropout = nn.Dropout(dropout)
self.weight_ih = nn.Parameter(T.randn(8, D, hidden_size))
self.weight_hh = nn.Parameter(T.randn(8, hidden_size, hidden_size))
self.bias = nn.Parameter(T.zeros(8, 1, hidden_size))
self.init_weights()
def init_weights(self):
for name, param in self.named_parameters():
if 'bias' in name.lower():
nn.init.zeros_(param.data)
elif 'hidden_state' or 'cell' in name.lower():
nn.init.zeros_(param.data)
else:
nn.init.xavier_uniform_(param.data)
def forward(self, input_0, input_1):
primals_3 = self.initial_hidden_f
primals_4 = self.initial_hidden_b
primals_5 = self.initial_cell_f
primals_6 = self.initial_cell_b
primals_7 = self.weight_ih
primals_8 = self.weight_hh
primals_9 = self.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, primals_9])
return output[0], output[1]
|
JRC1995/BERT-Disaster-Classification-Capsule-Routing
|
BiLSTM_Encoder
| false
| 8,405
|
[
"MIT"
] | 16
|
520d2b37af309c95f09bcda321915cffae803086
|
https://github.com/JRC1995/BERT-Disaster-Classification-Capsule-Routing/tree/520d2b37af309c95f09bcda321915cffae803086
|
MultiHeadQKVAttention
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'d_k': 4, 'd_v': 4, 'n_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@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_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
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf0)
del primals_4
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf1)
del primals_6
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf2)
del primals_8
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4, 16)](buf0, primals_5, buf3, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_5
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(4, 16)](buf1, primals_7, buf4, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_7
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(4, 16)](buf2, primals_9, buf8, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_9
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_11, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_11
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), primals_10, reinterpret_tensor(buf8, (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, 1), 0)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttentionNew(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, input_0, input_1, input_2):
primals_4 = self.q_projector.weight
primals_5 = self.q_projector.bias
primals_6 = self.k_projector.weight
primals_7 = self.k_projector.bias
primals_8 = self.v_projector.weight
primals_9 = self.v_projector.bias
primals_10 = self.o_projector.weight
primals_11 = self.o_projector.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
KohavTal/SCAE_Project
|
MultiHeadQKVAttention
| false
| 8,406
|
[
"Apache-2.0"
] | 40
|
bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
https://github.com/KohavTal/SCAE_Project/tree/bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
MAB
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4, 'n_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@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_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
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_5(in_ptr0, in_ptr1,
in_ptr2, 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 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp7 = 0.0
tmp8 = tmp5 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (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_3, (4, 4), (1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4, 16)](buf0, primals_4, buf3, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_4
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(4, 16)](buf1, primals_6, buf4, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(4, 16)](buf2, primals_8, buf8, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0)
del buf11
triton_poi_fused_add_4[grid(64)](buf12, primals_10, primals_1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_10
buf13 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf13)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_5[grid(64)](buf12,
buf13, primals_12, buf14, buf15, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf13
del primals_12
return buf14, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), reinterpret_tensor(buf12, (16, 4), (4, 1), 0
), buf15, primals_11, primals_9, reinterpret_tensor(buf8, (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, 1), 0)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MABNew(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, input_0, input_1):
primals_3 = self.mqkv.q_projector.weight
primals_4 = self.mqkv.q_projector.bias
primals_5 = self.mqkv.k_projector.weight
primals_6 = self.mqkv.k_projector.bias
primals_7 = self.mqkv.v_projector.weight
primals_8 = self.mqkv.v_projector.bias
primals_9 = self.mqkv.o_projector.weight
primals_10 = self.mqkv.o_projector.bias
primals_11 = self.fc.weight
primals_12 = self.fc.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, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
KohavTal/SCAE_Project
|
MAB
| false
| 8,407
|
[
"Apache-2.0"
] | 40
|
bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
https://github.com/KohavTal/SCAE_Project/tree/bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
ConditionalLayerNorm
|
import torch
from sklearn.metrics import *
from torch import nn
class ConditionalLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-06):
super(ConditionalLayerNorm, self).__init__()
self.eps = eps
self.gamma_dense = nn.Linear(hidden_size, hidden_size, bias=False)
self.beta_dense = nn.Linear(hidden_size, hidden_size, bias=False)
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
nn.init.zeros_(self.gamma_dense.weight)
nn.init.zeros_(self.beta_dense.weight)
def forward(self, x, condition):
"""
:param x: [b, t, e]
:param condition: [b, e]
:return:
"""
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
condition = condition.unsqueeze(1).expand_as(x)
gamma = self.gamma_dense(condition) + self.gamma
beta = self.beta_dense(condition) + self.beta
x = gamma * (x - mean) / (std + self.eps) + beta
return x
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from sklearn.metrics import *
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_1(in_out_ptr0, in_out_ptr1,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = 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_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_out_ptr1 + x2, xmask)
tmp33 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = 4.0
tmp12 = tmp10 / tmp11
tmp13 = tmp3 - tmp12
tmp14 = tmp2 * tmp13
tmp15 = tmp4 - tmp12
tmp16 = tmp15 * tmp15
tmp17 = tmp5 - tmp12
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp7 - tmp12
tmp21 = tmp20 * tmp20
tmp22 = tmp19 + tmp21
tmp23 = tmp9 - tmp12
tmp24 = tmp23 * tmp23
tmp25 = tmp22 + tmp24
tmp26 = 3.0
tmp27 = tmp25 / tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = 1e-06
tmp30 = tmp28 + tmp29
tmp31 = tmp14 / tmp30
tmp34 = tmp32 + tmp33
tmp35 = tmp31 + tmp34
tl.store(in_out_ptr1 + x2, tmp35, 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, 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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_2, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 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), (16, 4, 1), 0)
del buf1
buf4 = reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0)
del buf2
triton_poi_fused_add_div_mean_mul_std_sub_1[grid(64)](buf3, buf4,
primals_4, primals_1, primals_6, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf3
del primals_4
del primals_6
return buf4, primals_1, reinterpret_tensor(buf0, (16, 4), (4, 1), 0)
class ConditionalLayerNormNew(nn.Module):
def __init__(self, hidden_size, eps=1e-06):
super(ConditionalLayerNormNew, self).__init__()
self.eps = eps
self.gamma_dense = nn.Linear(hidden_size, hidden_size, bias=False)
self.beta_dense = nn.Linear(hidden_size, hidden_size, bias=False)
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
nn.init.zeros_(self.gamma_dense.weight)
nn.init.zeros_(self.beta_dense.weight)
def forward(self, input_0, input_1):
primals_4 = self.gamma
primals_6 = self.beta
primals_2 = self.gamma_dense.weight
primals_3 = self.beta_dense.weight
primals_1 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
JiaweiSheng/CasEE
|
ConditionalLayerNorm
| false
| 8,408
|
[
"MIT"
] | 44
|
af69432baf34d150f4721a4b4119002555758601
|
https://github.com/JiaweiSheng/CasEE/tree/af69432baf34d150f4721a4b4119002555758601
|
VisTransformerDecoderLayer
|
import torch
from torch import Tensor
from typing import Tuple
from typing import Optional
import torch.nn as nn
class VisTransformerDecoderLayer(nn.TransformerDecoderLayer):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu', layer_norm_eps=1e-05, batch_first=False, device=
None, dtype=None) ->None:
super(VisTransformerDecoderLayer, self).__init__(d_model, nhead,
dim_feedforward=dim_feedforward, dropout=dropout, activation=
activation, layer_norm_eps=layer_norm_eps, batch_first=
batch_first, device=device, dtype=dtype)
def forward(self, tgt: 'Tensor', memory: 'Tensor', tgt_mask:
'Optional[Tensor]'=None, memory_mask: 'Optional[Tensor]'=None,
tgt_key_padding_mask: 'Optional[Tensor]'=None,
memory_key_padding_mask: 'Optional[Tensor]'=None) ->Tuple[Tensor,
Tensor]:
"""Pass the inputs (and mask) through the decoder layer.
Args:
tgt: the sequence to the decoder layer (required).
memory: the sequence from the last layer of the encoder (required).
tgt_mask: the mask for the tgt sequence (optional).
memory_mask: the mask for the memory sequence (optional).
tgt_key_padding_mask: the mask for the tgt keys per batch (optional).
memory_key_padding_mask: the mask for the memory keys per batch (optional).
Shape:
see the docs in Transformer class.
"""
tgt2 = self.self_attn(tgt, tgt, tgt, attn_mask=tgt_mask,
key_padding_mask=tgt_key_padding_mask)[0]
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
tgt2, attn_output_weights = self.multihead_attn(tgt, memory, memory,
attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask)
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
tgt = tgt + self.dropout3(tgt2)
tgt = self.norm3(tgt)
return tgt, attn_output_weights
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'nhead': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_4(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = tmp27 / tmp15
tl.store(out_ptr0 + x0, tmp16, xmask)
tl.store(out_ptr1 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_5(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tmp6 = 1e-05
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp4 * tmp8
tmp11 = tmp9 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_mean_6(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_7(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_8(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_9(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_relu_10(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 2048
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (12, 4), (4, 1))
assert_size_stride(primals_3, (12,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (12, 4), (4, 1))
assert_size_stride(primals_10, (12,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4,), (1,))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (2048, 4), (4, 1))
assert_size_stride(primals_16, (2048,), (1,))
assert_size_stride(primals_17, (4, 2048), (2048, 1))
assert_size_stride(primals_18, (4,), (1,))
assert_size_stride(primals_19, (4,), (1,))
assert_size_stride(primals_20, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4),
(1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 4),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 16),
alpha=1, beta=1, out=buf1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_3, (4,), (1,), 8),
primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf2)
del primals_2
buf3 = reinterpret_tensor(buf0, (4, 4, 1), (1, 4, 16), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](buf3, primals_3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_3
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf1, (4, 1, 4), (1, 1,
4), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 1), (1, 4,
1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_5, reinterpret_tensor(buf8, (4, 4), (4,
1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf9)
del primals_5
buf10 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf11 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
triton_poi_fused_add_native_layer_norm_4[grid(4)](primals_1, buf9,
buf10, buf11, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_5[grid(16)](primals_1, buf9,
buf10, buf11, primals_6, primals_7, buf12, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_7
buf13 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf12, reinterpret_tensor(primals_9, (4, 4), (1,
4), 0), out=buf13)
buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_10, (4,), (1,), 4),
primals_8, reinterpret_tensor(primals_9, (4, 4), (1, 4), 16),
alpha=1, beta=1, out=buf14)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_10, (4,), (1,), 8),
primals_8, reinterpret_tensor(primals_9, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf15)
buf16 = reinterpret_tensor(buf13, (4, 4, 1), (1, 4, 16), 0)
del buf13
triton_poi_fused_mul_0[grid(16)](buf16, primals_10, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_10
buf17 = buf5
del buf5
extern_kernels.bmm(buf16, reinterpret_tensor(buf14, (4, 1, 4), (1,
1, 4), 0), out=buf17)
buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf17, buf18, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf19 = buf17
del buf17
triton_poi_fused__softmax_2[grid(64)](buf18, buf19, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf18
buf20 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf19, reinterpret_tensor(buf15, (4, 4, 1), (1,
4, 1), 0), out=buf20)
buf21 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf20, buf21, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf22 = reinterpret_tensor(buf20, (4, 4), (4, 1), 0)
del buf20
extern_kernels.mm(reinterpret_tensor(buf21, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf22)
buf23 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_mean_6[grid(16)](buf19, buf23, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf24 = buf22
del buf22
triton_poi_fused_add_7[grid(16)](buf24, buf12, primals_12, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_12
buf25 = buf11
del buf11
buf26 = buf10
del buf10
triton_poi_fused_native_layer_norm_8[grid(4)](buf24, buf25, buf26,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf27 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_9[grid(16)](buf24, buf25, buf26,
primals_13, primals_14, buf27, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_14
buf28 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32)
extern_kernels.mm(buf27, reinterpret_tensor(primals_15, (4, 2048),
(1, 4), 0), out=buf28)
buf29 = buf28
del buf28
triton_poi_fused_relu_10[grid(8192)](buf29, primals_16, 8192,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_16
buf30 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf29, reinterpret_tensor(primals_17, (2048, 4),
(1, 2048), 0), out=buf30)
buf31 = buf30
del buf30
triton_poi_fused_add_7[grid(16)](buf31, buf27, primals_18, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_18
buf32 = buf26
del buf26
buf33 = buf25
del buf25
triton_poi_fused_native_layer_norm_8[grid(4)](buf31, buf32, buf33,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf34 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_9[grid(16)](buf31, buf32, buf33,
primals_19, primals_20, buf34, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf32
del buf33
del primals_20
return (buf34, reinterpret_tensor(buf23, (4, 4), (4, 1), 0), primals_1,
primals_6, primals_13, primals_19, buf6, reinterpret_tensor(buf8, (
4, 4), (4, 1), 0), buf9, buf12, primals_8, buf19,
reinterpret_tensor(buf21, (4, 4), (4, 1), 0), buf24, buf27, buf29,
buf31, primals_17, primals_15, primals_11, reinterpret_tensor(buf15,
(4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf16, (4, 1, 4), (1,
1, 4), 0), reinterpret_tensor(buf14, (4, 4, 1), (1, 4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (4, 1), 0), primals_4,
reinterpret_tensor(buf2, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf3, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf1, (4, 4, 1), (1, 4, 1), 0))
class VisTransformerDecoderLayerNew(nn.TransformerDecoderLayer):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu', layer_norm_eps=1e-05, batch_first=False, device=
None, dtype=None) ->None:
super(VisTransformerDecoderLayerNew, self).__init__(d_model, nhead,
dim_feedforward=dim_feedforward, dropout=dropout, activation=
activation, layer_norm_eps=layer_norm_eps, batch_first=
batch_first, device=device, dtype=dtype)
def forward(self, input_0, input_1):
primals_2 = self.self_attn.in_proj_weight
primals_3 = self.self_attn.in_proj_bias
primals_1 = self.self_attn.out_proj.weight
primals_5 = self.self_attn.out_proj.bias
primals_9 = self.multihead_attn.in_proj_weight
primals_10 = self.multihead_attn.in_proj_bias
primals_4 = self.multihead_attn.out_proj.weight
primals_6 = self.multihead_attn.out_proj.bias
primals_15 = self.linear1.weight
primals_16 = self.linear1.bias
primals_17 = self.linear2.weight
primals_7 = self.linear2.bias
primals_12 = self.norm1.weight
primals_13 = self.norm1.bias
primals_14 = self.norm2.weight
primals_18 = self.norm2.bias
primals_19 = self.norm3.weight
primals_20 = self.norm3.bias
primals_8 = input_0
primals_11 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20])
return output[0], output[1]
|
Kamino666/Video-Captioning-Transformer
|
VisTransformerDecoderLayer
| false
| 8,409
|
[
"Apache-2.0"
] | 14
|
06e6c95d9bf11d61f5825be3c640e489521f9934
|
https://github.com/Kamino666/Video-Captioning-Transformer/tree/06e6c95d9bf11d61f5825be3c640e489521f9934
|
SAB
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class SAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.mab = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
def forward(self, x, presence=None):
return self.mab(x, x, presence)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4, 'n_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@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_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
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_5(in_ptr0, in_ptr1,
in_ptr2, 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 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp7 = 0.0
tmp8 = tmp5 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = 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,))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (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(4, 16)](buf0, primals_3, buf3, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(4, 16)](buf1, primals_5, buf4, 4, 16,
XBLOCK=8, YBLOCK=4, 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 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(4, 16)](buf2, primals_7, buf8, 4, 16,
XBLOCK=8, YBLOCK=4, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0)
del buf11
triton_poi_fused_add_4[grid(64)](buf12, primals_9, primals_1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf13 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf13)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_5[grid(64)](buf12,
buf13, primals_11, buf14, buf15, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf13
del primals_11
return buf14, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), reinterpret_tensor(buf12, (16, 4), (4, 1), 0
), buf15, primals_10, primals_8, reinterpret_tensor(buf8, (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, 1), 0)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class SABNew(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.mab = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
def forward(self, input_0):
primals_2 = self.mab.mqkv.q_projector.weight
primals_3 = self.mab.mqkv.q_projector.bias
primals_4 = self.mab.mqkv.k_projector.weight
primals_5 = self.mab.mqkv.k_projector.bias
primals_6 = self.mab.mqkv.v_projector.weight
primals_7 = self.mab.mqkv.v_projector.bias
primals_8 = self.mab.mqkv.o_projector.weight
primals_9 = self.mab.mqkv.o_projector.bias
primals_10 = self.mab.fc.weight
primals_11 = self.mab.fc.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]
|
KohavTal/SCAE_Project
|
SAB
| false
| 8,410
|
[
"Apache-2.0"
] | 40
|
bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
https://github.com/KohavTal/SCAE_Project/tree/bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
AvgPoolShortCut
|
import torch
from torch import nn
from torch.nn import functional as F
class AvgPoolShortCut(nn.Module):
def __init__(self, stride, out_c, in_c):
super(AvgPoolShortCut, self).__init__()
self.stride = stride
self.out_c = out_c
self.in_c = in_c
def forward(self, x):
if x.shape[2] % 2 != 0:
x = F.avg_pool2d(x, 1, self.stride)
else:
x = F.avg_pool2d(x, self.stride, self.stride)
pad = torch.zeros(x.shape[0], self.out_c - self.in_c, x.shape[2], x
.shape[3], device=x.device)
x = torch.cat((x, pad), dim=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'stride': 1, 'out_c': 4, 'in_c': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_avg_pool2d_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
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_avg_pool2d_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class AvgPoolShortCutNew(nn.Module):
def __init__(self, stride, out_c, in_c):
super(AvgPoolShortCutNew, self).__init__()
self.stride = stride
self.out_c = out_c
self.in_c = in_c
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Karthik-Ragunath/DDU
|
AvgPoolShortCut
| false
| 8,411
|
[
"MIT"
] | 43
|
b9daae9304bdeb222857884ef8cb3b6b3d004d33
|
https://github.com/Karthik-Ragunath/DDU/tree/b9daae9304bdeb222857884ef8cb3b6b3d004d33
|
CNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CNet(nn.Module):
def __init__(self, s_dim, a_dim):
super(CNet, self).__init__()
self.fcs = nn.Linear(s_dim, 30)
self.fcs.weight.data.normal_(0, 0.1)
self.fca = nn.Linear(a_dim, 30)
self.fca.weight.data.normal_(0, 0.1)
self.out = nn.Linear(30, 1)
self.out.weight.data.normal_(0, 0.1)
def forward(self, s, a):
x = self.fcs(s)
y = self.fca(a)
net = F.relu(x + y)
actions_value = self.out(net)
return actions_value
class net(nn.Module):
def __init__(self, input_dim, output_dim):
super(net, self).__init__()
self.fc1 = nn.Linear(input_dim, 30)
self.fc1.weight.data.normal_(0, 1)
self.fc2 = nn.Linear(30, 20)
self.fc2.weight.data.normal_(0, 1)
self.fc3 = nn.Linear(20, output_dim)
self.fc3.weight.data.normal_(0, 1)
def forward(self, x):
x = F.tanh(self.fc1(x))
x = F.tanh(self.fc2(x))
out = self.fc3(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'s_dim': 4, 'a_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_add_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1920
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 30
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.full([1], 0, tl.int32)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp9 = 0.0
tmp10 = tmp8 <= tmp9
tl.store(in_out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr0 + x2, tmp10, 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, (30, 4), (4, 1))
assert_size_stride(primals_2, (30,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (30, 4), (4, 1))
assert_size_stride(primals_5, (30,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (1, 30), (30, 1))
assert_size_stride(primals_8, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 30), (30, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 30), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 30), (30, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 30), (1, 4), 0), out=buf1)
del primals_4
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 30), (480, 120, 30, 1), 0)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 30), (480, 120, 30, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_relu_threshold_backward_0[grid(1920)](buf2,
primals_2, buf1, primals_5, buf5, 1920, XBLOCK=128, num_warps=4,
num_stages=1)
del buf1
del primals_2
del primals_5
buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(buf2, (64, 30),
(30, 1), 0), reinterpret_tensor(primals_7, (30, 1), (1, 30), 0),
alpha=1, beta=1, out=buf4)
del primals_8
return reinterpret_tensor(buf4, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (64, 30), (30, 1), 0), primals_7, buf5
class CNetNew(nn.Module):
def __init__(self, s_dim, a_dim):
super(CNetNew, self).__init__()
self.fcs = nn.Linear(s_dim, 30)
self.fcs.weight.data.normal_(0, 0.1)
self.fca = nn.Linear(a_dim, 30)
self.fca.weight.data.normal_(0, 0.1)
self.out = nn.Linear(30, 1)
self.out.weight.data.normal_(0, 0.1)
def forward(self, input_0, input_1):
primals_1 = self.fcs.weight
primals_2 = self.fcs.bias
primals_4 = self.fca.weight
primals_5 = self.fca.bias
primals_7 = self.out.weight
primals_8 = self.out.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]
class net(nn.Module):
def __init__(self, input_dim, output_dim):
super(net, self).__init__()
self.fc1 = nn.Linear(input_dim, 30)
self.fc1.weight.data.normal_(0, 1)
self.fc2 = nn.Linear(30, 20)
self.fc2.weight.data.normal_(0, 1)
self.fc3 = nn.Linear(20, output_dim)
self.fc3.weight.data.normal_(0, 1)
def forward(self, x):
x = F.tanh(self.fc1(x))
x = F.tanh(self.fc2(x))
out = self.fc3(x)
return out
|
Kernels-K/DDPG-pytorch-
|
CNet
| false
| 8,412
|
[
"MIT"
] | 26
|
9a80a56f52f2232e5bd197521d3d2d388b48c882
|
https://github.com/Kernels-K/DDPG-pytorch-/tree/9a80a56f52f2232e5bd197521d3d2d388b48c882
|
HSwish
|
import torch
import torch.nn as nn
import torch.nn
class HSwish(nn.Module):
"""
H-Swish activation function from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
inplace : bool
Whether to use inplace version of the module.
"""
def __init__(self, inplace=True):
super(HSwish, self).__init__()
self.inplace = inplace
self.relu = nn.ReLU6(inplace=self.inplace)
def forward(self, x):
return x * self.relu(x + 3.0) / 6.0
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
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_div_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 3.0
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = 6.0
tmp6 = triton_helpers.minimum(tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp8 = 0.16666666666666666
tmp9 = tmp7 * tmp8
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_hardtanh_mul_0[grid(256)](arg0_1, buf0,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class HSwishNew(nn.Module):
"""
H-Swish activation function from 'Searching for MobileNetV3,' https://arxiv.org/abs/1905.02244.
Parameters:
----------
inplace : bool
Whether to use inplace version of the module.
"""
def __init__(self, inplace=True):
super(HSwishNew, self).__init__()
self.inplace = inplace
self.relu = nn.ReLU6(inplace=self.inplace)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Kthyeon/micronet_neurips_challenge
|
HSwish
| false
| 8,413
|
[
"MIT"
] | 19
|
9f71fb752e8fbd5abca07be530f7fb19e164125c
|
https://github.com/Kthyeon/micronet_neurips_challenge/tree/9f71fb752e8fbd5abca07be530f7fb19e164125c
|
SAMblock
|
import torch
class SAMblock(torch.nn.Module):
def __init__(self, size=7, model='full', outplanes=None):
super(SAMblock, self).__init__()
self.outplanes = outplanes
if self.outplanes is None:
self.outplanes = 1
self.model = model
self.conv1 = torch.nn.Conv2d(2, self.outplanes, (size, size),
stride=1, padding=size // 2)
if self.model != 'full':
self.conv1 = torch.nn.Conv2d(1, self.outplanes, (size, size),
stride=1, padding=size // 2)
self.sigmod = torch.nn.Sigmoid()
def forward(self, x):
if self.model == 'mean':
meanpool = torch.mean(x, 1, True)
sp = meanpool
if self.model == 'max':
maxpool, _ = torch.max(x, 1, True)
sp = maxpool
if self.model == 'full':
maxpool, _ = torch.max(x, 1, True)
meanpool = torch.mean(x, 1, True)
sp = torch.cat([maxpool, meanpool], dim=1)
sp = self.conv1(sp)
sp = self.sigmod(sp)
x = sp * x
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 2
x0 = xindex % 16
x2 = xindex // 32
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 2, tl.int64)
tmp17 = tl.load(in_ptr0 + (x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp18 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp19 = tmp17 + tmp18
tmp20 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = tmp19 + tmp20
tmp22 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), tmp14 & xmask,
eviction_policy='evict_last', other=0.0)
tmp23 = tmp21 + tmp22
tmp24 = 4.0
tmp25 = tmp23 / tmp24
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp14, tmp25, tmp26)
tmp28 = tl.where(tmp4, tmp13, tmp27)
tl.store(out_ptr0 + x3, tmp28, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr1 + x3, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x3, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 2, 7, 7), (98, 49, 7, 1))
assert_size_stride(primals_3, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 4, 4), (32, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(128)](primals_1, buf0, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(3, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 1, 4, 4), (16, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_2[grid(256)](buf2, primals_1, buf3,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf3, primals_1, primals_2, buf0, buf2
class SAMblockNew(torch.nn.Module):
def __init__(self, size=7, model='full', outplanes=None):
super(SAMblockNew, self).__init__()
self.outplanes = outplanes
if self.outplanes is None:
self.outplanes = 1
self.model = model
self.conv1 = torch.nn.Conv2d(2, self.outplanes, (size, size),
stride=1, padding=size // 2)
if self.model != 'full':
self.conv1 = torch.nn.Conv2d(1, self.outplanes, (size, size),
stride=1, padding=size // 2)
self.sigmod = torch.nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Knight825/models-pytorch
|
SAMblock
| false
| 8,414
|
[
"Apache-2.0"
] | 16
|
133559eebb8795d78a32fa44d49408d0c5167ae9
|
https://github.com/Knight825/models-pytorch/tree/133559eebb8795d78a32fa44d49408d0c5167ae9
|
CrossAttention
|
import torch
import torch.nn as nn
class CrossAttention(nn.Module):
def __init__(self, in_channel=256, ratio=8):
super(CrossAttention, self).__init__()
self.conv_query = nn.Conv2d(in_channel, in_channel // ratio,
kernel_size=1)
self.conv_key = nn.Conv2d(in_channel, in_channel // ratio,
kernel_size=1)
self.conv_value = nn.Conv2d(in_channel, in_channel, kernel_size=1)
def forward(self, rgb, depth):
bz, c, h, w = rgb.shape
depth_q = self.conv_query(depth).view(bz, -1, h * w).permute(0, 2, 1)
depth_k = self.conv_key(depth).view(bz, -1, h * w)
mask = torch.bmm(depth_q, depth_k)
mask = torch.softmax(mask, dim=-1)
rgb_v = self.conv_value(rgb).view(bz, c, -1)
feat = torch.bmm(rgb_v, mask.permute(0, 2, 1))
feat = feat.view(bz, c, h, w)
return feat
def get_inputs():
return [torch.rand([4, 256, 64, 64]), torch.rand([4, 256, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 256 * x2 + 1048576 * y1), tmp0, None)
@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 128
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y0 = yindex % 32
y1 = yindex // 32
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 32 * x2 + 131072 * y1), ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, ymask)
@triton.jit
def triton_red_fused__softmax_2(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr, RBLOCK: tl.constexpr):
rnumel = 4096
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
_tmp2 = tl.full([XBLOCK, RBLOCK], float('-inf'), tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask, eviction_policy=
'evict_last', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = triton_helpers.maximum(_tmp2, tmp1)
_tmp2 = tl.where(rmask, tmp3, _tmp2)
tmp2 = triton_helpers.max2(_tmp2, 1)[:, None]
_tmp8 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp4 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask, eviction_policy=
'evict_last', other=0.0)
tmp5 = tmp4 - tmp2
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = _tmp8 + tmp7
_tmp8 = tl.where(rmask, tmp9, _tmp8)
tmp8 = tl.sum(_tmp8, 1)[:, None]
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp10 = tl.load(in_ptr0 + (r1 + 4096 * x0), rmask, eviction_policy=
'evict_first', other=0.0)
tmp11 = tmp10 - tmp2
tmp12 = tl_math.exp(tmp11)
tmp13 = tmp12 / tmp8
tl.store(out_ptr2 + (r1 + 4096 * x0), tmp13, rmask)
@triton.jit
def triton_poi_fused_convolution_3(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y0 = yindex % 256
y1 = yindex // 256
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 1048576 * y1), None,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4096 * y3), tmp2, 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, 256, 64, 64), (1048576, 4096, 64, 1))
assert_size_stride(primals_2, (32, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_3, (32,), (1,))
assert_size_stride(primals_4, (4, 256, 64, 64), (1048576, 4096, 64, 1))
assert_size_stride(primals_5, (32, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_6, (32,), (1,))
assert_size_stride(primals_7, (256, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_8, (256,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 256, 64, 64), (1048576, 1, 16384, 256
), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(1024, 4096)](primals_1, buf0, 1024, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 256, 64, 64), (1048576, 1, 16384, 256
), torch.float32)
triton_poi_fused_0[grid(1024, 4096)](primals_4, buf1, 1024, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_4
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, 32, 64, 64), (131072, 1, 2048, 32))
buf3 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_1[grid(128, 4096)](buf2, primals_3,
buf3, 128, 4096, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1)
del primals_3
buf4 = 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(buf4, (4, 32, 64, 64), (131072, 1, 2048, 32))
buf5 = reinterpret_tensor(buf2, (4, 32, 64, 64), (131072, 4096, 64,
1), 0)
del buf2
triton_poi_fused_convolution_1[grid(128, 4096)](buf4, primals_6,
buf5, 128, 4096, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1)
del buf4
del primals_6
buf6 = empty_strided_cuda((4, 4096, 4096), (16777216, 4096, 1),
torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (4, 4096, 32), (131072,
1, 4096), 0), reinterpret_tensor(buf5, (4, 32, 4096), (131072,
4096, 1), 0), out=buf6)
buf9 = empty_strided_cuda((4, 4096, 4096), (16777216, 4096, 1),
torch.float32)
triton_red_fused__softmax_2[grid(16384)](buf6, buf9, 16384, 4096,
XBLOCK=1, RBLOCK=2048, num_warps=16, num_stages=1)
del buf6
buf10 = extern_kernels.convolution(buf0, primals_7, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 256, 64, 64), (1048576, 1, 16384, 256))
buf11 = empty_strided_cuda((4, 256, 64, 64), (1048576, 4096, 64, 1),
torch.float32)
triton_poi_fused_convolution_3[grid(1024, 4096)](buf10, primals_8,
buf11, 1024, 4096, XBLOCK=16, YBLOCK=256, num_warps=8, num_stages=1
)
del primals_8
buf12 = reinterpret_tensor(buf10, (4, 256, 4096), (1048576, 4096, 1), 0
)
del buf10
extern_kernels.bmm(reinterpret_tensor(buf11, (4, 256, 4096), (
1048576, 4096, 1), 0), reinterpret_tensor(buf9, (4, 4096, 4096),
(16777216, 1, 4096), 0), out=buf12)
return reinterpret_tensor(buf12, (4, 256, 64, 64), (1048576, 4096, 64,
1), 0
), buf0, primals_2, buf1, primals_5, primals_7, buf9, reinterpret_tensor(
buf11, (4, 4096, 256), (1048576, 1, 4096), 0), reinterpret_tensor(buf3,
(4, 32, 4096), (131072, 4096, 1), 0), reinterpret_tensor(buf5, (4,
4096, 32), (131072, 1, 4096), 0)
class CrossAttentionNew(nn.Module):
def __init__(self, in_channel=256, ratio=8):
super(CrossAttentionNew, self).__init__()
self.conv_query = nn.Conv2d(in_channel, in_channel // ratio,
kernel_size=1)
self.conv_key = nn.Conv2d(in_channel, in_channel // ratio,
kernel_size=1)
self.conv_value = nn.Conv2d(in_channel, in_channel, kernel_size=1)
def forward(self, input_0, input_1):
primals_2 = self.conv_query.weight
primals_3 = self.conv_query.bias
primals_5 = self.conv_key.weight
primals_6 = self.conv_key.bias
primals_7 = self.conv_value.weight
primals_8 = self.conv_value.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
JosephChenHub/DPANet
|
CrossAttention
| false
| 8,415
|
[
"MIT"
] | 19
|
68cf40a405d8c8c6506884079cd0a206d6d58e63
|
https://github.com/JosephChenHub/DPANet/tree/68cf40a405d8c8c6506884079cd0a206d6d58e63
|
ISAB
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class ISAB(nn.Module):
def __init__(self, d, n_heads, n_inducing_points, layer_norm=False):
super().__init__()
self.mab0 = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
self.mab1 = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
self.I = nn.Parameter(torch.zeros(1, n_inducing_points, d),
requires_grad=True)
with torch.no_grad():
nn.init.xavier_uniform_(self.I)
def forward(self, x, presence=None):
batch_size = x.shape[0]
h = self.mab0(self.I.repeat(batch_size, 1, 1), x, presence)
return self.mab1(x, h)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4, 'n_heads': 4, 'n_inducing_points': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_repeat_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
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_5(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_6(in_ptr0, in_ptr1,
in_ptr2, 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 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp7 = 0.0
tmp8 = tmp5 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 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,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (4, 4), (4, 1))
assert_size_stride(primals_16, (4,), (1,))
assert_size_stride(primals_17, (4, 4), (4, 1))
assert_size_stride(primals_18, (4,), (1,))
assert_size_stride(primals_19, (4, 4), (4, 1))
assert_size_stride(primals_20, (4,), (1,))
assert_size_stride(primals_21, (4, 4), (4, 1))
assert_size_stride(primals_22, (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_repeat_0[grid(64)](primals_2, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
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_5, (4, 4), (1, 4), 0), out=buf2)
del primals_5
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf3)
del primals_7
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_1[grid(4, 16)](buf1, primals_4, buf4, 4, 16,
XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_4
buf5 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_1[grid(4, 16)](buf2, primals_6, buf5, 4, 16,
XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_6
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf5, (16, 1, 4), (4, 0, 1), 0), out=buf6)
buf7 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf8 = buf6
del buf6
triton_poi_fused__softmax_3[grid(256)](buf7, buf8, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf9 = reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf2
triton_poi_fused_clone_1[grid(4, 16)](buf3, primals_8, buf9, 4, 16,
XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_8
buf10 = reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 1), 0)
del buf3
extern_kernels.bmm(buf8, reinterpret_tensor(buf9, (16, 4, 1), (4, 1,
0), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf11, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf12)
buf13 = reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0)
del buf12
triton_poi_fused_add_5[grid(64)](buf13, primals_10, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_10
buf14 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf13, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf14)
buf15 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), out=buf15)
del primals_13
buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf32 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_6[grid(64)](buf13,
buf14, primals_12, buf16, buf32, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_12
buf17 = buf14
del buf14
extern_kernels.mm(reinterpret_tensor(buf16, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_15, (4, 4), (1, 4), 0), out=buf17)
buf18 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf16, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_17, (4, 4), (1, 4), 0), out=buf18)
buf19 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_1[grid(4, 16)](buf15, primals_14, buf19, 4,
16, XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_14
buf20 = reinterpret_tensor(buf15, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf15
triton_poi_fused_clone_1[grid(4, 16)](buf17, primals_16, buf20, 4,
16, XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_16
buf21 = buf7
del buf7
extern_kernels.bmm(reinterpret_tensor(buf19, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf20, (16, 1, 4), (4, 0, 1), 0), out=buf21)
buf22 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(256)](buf21, buf22, 256, XBLOCK=
128, num_warps=4, num_stages=1)
buf23 = buf21
del buf21
triton_poi_fused__softmax_3[grid(256)](buf22, buf23, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf22
buf24 = reinterpret_tensor(buf17, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf17
triton_poi_fused_clone_1[grid(4, 16)](buf18, primals_18, buf24, 4,
16, XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_18
buf25 = reinterpret_tensor(buf18, (16, 4, 1), (4, 1, 1), 0)
del buf18
extern_kernels.bmm(buf23, reinterpret_tensor(buf24, (16, 4, 1), (4,
1, 0), 0), out=buf25)
buf26 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf25, buf26, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf27 = reinterpret_tensor(buf25, (16, 4), (4, 1), 0)
del buf25
extern_kernels.mm(reinterpret_tensor(buf26, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_19, (4, 4), (1, 4), 0), out=buf27)
buf28 = reinterpret_tensor(buf27, (4, 4, 4), (16, 4, 1), 0)
del buf27
triton_poi_fused_add_5[grid(64)](buf28, primals_20, primals_1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_20
buf29 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf28, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_21, (4, 4), (1, 4), 0), out=buf29)
buf30 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf31 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_6[grid(64)](buf28,
buf29, primals_22, buf30, buf31, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf29
del primals_22
return (buf30, reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), buf8,
reinterpret_tensor(buf11, (16, 4), (4, 1), 0), reinterpret_tensor(
buf13, (16, 4), (4, 1), 0), reinterpret_tensor(buf16, (16, 4), (4,
1), 0), buf23, reinterpret_tensor(buf26, (16, 4), (4, 1), 0),
reinterpret_tensor(buf28, (16, 4), (4, 1), 0), buf31, primals_21,
primals_19, reinterpret_tensor(buf24, (16, 1, 4), (4, 1, 1), 0),
reinterpret_tensor(buf19, (16, 1, 4), (4, 1, 1), 0),
reinterpret_tensor(buf20, (16, 4, 1), (4, 1, 1), 0), primals_17,
primals_15, buf32, primals_11, primals_9, reinterpret_tensor(buf9,
(16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf4, (16, 1, 4), (4,
1, 1), 0), reinterpret_tensor(buf5, (16, 4, 1), (4, 1, 1), 0),
primals_3)
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class ISABNew(nn.Module):
def __init__(self, d, n_heads, n_inducing_points, layer_norm=False):
super().__init__()
self.mab0 = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
self.mab1 = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
self.I = nn.Parameter(torch.zeros(1, n_inducing_points, d),
requires_grad=True)
with torch.no_grad():
nn.init.xavier_uniform_(self.I)
def forward(self, input_0):
primals_2 = self.I
primals_3 = self.mab0.mqkv.q_projector.weight
primals_4 = self.mab0.mqkv.q_projector.bias
primals_5 = self.mab0.mqkv.k_projector.weight
primals_6 = self.mab0.mqkv.k_projector.bias
primals_7 = self.mab0.mqkv.v_projector.weight
primals_8 = self.mab0.mqkv.v_projector.bias
primals_9 = self.mab0.mqkv.o_projector.weight
primals_10 = self.mab0.mqkv.o_projector.bias
primals_11 = self.mab0.fc.weight
primals_12 = self.mab0.fc.bias
primals_13 = self.mab1.mqkv.q_projector.weight
primals_14 = self.mab1.mqkv.q_projector.bias
primals_15 = self.mab1.mqkv.k_projector.weight
primals_16 = self.mab1.mqkv.k_projector.bias
primals_17 = self.mab1.mqkv.v_projector.weight
primals_18 = self.mab1.mqkv.v_projector.bias
primals_19 = self.mab1.mqkv.o_projector.weight
primals_20 = self.mab1.mqkv.o_projector.bias
primals_21 = self.mab1.fc.weight
primals_22 = self.mab1.fc.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22])
return output[0]
|
KohavTal/SCAE_Project
|
ISAB
| false
| 8,416
|
[
"Apache-2.0"
] | 40
|
bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
https://github.com/KohavTal/SCAE_Project/tree/bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
PositionWiseFeedForwardNetworks
|
import torch
from torch import nn
from torch.nn import functional as F
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.0)
return m
class PositionWiseFeedForwardNetworks(nn.Module):
def __init__(self, input_size, output_size, d_ff):
super().__init__()
self.W_1 = Linear(input_size, d_ff, bias=True)
self.W_2 = Linear(d_ff, output_size, bias=True)
nn.init.constant_(self.W_1.bias, 0.0)
nn.init.constant_(self.W_2.bias, 0.0)
def forward(self, input):
outputs = F.relu(self.W_1(input), inplace=True)
return self.W_2(outputs)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4, 'd_ff': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf4 = 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, buf4, 256, XBLOCK=256, 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.addmm(primals_5, buf2, reinterpret_tensor(primals_4,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2, primals_4, buf4
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.0)
return m
class PositionWiseFeedForwardNetworksNew(nn.Module):
def __init__(self, input_size, output_size, d_ff):
super().__init__()
self.W_1 = Linear(input_size, d_ff, bias=True)
self.W_2 = Linear(d_ff, output_size, bias=True)
nn.init.constant_(self.W_1.bias, 0.0)
nn.init.constant_(self.W_2.bias, 0.0)
def forward(self, input_0):
primals_1 = self.W_1.weight
primals_2 = self.W_1.bias
primals_4 = self.W_2.weight
primals_5 = self.W_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
L-Zhe/FasySeq
|
PositionWiseFeedForwardNetworks
| false
| 8,417
|
[
"Apache-2.0"
] | 34
|
2cd2abd290666b1e118d8ad11c973b58ca4f0573
|
https://github.com/L-Zhe/FasySeq/tree/2cd2abd290666b1e118d8ad11c973b58ca4f0573
|
SEBlock
|
import torch
class SEBlock(torch.nn.Module):
def __init__(self, inplanes, redr, poolflag='avg'):
super(SEBlock, self).__init__()
if poolflag == 'max':
self.pool = torch.nn.AdaptiveMaxPool2d((1, 1))
if poolflag == 'avg':
self.pool = torch.nn.AdaptiveAvgPool2d((1, 1))
self.replanes = inplanes // redr
self.linear1 = torch.nn.Conv2d(inplanes, self.replanes, (1, 1),
padding=0)
self.relu = torch.nn.ReLU(inplace=True)
self.linear2 = torch.nn.Conv2d(self.replanes, inplanes, (1, 1),
padding=0)
self.sigmod = torch.nn.Sigmoid()
def forward(self, x):
se = self.pool(x)
se = self.linear1(se)
se = self.relu(se)
se = self.linear2(se)
se = self.sigmod(se)
x = se * x
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'redr': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tl.store(in_out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (4, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=8,
num_warps=2, num_stages=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, 1, 1, 1), (1, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(4)](buf3, primals_3, 4,
XBLOCK=4, num_warps=1, num_stages=1)
del primals_3
buf4 = extern_kernels.convolution(buf3, 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, 4, 1, 1), (4, 1, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(16)](buf5, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_3[grid(256)](buf5, primals_1, buf6,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf6, primals_1, primals_2, primals_4, buf1, buf3, buf5
class SEBlockNew(torch.nn.Module):
def __init__(self, inplanes, redr, poolflag='avg'):
super(SEBlockNew, self).__init__()
if poolflag == 'max':
self.pool = torch.nn.AdaptiveMaxPool2d((1, 1))
if poolflag == 'avg':
self.pool = torch.nn.AdaptiveAvgPool2d((1, 1))
self.replanes = inplanes // redr
self.linear1 = torch.nn.Conv2d(inplanes, self.replanes, (1, 1),
padding=0)
self.relu = torch.nn.ReLU(inplace=True)
self.linear2 = torch.nn.Conv2d(self.replanes, inplanes, (1, 1),
padding=0)
self.sigmod = torch.nn.Sigmoid()
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_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Knight825/models-pytorch
|
SEBlock
| false
| 8,418
|
[
"Apache-2.0"
] | 16
|
133559eebb8795d78a32fa44d49408d0c5167ae9
|
https://github.com/Knight825/models-pytorch/tree/133559eebb8795d78a32fa44d49408d0c5167ae9
|
FourierEmbedding
|
import torch
from torch import nn
class FourierEmbedding(nn.Module):
def __init__(self, features, height, width, **kwargs):
super().__init__(**kwargs)
self.projector = nn.Linear(2, features)
self._height = height
self._width = width
def forward(self, y, x):
x_norm = 2 * x / (self._width - 1) - 1
y_norm = 2 * y / (self._height - 1) - 1
z = torch.cat((x_norm.unsqueeze(2), y_norm.unsqueeze(2)), dim=2)
return torch.sin(self.projector(z))
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'features': 4, 'height': 4, 'width': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_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 % 2
x1 = xindex // 2
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + x1, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp6 = 2.0
tmp7 = tmp5 * tmp6
tmp8 = 0.3333333333333333
tmp9 = tmp7 * tmp8
tmp10 = 1.0
tmp11 = tmp9 - tmp10
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 2, tl.int64)
tmp17 = tl.load(in_ptr1 + x1, tmp14 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp18 = tmp17 * tmp6
tmp19 = tmp18 * tmp8
tmp20 = tmp19 - tmp10
tmp21 = tl.full(tmp20.shape, 0.0, tmp20.dtype)
tmp22 = tl.where(tmp14, tmp20, tmp21)
tmp23 = tl.where(tmp4, tmp13, tmp22)
tl.store(out_ptr0 + x2, tmp23, xmask)
@triton.jit
def triton_poi_fused_sin_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 = tl_math.sin(tmp0)
tl.store(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, 4), (4, 1))
assert_size_stride(primals_3, (4, 2), (2, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 2), (8, 2, 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((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_4, reinterpret_tensor(buf0, (16, 2), (
2, 1), 0), reinterpret_tensor(primals_3, (2, 4), (1, 2), 0),
alpha=1, beta=1, out=buf1)
del primals_3
del primals_4
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_sin_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf2, reinterpret_tensor(buf0, (16, 2), (2, 1), 0), buf1
class FourierEmbeddingNew(nn.Module):
def __init__(self, features, height, width, **kwargs):
super().__init__(**kwargs)
self.projector = nn.Linear(2, features)
self._height = height
self._width = width
def forward(self, input_0, input_1):
primals_3 = self.projector.weight
primals_4 = self.projector.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
LS4GAN/uvcgan
|
FourierEmbedding
| false
| 8,419
|
[
"BSD-2-Clause"
] | 20
|
376439ae2a9be684ff279ddf634fe137aadc5df5
|
https://github.com/LS4GAN/uvcgan/tree/376439ae2a9be684ff279ddf634fe137aadc5df5
|
Critic
|
import torch
import torch.nn as nn
class Critic(nn.Module):
def __init__(self, state_dim, hidden_dim=64):
super(Critic, self).__init__()
self.l1 = nn.Linear(state_dim, hidden_dim)
self.l2 = nn.Linear(hidden_dim, hidden_dim)
self.l3 = nn.Linear(hidden_dim, 1)
def forward(self, state):
z = torch.tanh(self.l1(state))
z = torch.tanh(self.l2(z))
v = self.l3(z)
return v
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
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 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 64), (64, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (1, 64), (64, 1))
assert_size_stride(primals_7, (1,), (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
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(4096)](buf1, primals_2, 4096, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(4096)](buf3, primals_5, 4096, 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, 64),
(64, 1), 0), reinterpret_tensor(primals_6, (64, 1), (1, 64), 0),
alpha=1, beta=1, out=buf5)
del primals_7
return reinterpret_tensor(buf5, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf3, primals_6, primals_4
class CriticNew(nn.Module):
def __init__(self, state_dim, hidden_dim=64):
super(CriticNew, self).__init__()
self.l1 = nn.Linear(state_dim, hidden_dim)
self.l2 = nn.Linear(hidden_dim, hidden_dim)
self.l3 = nn.Linear(hidden_dim, 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]
|
LQNew/LWDRL
|
Critic
| false
| 8,420
|
[
"MIT"
] | 11
|
0e4fab077a0cfbd27590b840557f4fda033c74ff
|
https://github.com/LQNew/LWDRL/tree/0e4fab077a0cfbd27590b840557f4fda033c74ff
|
PMA
|
import math
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class PMA(nn.Module):
def __init__(self, d, n_heads, n_seeds, layer_norm=False):
super().__init__()
self.mab = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
self.S = nn.Parameter(torch.zeros(1, n_seeds, d), requires_grad=True)
with torch.no_grad():
nn.init.xavier_uniform_(self.S)
def forward(self, x, presence=None):
batch_size = x.shape[0]
return self.mab(self.S.repeat(batch_size, 1, 1), x, presence)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'d': 4, 'n_heads': 4, 'n_seeds': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_repeat_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
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x1 + 16 * y0), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x1), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_5(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_6(in_ptr0, in_ptr1,
in_ptr2, 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 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp0 + tmp5
tmp7 = 0.0
tmp8 = tmp5 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 4), (4, 1))
assert_size_stride(primals_12, (4,), (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_repeat_0[grid(64)](primals_2, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
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_5, (4, 4), (1, 4), 0), out=buf2)
del primals_5
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf3)
del primals_7
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_1[grid(4, 16)](buf1, primals_4, buf4, 4, 16,
XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_4
buf5 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_1[grid(4, 16)](buf2, primals_6, buf5, 4, 16,
XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_6
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf5, (16, 1, 4), (4, 0, 1), 0), out=buf6)
buf7 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf8 = buf6
del buf6
triton_poi_fused__softmax_3[grid(256)](buf7, buf8, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf7
buf9 = reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf2
triton_poi_fused_clone_1[grid(4, 16)](buf3, primals_8, buf9, 4, 16,
XBLOCK=16, YBLOCK=4, num_warps=1, num_stages=1)
del primals_8
buf10 = reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 1), 0)
del buf3
extern_kernels.bmm(buf8, reinterpret_tensor(buf9, (16, 4, 1), (4, 1,
0), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf11, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf12)
buf13 = reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0)
del buf12
triton_poi_fused_add_5[grid(64)](buf13, primals_10, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_10
buf14 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf13, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_11, (4, 4), (1, 4), 0), out=buf14)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_6[grid(64)](buf13,
buf14, primals_12, buf15, buf16, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf14
del primals_12
return buf15, reinterpret_tensor(buf0, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf8, reinterpret_tensor(buf11, (16, 4), (4, 1), 0
), reinterpret_tensor(buf13, (16, 4), (4, 1), 0
), buf16, primals_11, primals_9, reinterpret_tensor(buf9, (16, 1, 4
), (4, 1, 1), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf5, (16, 4, 1), (4, 1, 1), 0), primals_3
def qkv_attention(queries, keys, values, presence=None):
"""
Transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
d_k = queries.shape[-1]
routing = torch.matmul(queries, keys.transpose(1, 2))
if presence is not None:
routing -= (1.0 - presence.unsqueeze(-2)) * 1e+32
routing = F.softmax(routing / np.sqrt(d_k), -1)
return torch.matmul(routing, values)
class MultiHeadQKVAttention(nn.Module):
"""Multi-head version of Transformer-like attention."""
def __init__(self, d_k, d_v, n_heads):
super().__init__()
self.d_k = d_k
self.d_v = d_v
self.n_heads = n_heads
d_k_p = int(math.ceil(d_k / n_heads)) * n_heads
d_v_p = int(math.ceil(d_v / n_heads)) * n_heads
self.q_projector = nn.Linear(d_k, d_k_p)
self.k_projector = nn.Linear(d_k, d_k_p)
self.v_projector = nn.Linear(d_v, d_v_p)
self.o_projector = nn.Linear(d_v_p, d_v)
def forward(self, queries, keys, values, presence=None):
"""
Multi-head transformer-like self-attention.
Args:
queries: Tensor of shape [B, N, d_k].
keys: Tensor of shape [B, M, d_k].
values: : Tensor of shape [B, M, d_v].
presence: None or tensor of shape [B, M].
Returns:
Tensor of shape [B, N, d_v]
"""
assert queries.shape[2] == keys.shape[2]
assert keys.shape[1] == values.shape[1]
if presence is not None:
assert values.shape[:2] == presence.shape
B, N, _d_k = queries.shape
M, _d_v = values.shape[1:]
H = self.n_heads
q_p = self.q_projector(queries)
k_p = self.k_projector(keys)
v_p = self.v_projector(values)
del queries, keys, values
q = q_p.view(B, N, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, N, -1)
k = k_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
v = v_p.view(B, M, H, -1).permute(2, 0, 1, 3).contiguous().view(H *
B, M, -1)
if presence is not None:
presence = presence.repeat(self.n_heads, 1)
o = qkv_attention(q, k, v, presence)
o = o.view(H, B, N, -1).permute(1, 2, 0, 3).contiguous().view(B, N, -1)
return self.o_projector(o)
class MAB(nn.Module):
def __init__(self, d, n_heads, layer_norm=False):
super().__init__()
self.layer_norm = layer_norm
self.mqkv = MultiHeadQKVAttention(d_k=d, d_v=d, n_heads=n_heads)
if layer_norm:
self.ln0 = nn.LayerNorm(d)
self.ln1 = nn.LayerNorm(d)
self.fc = nn.Linear(d, d)
def forward(self, queries, keys, presence=None):
h = self.mqkv(queries, keys, keys, presence)
h = h + queries
if presence is not None:
assert presence.shape[1] == queries.shape[1] == keys.shape[1]
h = h * presence.unsqueeze(-1)
if self.layer_norm:
h = self.ln0(h)
h = h + F.relu(self.fc(h))
if self.layer_norm:
h = self.ln1(h)
return h
class PMANew(nn.Module):
def __init__(self, d, n_heads, n_seeds, layer_norm=False):
super().__init__()
self.mab = MAB(d=d, n_heads=n_heads, layer_norm=layer_norm)
self.S = nn.Parameter(torch.zeros(1, n_seeds, d), requires_grad=True)
with torch.no_grad():
nn.init.xavier_uniform_(self.S)
def forward(self, input_0):
primals_2 = self.S
primals_3 = self.mab.mqkv.q_projector.weight
primals_4 = self.mab.mqkv.q_projector.bias
primals_5 = self.mab.mqkv.k_projector.weight
primals_6 = self.mab.mqkv.k_projector.bias
primals_7 = self.mab.mqkv.v_projector.weight
primals_8 = self.mab.mqkv.v_projector.bias
primals_9 = self.mab.mqkv.o_projector.weight
primals_10 = self.mab.mqkv.o_projector.bias
primals_11 = self.mab.fc.weight
primals_12 = self.mab.fc.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])
return output[0]
|
KohavTal/SCAE_Project
|
PMA
| false
| 8,421
|
[
"Apache-2.0"
] | 40
|
bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
https://github.com/KohavTal/SCAE_Project/tree/bc6d1c3697fcb9327dd96e9657c3299b47cf355e
|
MeanMap
|
import torch
import torch.nn as nn
import torch.autograd
class MeanMap(nn.Module):
"""
Compute vanilla mean on a 4D tensor. This acts as a standard PyTorch layer.
The Mean is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) Recommend a tensor with only positive values. (After a ReLU)
Any real value will work.
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self):
super(MeanMap, self).__init__()
def forward(self, x):
assert torch.is_tensor(x), 'input must be a Torch Tensor'
assert len(x.size()) > 2, 'input must have at least three dims'
x = torch.mean(x, dim=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mean_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class MeanMapNew(nn.Module):
"""
Compute vanilla mean on a 4D tensor. This acts as a standard PyTorch layer.
The Mean is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) Recommend a tensor with only positive values. (After a ReLU)
Any real value will work.
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self):
super(MeanMapNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
MeanMap
| false
| 8,422
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
SMOEScaleMap
|
import torch
import torch.nn as nn
import torch.autograd
class SMOEScaleMap(nn.Module):
"""
Compute SMOE Scale on a 4D tensor. This acts as a standard PyTorch layer.
SMOE Scale is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) A tensor with only positive values. (After a ReLU)
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self, run_relu=False):
super(SMOEScaleMap, self).__init__()
"""
SMOE Scale must take in values > 0. Optionally, we can run a ReLU to do that.
"""
if run_relu:
self.relu = nn.ReLU(inplace=False)
else:
self.relu = None
def forward(self, x):
assert torch.is_tensor(x), 'input must be a Torch Tensor'
assert len(x.size()) > 2, 'input must have at least three dims'
"""
If we do not have a convenient ReLU to pluck from, we can do it here
"""
if self.relu is not None:
x = self.relu(x)
"""
avoid log(0)
"""
x = x + 1e-07
"""
This is one form. We can also use the log only form.
"""
m = torch.mean(x, dim=1)
k = torch.log2(m) - torch.mean(torch.log2(x), dim=1)
th = k * m
return th
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.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_add_log2_mean_mul_sub_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp1 = 1e-07
tmp2 = tmp0 + tmp1
tmp4 = tmp3 + tmp1
tmp5 = tmp2 + tmp4
tmp7 = tmp6 + tmp1
tmp8 = tmp5 + tmp7
tmp10 = tmp9 + tmp1
tmp11 = tmp8 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = libdevice.log2(tmp13)
tmp15 = libdevice.log2(tmp2)
tmp16 = libdevice.log2(tmp4)
tmp17 = tmp15 + tmp16
tmp18 = libdevice.log2(tmp7)
tmp19 = tmp17 + tmp18
tmp20 = libdevice.log2(tmp10)
tmp21 = tmp19 + tmp20
tmp22 = tmp21 / tmp12
tmp23 = tmp14 - tmp22
tmp24 = tmp23 * tmp13
tl.store(out_ptr0 + x2, tmp24, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_log2_mean_mul_sub_0[grid(64)](arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
return buf0,
class SMOEScaleMapNew(nn.Module):
"""
Compute SMOE Scale on a 4D tensor. This acts as a standard PyTorch layer.
SMOE Scale is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) A tensor with only positive values. (After a ReLU)
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self, run_relu=False):
super(SMOEScaleMapNew, self).__init__()
"""
SMOE Scale must take in values > 0. Optionally, we can run a ReLU to do that.
"""
if run_relu:
self.relu = nn.ReLU(inplace=False)
else:
self.relu = None
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
SMOEScaleMap
| false
| 8,423
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
EqualConv2d
|
import torch
import torch.nn as nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualConv2d(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
conv = nn.Conv2d(*args, **kwargs)
conv.weight.data.normal_()
conv.bias.data.zero_()
self.conv = equal_lr(conv)
def forward(self, input):
return self.conv(input)
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
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.1767766952966369
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(primals_3, buf0, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 1, 1), (4, 1, 1, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(16)](buf2, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
return buf2, buf0, primals_3, buf0
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualConv2dNew(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
conv = nn.Conv2d(*args, **kwargs)
conv.weight.data.normal_()
conv.bias.data.zero_()
self.conv = equal_lr(conv)
def forward(self, input_0):
primals_2 = self.conv.bias
primals_1 = self.conv.weight_orig
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
KwonGihyun/DiagonalGAN
|
EqualConv2d
| false
| 8,424
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
SE
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SE(nn.Module):
"""Squeeze-and-Excitation block."""
def __init__(self, in_planes, se_planes):
super(SE, self).__init__()
self.se1 = nn.Conv2d(in_planes, se_planes, kernel_size=1, bias=True)
self.se2 = nn.Conv2d(se_planes, in_planes, kernel_size=1, bias=True)
def forward(self, x):
out = F.adaptive_avg_pool2d(x, (1, 1))
out = F.relu(self.se1(out))
out = self.se2(out).sigmoid()
out = x * out
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_planes': 4, 'se_planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 16.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=8,
num_warps=2, num_stages=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, 4, 1, 1), (4, 1, 1, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(16)](buf3, primals_3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf4 = extern_kernels.convolution(buf3, 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, 4, 1, 1), (4, 1, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(16)](buf5, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_3[grid(256)](primals_1, buf5, buf6,
256, XBLOCK=128, num_warps=4, num_stages=1)
return buf6, primals_1, primals_2, primals_4, buf1, buf3, buf5
class SENew(nn.Module):
"""Squeeze-and-Excitation block."""
def __init__(self, in_planes, se_planes):
super(SENew, self).__init__()
self.se1 = nn.Conv2d(in_planes, se_planes, kernel_size=1, bias=True)
self.se2 = nn.Conv2d(se_planes, in_planes, kernel_size=1, bias=True)
def forward(self, input_0):
primals_2 = self.se1.weight
primals_3 = self.se1.bias
primals_4 = self.se2.weight
primals_5 = self.se2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
LIJUNYI95/SuperAdam
|
SE
| false
| 8,425
|
[
"MIT"
] | 14
|
00fc8a4d90bd037ccb9b871fbc64482818457b93
|
https://github.com/LIJUNYI95/SuperAdam/tree/00fc8a4d90bd037ccb9b871fbc64482818457b93
|
StdMap
|
import torch
import torch.nn as nn
import torch.autograd
class StdMap(nn.Module):
"""
Compute vanilla standard deviation on a 4D tensor. This acts as a standard PyTorch layer.
Standard Deviation is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) Recommend a tensor with only positive values. (After a ReLU)
Any real value will work.
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self):
super(StdMap, self).__init__()
def forward(self, x):
assert torch.is_tensor(x), 'input must be a Torch Tensor'
assert len(x.size()) > 2, 'input must have at least three dims'
x = torch.std(x, dim=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_std_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = 3.0
tmp21 = tmp19 / tmp20
tmp22 = libdevice.sqrt(tmp21)
tl.store(out_ptr0 + x2, tmp22, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_std_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class StdMapNew(nn.Module):
"""
Compute vanilla standard deviation on a 4D tensor. This acts as a standard PyTorch layer.
Standard Deviation is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) Recommend a tensor with only positive values. (After a ReLU)
Any real value will work.
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self):
super(StdMapNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
StdMap
| false
| 8,426
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
RangeNorm2D
|
import torch
import torch.nn as nn
import torch.autograd
class RangeNorm2D(nn.Module):
"""
This will normalize a saliency map to range from 0 to 1 via linear range function.
Input and output will be a 3D tensor of size [batch size x height x width].
Input can be any real valued number (supported by hardware)
Output will range from 0 to 1
Parameters:
full_norm: This forces the values to range completely from 0 to 1.
"""
def __init__(self, full_norm=True, eps=1e-09):
super(RangeNorm2D, self).__init__()
self.full_norm = full_norm
self.eps = eps
def forward(self, x):
"""
Input:
x: A Torch Tensor image with shape [batch size x height x width] e.g. [64,7,7]
All values should be real positive (i.e. >= 0).
Return:
x: x Normalized by dividing by either the min value or the range between max and min.
Each max/min is computed for each batch item.
"""
assert torch.is_tensor(x), 'Input must be a Torch Tensor'
assert len(x.size()
) == 3, 'Input should be sizes [batch size x height x width]'
s0 = x.size()[0]
s1 = x.size()[1]
s2 = x.size()[2]
x = x.reshape(s0, s1 * s2)
xmax = x.max(dim=1)[0].reshape(s0, 1)
if self.full_norm:
xmin = x.min(dim=1)[0].reshape(s0, 1)
nval = x - xmin
range = xmax - xmin
else:
nval = x
range = xmax
"""
prevent divide by zero by setting zero to a small number
Simply adding eps does not work will in this case. So we use torch.where to set a minimum value.
"""
eps_mat = torch.zeros_like(range) + self.eps
range = torch.where(range > self.eps, range, eps_mat)
x = nval / range
x = x.reshape(s0, s1, s2)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_gt_max_min_sub_where_0(in_ptr0, out_ptr2,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp6 = tl.where(xmask, tmp1, float('inf'))
tmp7 = triton_helpers.min2(tmp6, 1)[:, None]
tmp8 = tmp0 - tmp7
tmp9 = tmp4 - tmp7
tmp10 = 1e-09
tmp11 = tmp9 > tmp10
tmp12 = 9.999999717180685e-10
tmp13 = tl.where(tmp11, tmp9, tmp12)
tmp14 = tmp8 / tmp13
tl.store(out_ptr2 + (r1 + 16 * x0), tmp14, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf4 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_gt_max_min_sub_where_0[grid(4)](arg0_1,
buf4, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0),
class RangeNorm2DNew(nn.Module):
"""
This will normalize a saliency map to range from 0 to 1 via linear range function.
Input and output will be a 3D tensor of size [batch size x height x width].
Input can be any real valued number (supported by hardware)
Output will range from 0 to 1
Parameters:
full_norm: This forces the values to range completely from 0 to 1.
"""
def __init__(self, full_norm=True, eps=1e-09):
super(RangeNorm2DNew, self).__init__()
self.full_norm = full_norm
self.eps = eps
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
RangeNorm2D
| false
| 8,427
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
MaxMap
|
import torch
import torch.nn as nn
import torch.autograd
class MaxMap(nn.Module):
"""
Compute vanilla mean on a 4D tensor. This acts as a standard PyTorch layer.
The Max is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) Recommend a tensor with only positive values. (After a ReLU)
Any real value will work.
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self):
super(MaxMap, self).__init__()
def forward(self, x):
assert torch.is_tensor(x), 'input must be a Torch Tensor'
assert len(x.size()) > 2, 'input must have at least three dims'
x = torch.max(x, dim=1)[0]
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_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 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class MaxMapNew(nn.Module):
"""
Compute vanilla mean on a 4D tensor. This acts as a standard PyTorch layer.
The Max is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) Recommend a tensor with only positive values. (After a ReLU)
Any real value will work.
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self):
super(MaxMapNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
MaxMap
| false
| 8,428
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
InfoNCE_loss_vectorized
|
import torch
import torch.nn as nn
class InfoNCE_loss_vectorized(nn.Module):
"""
SimCLR loss: https://github.com/google-research/simclr // https://github.com/sthalles/SimCLR
"""
def __init__(self, temperature):
super(InfoNCE_loss_vectorized, self).__init__()
self.temperature = temperature
self.cos = nn.CosineSimilarity(dim=1)
def forward(self, graph_out, sent_out):
total_loss = 0
for g, s in zip(graph_out, sent_out):
similarities = self.cos(g, s)
similarities = similarities / self.temperature
exp_tensor = torch.exp(similarities)
loss = exp_tensor[0] / torch.sum(exp_tensor)
loss = -torch.log(loss)
total_loss = total_loss + loss
total_loss_final = total_loss / len(graph_out)
return total_loss_final
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'temperature': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + x3, xmask)
tmp17 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr1 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr1 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-08
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp18 = tmp17 * tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = triton_helpers.maximum(tmp28, tmp13)
tmp30 = tmp16 / tmp29
tmp31 = tmp15 * tmp30
tl.store(out_ptr0 + x3, tmp31, xmask)
@triton.jit
def triton_per_fused_div_exp_sum_1(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 4
r1 = rindex // 4
tmp0 = tl.load(in_ptr0 + (r0 + 16 * r1), None)
tmp1 = tl.load(in_ptr0 + (4 + r0 + 16 * r1), None)
tmp3 = tl.load(in_ptr0 + (8 + r0 + 16 * r1), None)
tmp5 = tl.load(in_ptr0 + (12 + r0 + 16 * r1), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.sum(tmp10, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp12, None)
@triton.jit
def triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_2(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + (64 + x3), xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (68 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (72 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (76 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + (64 + x3), xmask)
tmp17 = tl.load(in_ptr1 + (64 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr1 + (68 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (72 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr1 + (76 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-08
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp18 = tmp17 * tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = triton_helpers.maximum(tmp28, tmp13)
tmp30 = tmp16 / tmp29
tmp31 = tmp15 * tmp30
tl.store(out_ptr0 + x3, tmp31, xmask)
@triton.jit
def triton_poi_fused_clamp_min_div_linalg_vector_norm_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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + (128 + x3), xmask)
tmp1 = tl.load(in_ptr0 + (128 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (132 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (136 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (140 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + (128 + x3), xmask)
tmp17 = tl.load(in_ptr1 + (128 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr1 + (132 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (136 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr1 + (140 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-08
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp18 = tmp17 * tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = triton_helpers.maximum(tmp28, tmp13)
tmp30 = tmp16 / tmp29
tmp31 = tmp15 * tmp30
tl.store(out_ptr0 + x3, tmp31, xmask)
@triton.jit
def triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_4(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + (192 + x3), xmask)
tmp1 = tl.load(in_ptr0 + (192 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (196 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (200 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (204 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + (192 + x3), xmask)
tmp17 = tl.load(in_ptr1 + (192 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr1 + (196 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp22 = tl.load(in_ptr1 + (200 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr1 + (204 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-08
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tmp18 = tmp17 * tmp17
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = triton_helpers.maximum(tmp28, tmp13)
tmp30 = tmp16 / tmp29
tmp31 = tmp15 * tmp30
tl.store(out_ptr0 + x3, tmp31, xmask)
@triton.jit
def triton_poi_fused_add_div_log_neg_5(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, xnumel, XBLOCK:
tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0), xmask)
tmp10 = tl.load(in_ptr1 + 0)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK])
tmp17 = tl.load(in_ptr2 + x0, xmask)
tmp18 = tl.load(in_ptr2 + (4 + x0), xmask)
tmp20 = tl.load(in_ptr2 + (8 + x0), xmask)
tmp22 = tl.load(in_ptr2 + (12 + x0), xmask)
tmp26 = tl.load(in_ptr3 + 0)
tmp27 = tl.broadcast_to(tmp26, [XBLOCK])
tmp32 = tl.load(in_ptr4 + x0, xmask)
tmp33 = tl.load(in_ptr4 + (4 + x0), xmask)
tmp35 = tl.load(in_ptr4 + (8 + x0), xmask)
tmp37 = tl.load(in_ptr4 + (12 + x0), xmask)
tmp41 = tl.load(in_ptr5 + 0)
tmp42 = tl.broadcast_to(tmp41, [XBLOCK])
tmp47 = tl.load(in_ptr6 + x0, xmask)
tmp48 = tl.load(in_ptr6 + (4 + x0), xmask)
tmp50 = tl.load(in_ptr6 + (8 + x0), xmask)
tmp52 = tl.load(in_ptr6 + (12 + x0), xmask)
tmp56 = tl.load(in_ptr7 + 0)
tmp57 = tl.broadcast_to(tmp56, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tmp9 = tl_math.exp(tmp8)
tmp12 = tmp9 / tmp11
tmp13 = tl_math.log(tmp12)
tmp14 = -tmp13
tmp15 = 0.0
tmp16 = tmp14 + tmp15
tmp19 = tmp17 + tmp18
tmp21 = tmp19 + tmp20
tmp23 = tmp21 + tmp22
tmp24 = tmp23 * tmp7
tmp25 = tl_math.exp(tmp24)
tmp28 = tmp25 / tmp27
tmp29 = tl_math.log(tmp28)
tmp30 = -tmp29
tmp31 = tmp16 + tmp30
tmp34 = tmp32 + tmp33
tmp36 = tmp34 + tmp35
tmp38 = tmp36 + tmp37
tmp39 = tmp38 * tmp7
tmp40 = tl_math.exp(tmp39)
tmp43 = tmp40 / tmp42
tmp44 = tl_math.log(tmp43)
tmp45 = -tmp44
tmp46 = tmp31 + tmp45
tmp49 = tmp47 + tmp48
tmp51 = tmp49 + tmp50
tmp53 = tmp51 + tmp52
tmp54 = tmp53 * tmp7
tmp55 = tl_math.exp(tmp54)
tmp58 = tmp55 / tmp57
tmp59 = tl_math.log(tmp58)
tmp60 = -tmp59
tmp61 = tmp46 + tmp60
tmp62 = tmp61 * tmp7
tl.store(in_out_ptr0 + x0, tmp62, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0[grid(64)](
arg0_1, arg1_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_div_exp_sum_1[grid(1)](buf0, buf1, 1, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_2[grid(64)](
arg0_1, arg1_1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_div_exp_sum_1[grid(1)](buf2, buf3, 1, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_3[grid(64)](
arg0_1, arg1_1, buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_div_exp_sum_1[grid(1)](buf5, buf6, 1, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_4[grid(64)](
arg0_1, arg1_1, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf8 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_div_exp_sum_1[grid(1)](buf7, buf8, 1, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf4 = empty_strided_cuda((4,), (1,), torch.float32)
buf9 = buf4
del buf4
buf10 = buf9
del buf9
triton_poi_fused_add_div_log_neg_5[grid(4)](buf10, buf0, buf1, buf2,
buf3, buf5, buf6, buf7, buf8, 4, XBLOCK=4, num_warps=1,
num_stages=1)
del buf0
del buf1
del buf2
del buf3
del buf5
del buf6
del buf7
del buf8
return buf10,
class InfoNCE_loss_vectorizedNew(nn.Module):
"""
SimCLR loss: https://github.com/google-research/simclr // https://github.com/sthalles/SimCLR
"""
def __init__(self, temperature):
super(InfoNCE_loss_vectorizedNew, self).__init__()
self.temperature = temperature
self.cos = nn.CosineSimilarity(dim=1)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
LIIR-KULeuven/CLDR_CLNER_models
|
InfoNCE_loss_vectorized
| false
| 8,429
|
[
"MIT"
] | 12
|
5fe47a988b88a36d0ccf4484aff5ab70c59f39d6
|
https://github.com/LIIR-KULeuven/CLDR_CLNER_models/tree/5fe47a988b88a36d0ccf4484aff5ab70c59f39d6
|
ClassificationModel
|
import torch
import torch.nn as nn
class ClassificationModel(nn.Module):
def __init__(self, num_features_in, num_anchors=9, num_classes=80,
prior=0.01, feature_size=256):
super(ClassificationModel, self).__init__()
self.num_classes = num_classes
self.num_anchors = num_anchors
self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3,
padding=1)
self.act1 = nn.ReLU()
self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3,
padding=1)
self.act2 = nn.ReLU()
self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3,
padding=1)
self.act3 = nn.ReLU()
self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3,
padding=1)
self.act4 = nn.ReLU()
self.output = nn.Conv2d(feature_size, num_anchors * num_classes,
kernel_size=3, padding=1)
self.output_act = nn.Sigmoid()
def forward(self, x):
out = self.conv1(x)
out = self.act1(out)
out = self.conv2(out)
out = self.act2(out)
out = self.conv3(out)
out = self.act3(out)
out = self.conv4(out)
out = self.act4(out)
out = self.output(out)
out = self.output_act(out)
out1 = out.permute(0, 2, 3, 1)
batch_size, width, height, _channels = out1.shape
out2 = out1.view(batch_size, width, height, self.num_anchors, self.
num_classes)
return out2
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features_in': 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_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)
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_sigmoid_sigmoid_backward_5(in_ptr0,
in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr,
XBLOCK: tl.constexpr):
ynumel = 2880
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 720
y1 = yindex // 720
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 720 * x2 + 11520 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp4 = 1.0
tmp5 = tmp4 - tmp3
tmp6 = tmp3 * tmp5
tl.store(out_ptr0 + (x2 + 16 * y3), tmp3, xmask & ymask)
tl.store(out_ptr1 + (y0 + 720 * x2 + 11520 * y1), tmp6, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (256, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_5, (256,), (1,))
assert_size_stride(primals_6, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_9, (256,), (1,))
assert_size_stride(primals_10, (720, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_11, (720,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((256, 4, 3, 3), (36, 1, 12, 4), torch.float32
)
get_raw_stream(0)
triton_poi_fused_0[grid(1024, 9)](primals_1, buf0, 1024, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_1[grid(16, 16)](primals_3, buf1, 16, 16, XBLOCK=16,
YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_2[grid(65536, 9)](primals_4, buf2, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_2[grid(65536, 9)](primals_6, buf3, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_2[grid(65536, 9)](primals_8, buf4, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf5 = empty_strided_cuda((720, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_3[grid(184320, 9)](primals_10, buf5, 184320, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_10
buf6 = extern_kernels.convolution(buf1, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 256, 4, 4), (4096, 1, 1024, 256))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_4[grid(16384)](buf7, primals_2,
16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf8 = extern_kernels.convolution(buf7, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 256, 4, 4), (4096, 1, 1024, 256))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_4[grid(16384)](buf9, primals_5,
16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf10 = extern_kernels.convolution(buf9, buf3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 256, 4, 4), (4096, 1, 1024, 256))
buf11 = buf10
del buf10
triton_poi_fused_convolution_relu_4[grid(16384)](buf11, primals_7,
16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf12 = extern_kernels.convolution(buf11, buf4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 256, 4, 4), (4096, 1, 1024, 256))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_4[grid(16384)](buf13, primals_9,
16384, XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf14 = extern_kernels.convolution(buf13, buf5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 720, 4, 4), (11520, 1, 2880, 720))
buf15 = empty_strided_cuda((4, 720, 4, 4), (11520, 16, 4, 1), torch
.float32)
buf16 = empty_strided_cuda((4, 720, 4, 4), (11520, 1, 2880, 720),
torch.float32)
triton_poi_fused_convolution_sigmoid_sigmoid_backward_5[grid(2880, 16)
](buf14, primals_11, buf15, buf16, 2880, 16, XBLOCK=16, YBLOCK=
32, num_warps=4, num_stages=1)
del buf14
del primals_11
return reinterpret_tensor(buf15, (4, 4, 4, 9, 80), (11520, 4, 1, 1280,
16), 0
), buf0, buf1, buf2, buf3, buf4, buf5, buf7, buf9, buf11, buf13, buf16
class ClassificationModelNew(nn.Module):
def __init__(self, num_features_in, num_anchors=9, num_classes=80,
prior=0.01, feature_size=256):
super(ClassificationModelNew, self).__init__()
self.num_classes = num_classes
self.num_anchors = num_anchors
self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3,
padding=1)
self.act1 = nn.ReLU()
self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3,
padding=1)
self.act2 = nn.ReLU()
self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3,
padding=1)
self.act3 = nn.ReLU()
self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3,
padding=1)
self.act4 = nn.ReLU()
self.output = nn.Conv2d(feature_size, num_anchors * num_classes,
kernel_size=3, padding=1)
self.output_act = nn.Sigmoid()
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.output.weight
primals_11 = self.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]
|
LLYXC/OXNet
|
ClassificationModel
| false
| 8,430
|
[
"Apache-2.0"
] | 13
|
4fb67a8c42b9158a8e563c4b68a157e4dedd9c66
|
https://github.com/LLYXC/OXNet/tree/4fb67a8c42b9158a8e563c4b68a157e4dedd9c66
|
TwoLayerNet
|
import torch
class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, x):
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'D_in': 4, 'H': 4, 'D_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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clamp_ge_0(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 % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp5 = tmp2 >= tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_clamp_ge_0[grid(256)](buf0, primals_2, buf1, buf3,
256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = buf0
del buf0
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), primals_4, buf3
class TwoLayerNetNew(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(TwoLayerNetNew, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, input_0):
primals_1 = self.linear1.weight
primals_2 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
KentonMurray/ProxGradPytorch
|
TwoLayerNet
| false
| 8,431
|
[
"MIT"
] | 27
|
c534a49142ac9ec149ca67de24bb0487fde1607b
|
https://github.com/KentonMurray/ProxGradPytorch/tree/c534a49142ac9ec149ca67de24bb0487fde1607b
|
DiagonalwiseRefactorization
|
import torch
import numpy as np
import torch.nn.parallel
import torch.optim
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
def get_mask(in_channels, channels, ks):
in_channels = int(in_channels)
channels = int(channels)
if len(ks) == 1:
mask = np.zeros((int(in_channels), int(channels), int(ks[0])))
elif len(ks) == 2:
mask = np.zeros((int(in_channels), int(channels), int(ks[0]), int(
ks[1])))
elif len(ks) == 3:
mask = np.zeros((int(in_channels), int(channels), int(ks[0]), int(
ks[1]), int(ks[2])))
else:
raise Error('not implement yet')
for _ in range(in_channels):
mask[_, _ % channels, :, :] = 1.0
return mask
class DiagonalwiseRefactorization(nn.Module):
def __init__(self, in_channels, ks, stride=1, groups=1):
super(DiagonalwiseRefactorization, self).__init__()
channels = in_channels // groups
self.in_channels = in_channels
self.groups = groups
self.stride = stride
p = (np.array(ks) - 1) // 2
self.p = p.tolist()
self.mask = nn.Parameter(torch.Tensor(get_mask(in_channels,
channels, ks=ks)), requires_grad=False)
self.weight = nn.Parameter(torch.Tensor(in_channels, channels, *ks),
requires_grad=True)
torch.nn.init.xavier_uniform_(self.weight.data)
self.weight.data.mul_(self.mask.data)
if len(ks) == 1:
self.conv = nn.functional.conv1d
elif len(ks) == 2:
self.conv = nn.functional.conv2d
elif len(ks) == 3:
self.conv = nn.functional.conv3d
else:
raise Error(
'The kernal size in DiagonalwiseRefactorization is wrong!')
def forward(self, x):
weight = torch.mul(self.weight, self.mask)
x = self.conv(x, weight, bias=None, stride=self.stride, padding=
self.p, groups=self.groups)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'ks': [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
import numpy as np
import torch.nn.parallel
import torch.optim
import torch
import torch.nn as nn
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, primals_2, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(primals_3, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 3, 3), (36, 9, 3, 1))
return buf1, primals_2, primals_3, buf0
def get_mask(in_channels, channels, ks):
in_channels = int(in_channels)
channels = int(channels)
if len(ks) == 1:
mask = np.zeros((int(in_channels), int(channels), int(ks[0])))
elif len(ks) == 2:
mask = np.zeros((int(in_channels), int(channels), int(ks[0]), int(
ks[1])))
elif len(ks) == 3:
mask = np.zeros((int(in_channels), int(channels), int(ks[0]), int(
ks[1]), int(ks[2])))
else:
raise Error('not implement yet')
for _ in range(in_channels):
mask[_, _ % channels, :, :] = 1.0
return mask
class DiagonalwiseRefactorizationNew(nn.Module):
def __init__(self, in_channels, ks, stride=1, groups=1):
super(DiagonalwiseRefactorizationNew, self).__init__()
channels = in_channels // groups
self.in_channels = in_channels
self.groups = groups
self.stride = stride
p = (np.array(ks) - 1) // 2
self.p = p.tolist()
self.mask = nn.Parameter(torch.Tensor(get_mask(in_channels,
channels, ks=ks)), requires_grad=False)
self.weight = nn.Parameter(torch.Tensor(in_channels, channels, *ks),
requires_grad=True)
torch.nn.init.xavier_uniform_(self.weight.data)
self.weight.data.mul_(self.mask.data)
if len(ks) == 1:
self.conv = nn.functional.conv1d
elif len(ks) == 2:
self.conv = nn.functional.conv2d
elif len(ks) == 3:
self.conv = nn.functional.conv3d
else:
raise Error(
'The kernal size in DiagonalwiseRefactorization is wrong!')
def forward(self, input_0):
primals_1 = self.mask
primals_2 = self.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LaputaDream/region-based-non-local-network
|
DiagonalwiseRefactorization
| false
| 8,432
|
[
"MIT"
] | 18
|
98e5fb3d8010e8c5360ac3066fdc06c37106d7dc
|
https://github.com/LaputaDream/region-based-non-local-network/tree/98e5fb3d8010e8c5360ac3066fdc06c37106d7dc
|
GroupLinear
|
import torch
import torch.nn as nn
import torch.utils.data
class GroupLinear(nn.Module):
def __init__(self, in_features, out_features, groups, bias=True):
super(GroupLinear, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.groups = groups
self.weight = nn.Parameter(torch.Tensor(groups, out_features //
groups, in_features // groups))
if bias:
self.bias = nn.Parameter(torch.Tensor(groups, out_features //
groups))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
for weight in self.weight:
nn.init.kaiming_uniform_(weight, nonlinearity='linear')
if self.bias is not None:
nn.init.constant_(self.bias, 0)
def forward(self, input):
"""
Args:
input (Tensor): shape (*, in_features)
"""
batch_size = input.shape[:-1]
if self.bias is not None:
output = self.weight @ input.reshape(*batch_size, self.groups,
self.in_features // self.groups, 1) + self.bias[..., None]
else:
output = self.weight @ input.reshape(*batch_size, self.groups,
self.in_features // self.groups, 1)
return output.reshape(*batch_size, self.out_features)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4, 'groups': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
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_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
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, (1, 4), (4, 1))
assert_size_stride(primals_3, (1, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_3, (64, 4, 4), (0, 4,
1), 0), reinterpret_tensor(primals_1, (64, 4, 1), (4, 1, 1), 0),
out=buf0)
del primals_3
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 1, 4, 1), (64, 16, 4, 4,
1, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_1, (64, 1, 4), (4, 1, 1), 0)
class GroupLinearNew(nn.Module):
def __init__(self, in_features, out_features, groups, bias=True):
super(GroupLinearNew, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.groups = groups
self.weight = nn.Parameter(torch.Tensor(groups, out_features //
groups, in_features // groups))
if bias:
self.bias = nn.Parameter(torch.Tensor(groups, out_features //
groups))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
for weight in self.weight:
nn.init.kaiming_uniform_(weight, nonlinearity='linear')
if self.bias is not None:
nn.init.constant_(self.bias, 0)
def forward(self, input_0):
primals_3 = self.weight
primals_2 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Lakonik/EPro-PnP
|
GroupLinear
| false
| 8,433
|
[
"Apache-2.0"
] | 19
|
931df847190ce10eddd1dc3e3168ce1a2f295ffa
|
https://github.com/Lakonik/EPro-PnP/tree/931df847190ce10eddd1dc3e3168ce1a2f295ffa
|
GammaScaleMap
|
import torch
import torch.nn as nn
import torch.autograd
class GammaScaleMap(nn.Module):
"""
Compute Gamma Scale on a 4D tensor (The hard way). This acts as a standard PyTorch layer.
Gamma Scale is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) A tensor with only positive values. (After a ReLU)
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self, run_relu=False):
super(GammaScaleMap, self).__init__()
"""
SMOE Scale must take in values > 0. Optionally, we can run a ReLU to do that.
"""
if run_relu:
self.relu = nn.ReLU(inplace=False)
else:
self.relu = None
def _trigamma(self, x):
"""
We need this line since recursion is not good for x < 1.0
Note that we take + torch.reciprocal(x.pow(2)) at the end because:
trigamma(z) = trigamma(z + 1) + 1/z^2
"""
z = x + 1.0
zz = z.pow(2)
a = 0.2 - torch.reciprocal(7.0 * zz)
b = 1.0 - a / zz
c = 1.0 + b / (3.0 * z)
d = 1.0 + c / (2.0 * z)
e = d / z
e = e + torch.reciprocal(x.pow(2.0))
return e
def _k_update(self, k, s):
nm = torch.log(k) - torch.digamma(k) - s
dn = torch.reciprocal(k) - self._trigamma(k)
k2 = k - nm / dn
return k2
def _compute_k_est(self, x, i=10, dim=1):
"""
Calculate s
"""
s = torch.log(torch.mean(x, dim=dim)) - torch.mean(torch.log(x),
dim=dim)
"""
Get estimate of k to within 1.5%
NOTE: K gets smaller as log variance s increases
"""
s3 = s - 3.0
rt = torch.sqrt(s3.pow(2) + 24.0 * s)
nm = 3.0 - s + rt
dn = 12.0 * s
k = nm / dn + 1e-07
"""
Do i Newton-Raphson steps to get closer than 1.5%
For i=5 gets us within 4 or 5 decimal places
"""
for _ in range(i):
k = self._k_update(k, s)
return k
def forward(self, x):
assert torch.is_tensor(x), 'input must be a Torch Tensor'
assert len(x.size()) > 2, 'input must have at least three dims'
"""
If we do not have a convenient ReLU to pluck from, we can do it here
"""
if self.relu is not None:
x = self.relu(x)
"""
avoid log(0)
"""
x = x + 1e-07
k = self._compute_k_est(x)
th = torch.reciprocal(k) * torch.mean(x, dim=1)
return th
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_log_mean_mul_pow_rsub_sqrt_sub_0(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp1 = 1e-07
tmp2 = tmp0 + tmp1
tmp4 = tmp3 + tmp1
tmp5 = tmp2 + tmp4
tmp7 = tmp6 + tmp1
tmp8 = tmp5 + tmp7
tmp10 = tmp9 + tmp1
tmp11 = tmp8 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = tl_math.log(tmp13)
tmp15 = tl_math.log(tmp2)
tmp16 = tl_math.log(tmp4)
tmp17 = tmp15 + tmp16
tmp18 = tl_math.log(tmp7)
tmp19 = tmp17 + tmp18
tmp20 = tl_math.log(tmp10)
tmp21 = tmp19 + tmp20
tmp22 = tmp21 / tmp12
tmp23 = tmp14 - tmp22
tmp24 = 3.0
tmp25 = tmp23 - tmp24
tmp26 = tmp25 * tmp25
tmp27 = 24.0
tmp28 = tmp23 * tmp27
tmp29 = tmp26 + tmp28
tmp30 = libdevice.sqrt(tmp29)
tmp31 = tmp24 - tmp23
tmp32 = tmp31 + tmp30
tmp33 = 12.0
tmp34 = tmp23 * tmp33
tmp35 = tmp32 / tmp34
tmp36 = tmp35 + tmp1
tl.store(in_out_ptr0 + x2, tmp35, xmask)
tl.store(out_ptr0 + x2, tmp36, xmask)
@triton.jit
def triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_1(in_out_ptr0
, in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp6 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp11 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp14 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp30 = tl.load(in_ptr2 + x2, xmask)
tmp1 = 1e-07
tmp2 = tmp0 + tmp1
tmp3 = tl_math.log(tmp2)
tmp5 = tmp3 - tmp4
tmp7 = tmp6 + tmp1
tmp9 = tmp8 + tmp1
tmp10 = tmp7 + tmp9
tmp12 = tmp11 + tmp1
tmp13 = tmp10 + tmp12
tmp15 = tmp14 + tmp1
tmp16 = tmp13 + tmp15
tmp17 = 4.0
tmp18 = tmp16 / tmp17
tmp19 = tl_math.log(tmp18)
tmp20 = tl_math.log(tmp7)
tmp21 = tl_math.log(tmp9)
tmp22 = tmp20 + tmp21
tmp23 = tl_math.log(tmp12)
tmp24 = tmp22 + tmp23
tmp25 = tl_math.log(tmp15)
tmp26 = tmp24 + tmp25
tmp27 = tmp26 / tmp17
tmp28 = tmp19 - tmp27
tmp29 = tmp5 - tmp28
tmp31 = tl.full([1], 1, tl.int32)
tmp32 = tmp31 / tmp30
tmp33 = 1.0
tmp34 = tmp30 + tmp33
tmp35 = tmp34 * tmp34
tmp36 = 7.0
tmp37 = tmp35 * tmp36
tmp38 = tmp31 / tmp37
tmp39 = 0.2
tmp40 = tmp39 - tmp38
tmp41 = tmp40 / tmp35
tmp42 = tmp33 - tmp41
tmp43 = 3.0
tmp44 = tmp34 * tmp43
tmp45 = tmp42 / tmp44
tmp46 = tmp45 + tmp33
tmp47 = 2.0
tmp48 = tmp34 * tmp47
tmp49 = tmp46 / tmp48
tmp50 = tmp49 + tmp33
tmp51 = tmp50 / tmp34
tmp52 = tmp30 * tmp30
tmp53 = tmp31 / tmp52
tmp54 = tmp51 + tmp53
tmp55 = tmp32 - tmp54
tmp56 = tmp29 / tmp55
tmp57 = tmp30 - tmp56
tl.store(in_out_ptr0 + x2, tmp56, xmask)
tl.store(out_ptr0 + x2, tmp57, xmask)
@triton.jit
def triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_2(in_out_ptr0
, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr1 + x2, xmask)
tmp6 = tl.load(in_ptr2 + (x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr2 + (16 + x0 + 64 * x1), xmask)
tmp12 = tl.load(in_ptr2 + (32 + x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr2 + (48 + x0 + 64 * x1), xmask)
tmp31 = tl.load(in_ptr3 + x2, xmask)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.log(tmp2)
tmp5 = tmp3 - tmp4
tmp7 = 1e-07
tmp8 = tmp6 + tmp7
tmp10 = tmp9 + tmp7
tmp11 = tmp8 + tmp10
tmp13 = tmp12 + tmp7
tmp14 = tmp11 + tmp13
tmp16 = tmp15 + tmp7
tmp17 = tmp14 + tmp16
tmp18 = 4.0
tmp19 = tmp17 / tmp18
tmp20 = tl_math.log(tmp19)
tmp21 = tl_math.log(tmp8)
tmp22 = tl_math.log(tmp10)
tmp23 = tmp21 + tmp22
tmp24 = tl_math.log(tmp13)
tmp25 = tmp23 + tmp24
tmp26 = tl_math.log(tmp16)
tmp27 = tmp25 + tmp26
tmp28 = tmp27 / tmp18
tmp29 = tmp20 - tmp28
tmp30 = tmp5 - tmp29
tmp32 = tl.full([1], 1, tl.int32)
tmp33 = tmp32 / tmp31
tmp34 = 1.0
tmp35 = tmp31 + tmp34
tmp36 = tmp35 * tmp35
tmp37 = 7.0
tmp38 = tmp36 * tmp37
tmp39 = tmp32 / tmp38
tmp40 = 0.2
tmp41 = tmp40 - tmp39
tmp42 = tmp41 / tmp36
tmp43 = tmp34 - tmp42
tmp44 = 3.0
tmp45 = tmp35 * tmp44
tmp46 = tmp43 / tmp45
tmp47 = tmp46 + tmp34
tmp48 = 2.0
tmp49 = tmp35 * tmp48
tmp50 = tmp47 / tmp49
tmp51 = tmp50 + tmp34
tmp52 = tmp51 / tmp35
tmp53 = tmp31 * tmp31
tmp54 = tmp32 / tmp53
tmp55 = tmp52 + tmp54
tmp56 = tmp33 - tmp55
tmp57 = tmp30 / tmp56
tmp58 = tmp31 - tmp57
tl.store(in_out_ptr0 + x2, tmp30, xmask)
tl.store(out_ptr0 + x2, tmp58, xmask)
@triton.jit
def triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_3(in_out_ptr0
, 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
x1 = xindex % 16
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp30 = tl.load(in_out_ptr0 + x0, xmask)
tmp32 = tl.load(in_ptr2 + (x1 + 64 * x2), xmask)
tmp35 = tl.load(in_ptr2 + (16 + x1 + 64 * x2), xmask)
tmp38 = tl.load(in_ptr2 + (32 + x1 + 64 * x2), xmask)
tmp41 = tl.load(in_ptr2 + (48 + x1 + 64 * x2), xmask)
tmp57 = tl.load(in_ptr3 + x0, xmask)
tmp2 = tl.full([1], 1, tl.int32)
tmp3 = tmp2 / tmp0
tmp4 = 1.0
tmp5 = tmp0 + tmp4
tmp6 = tmp5 * tmp5
tmp7 = 7.0
tmp8 = tmp6 * tmp7
tmp9 = tmp2 / tmp8
tmp10 = 0.2
tmp11 = tmp10 - tmp9
tmp12 = tmp11 / tmp6
tmp13 = tmp4 - tmp12
tmp14 = 3.0
tmp15 = tmp5 * tmp14
tmp16 = tmp13 / tmp15
tmp17 = tmp16 + tmp4
tmp18 = 2.0
tmp19 = tmp5 * tmp18
tmp20 = tmp17 / tmp19
tmp21 = tmp20 + tmp4
tmp22 = tmp21 / tmp5
tmp23 = tmp0 * tmp0
tmp24 = tmp2 / tmp23
tmp25 = tmp22 + tmp24
tmp26 = tmp3 - tmp25
tmp27 = tmp1 / tmp26
tmp28 = tmp0 - tmp27
tmp29 = tl_math.log(tmp28)
tmp31 = tmp29 - tmp30
tmp33 = 1e-07
tmp34 = tmp32 + tmp33
tmp36 = tmp35 + tmp33
tmp37 = tmp34 + tmp36
tmp39 = tmp38 + tmp33
tmp40 = tmp37 + tmp39
tmp42 = tmp41 + tmp33
tmp43 = tmp40 + tmp42
tmp44 = 4.0
tmp45 = tmp43 / tmp44
tmp46 = tl_math.log(tmp45)
tmp47 = tl_math.log(tmp34)
tmp48 = tl_math.log(tmp36)
tmp49 = tmp47 + tmp48
tmp50 = tl_math.log(tmp39)
tmp51 = tmp49 + tmp50
tmp52 = tl_math.log(tmp42)
tmp53 = tmp51 + tmp52
tmp54 = tmp53 / tmp44
tmp55 = tmp46 - tmp54
tmp56 = tmp31 - tmp55
tmp58 = tmp2 / tmp57
tmp59 = tmp57 + tmp4
tmp60 = tmp59 * tmp59
tmp61 = tmp60 * tmp7
tmp62 = tmp2 / tmp61
tmp63 = tmp10 - tmp62
tmp64 = tmp63 / tmp60
tmp65 = tmp4 - tmp64
tmp66 = tmp59 * tmp14
tmp67 = tmp65 / tmp66
tmp68 = tmp67 + tmp4
tmp69 = tmp59 * tmp18
tmp70 = tmp68 / tmp69
tmp71 = tmp70 + tmp4
tmp72 = tmp71 / tmp59
tmp73 = tmp57 * tmp57
tmp74 = tmp2 / tmp73
tmp75 = tmp72 + tmp74
tmp76 = tmp58 - tmp75
tmp77 = tmp56 / tmp76
tmp78 = tmp57 - tmp77
tl.store(in_out_ptr0 + x0, tmp77, xmask)
tl.store(out_ptr0 + x0, tmp78, xmask)
@triton.jit
def triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_4(in_out_ptr0
, 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
x1 = xindex % 16
x2 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp30 = tl.load(in_ptr1 + x0, xmask)
tmp32 = tl.load(in_ptr2 + (x1 + 64 * x2), xmask)
tmp35 = tl.load(in_ptr2 + (16 + x1 + 64 * x2), xmask)
tmp38 = tl.load(in_ptr2 + (32 + x1 + 64 * x2), xmask)
tmp41 = tl.load(in_ptr2 + (48 + x1 + 64 * x2), xmask)
tmp57 = tl.load(in_ptr3 + x0, xmask)
tmp2 = tl.full([1], 1, tl.int32)
tmp3 = tmp2 / tmp0
tmp4 = 1.0
tmp5 = tmp0 + tmp4
tmp6 = tmp5 * tmp5
tmp7 = 7.0
tmp8 = tmp6 * tmp7
tmp9 = tmp2 / tmp8
tmp10 = 0.2
tmp11 = tmp10 - tmp9
tmp12 = tmp11 / tmp6
tmp13 = tmp4 - tmp12
tmp14 = 3.0
tmp15 = tmp5 * tmp14
tmp16 = tmp13 / tmp15
tmp17 = tmp16 + tmp4
tmp18 = 2.0
tmp19 = tmp5 * tmp18
tmp20 = tmp17 / tmp19
tmp21 = tmp20 + tmp4
tmp22 = tmp21 / tmp5
tmp23 = tmp0 * tmp0
tmp24 = tmp2 / tmp23
tmp25 = tmp22 + tmp24
tmp26 = tmp3 - tmp25
tmp27 = tmp1 / tmp26
tmp28 = tmp0 - tmp27
tmp29 = tl_math.log(tmp28)
tmp31 = tmp29 - tmp30
tmp33 = 1e-07
tmp34 = tmp32 + tmp33
tmp36 = tmp35 + tmp33
tmp37 = tmp34 + tmp36
tmp39 = tmp38 + tmp33
tmp40 = tmp37 + tmp39
tmp42 = tmp41 + tmp33
tmp43 = tmp40 + tmp42
tmp44 = 4.0
tmp45 = tmp43 / tmp44
tmp46 = tl_math.log(tmp45)
tmp47 = tl_math.log(tmp34)
tmp48 = tl_math.log(tmp36)
tmp49 = tmp47 + tmp48
tmp50 = tl_math.log(tmp39)
tmp51 = tmp49 + tmp50
tmp52 = tl_math.log(tmp42)
tmp53 = tmp51 + tmp52
tmp54 = tmp53 / tmp44
tmp55 = tmp46 - tmp54
tmp56 = tmp31 - tmp55
tmp58 = tmp2 / tmp57
tmp59 = tmp57 + tmp4
tmp60 = tmp59 * tmp59
tmp61 = tmp60 * tmp7
tmp62 = tmp2 / tmp61
tmp63 = tmp10 - tmp62
tmp64 = tmp63 / tmp60
tmp65 = tmp4 - tmp64
tmp66 = tmp59 * tmp14
tmp67 = tmp65 / tmp66
tmp68 = tmp67 + tmp4
tmp69 = tmp59 * tmp18
tmp70 = tmp68 / tmp69
tmp71 = tmp70 + tmp4
tmp72 = tmp71 / tmp59
tmp73 = tmp57 * tmp57
tmp74 = tmp2 / tmp73
tmp75 = tmp72 + tmp74
tmp76 = tmp58 - tmp75
tmp77 = tmp56 / tmp76
tmp78 = tmp57 - tmp77
tl.store(in_out_ptr0 + x0, tmp77, xmask)
tl.store(out_ptr0 + x0, tmp78, xmask)
@triton.jit
def triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_5(in_out_ptr0
, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr1 + x2, xmask)
tmp6 = tl.load(in_ptr2 + (x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr2 + (16 + x0 + 64 * x1), xmask)
tmp12 = tl.load(in_ptr2 + (32 + x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr2 + (48 + x0 + 64 * x1), xmask)
tmp31 = tl.load(in_out_ptr1 + x2, xmask)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.log(tmp2)
tmp5 = tmp3 - tmp4
tmp7 = 1e-07
tmp8 = tmp6 + tmp7
tmp10 = tmp9 + tmp7
tmp11 = tmp8 + tmp10
tmp13 = tmp12 + tmp7
tmp14 = tmp11 + tmp13
tmp16 = tmp15 + tmp7
tmp17 = tmp14 + tmp16
tmp18 = 4.0
tmp19 = tmp17 / tmp18
tmp20 = tl_math.log(tmp19)
tmp21 = tl_math.log(tmp8)
tmp22 = tl_math.log(tmp10)
tmp23 = tmp21 + tmp22
tmp24 = tl_math.log(tmp13)
tmp25 = tmp23 + tmp24
tmp26 = tl_math.log(tmp16)
tmp27 = tmp25 + tmp26
tmp28 = tmp27 / tmp18
tmp29 = tmp20 - tmp28
tmp30 = tmp5 - tmp29
tmp32 = tl.full([1], 1, tl.int32)
tmp33 = tmp32 / tmp31
tmp34 = 1.0
tmp35 = tmp31 + tmp34
tmp36 = tmp35 * tmp35
tmp37 = 7.0
tmp38 = tmp36 * tmp37
tmp39 = tmp32 / tmp38
tmp40 = 0.2
tmp41 = tmp40 - tmp39
tmp42 = tmp41 / tmp36
tmp43 = tmp34 - tmp42
tmp44 = 3.0
tmp45 = tmp35 * tmp44
tmp46 = tmp43 / tmp45
tmp47 = tmp46 + tmp34
tmp48 = 2.0
tmp49 = tmp35 * tmp48
tmp50 = tmp47 / tmp49
tmp51 = tmp50 + tmp34
tmp52 = tmp51 / tmp35
tmp53 = tmp31 * tmp31
tmp54 = tmp32 / tmp53
tmp55 = tmp52 + tmp54
tmp56 = tmp33 - tmp55
tmp57 = tmp30 / tmp56
tmp58 = tmp31 - tmp57
tmp59 = tmp32 / tmp58
tmp60 = tmp59 * tmp19
tl.store(in_out_ptr1 + x2, tmp60, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_log_mean_mul_pow_rsub_sqrt_sub_0[grid(64)](
buf1, arg0_1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = torch.ops.aten.digamma.default(buf2)
buf4 = buf3
del buf3
buf5 = buf1
del buf1
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_1[grid
(64)](buf5, buf4, arg0_1, buf2, buf6, 64, XBLOCK=64, num_warps=
1, num_stages=1)
buf7 = torch.ops.aten.digamma.default(buf6)
buf8 = buf7
del buf7
buf9 = buf2
del buf2
buf10 = buf4
del buf4
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_2[grid
(64)](buf9, buf5, buf8, arg0_1, buf6, buf10, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf5
buf11 = torch.ops.aten.digamma.default(buf10)
buf12 = buf11
del buf11
buf13 = buf12
del buf12
buf14 = buf13
del buf13
buf15 = buf8
del buf8
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_3[grid
(64)](buf14, buf6, buf9, arg0_1, buf10, buf15, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf6
buf16 = torch.ops.aten.digamma.default(buf15)
buf17 = buf16
del buf16
buf18 = buf10
del buf10
buf19 = buf9
del buf9
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_2[grid
(64)](buf18, buf14, buf17, arg0_1, buf15, buf19, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf14
buf20 = torch.ops.aten.digamma.default(buf19)
buf21 = buf20
del buf20
buf22 = buf15
del buf15
buf23 = buf22
del buf22
buf24 = buf17
del buf17
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_4[grid
(64)](buf23, buf18, buf21, arg0_1, buf19, buf24, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf18
buf25 = torch.ops.aten.digamma.default(buf24)
buf26 = buf25
del buf25
buf27 = buf19
del buf19
buf28 = buf21
del buf21
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_2[grid
(64)](buf27, buf23, buf26, arg0_1, buf24, buf28, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf23
buf29 = torch.ops.aten.digamma.default(buf28)
buf30 = buf29
del buf29
buf31 = buf24
del buf24
buf32 = buf31
del buf31
buf33 = buf26
del buf26
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_4[grid
(64)](buf32, buf27, buf30, arg0_1, buf28, buf33, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf27
buf34 = torch.ops.aten.digamma.default(buf33)
buf35 = buf34
del buf34
buf36 = buf28
del buf28
buf37 = buf30
del buf30
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_2[grid
(64)](buf36, buf32, buf35, arg0_1, buf33, buf37, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf32
buf38 = torch.ops.aten.digamma.default(buf37)
buf39 = buf38
del buf38
buf40 = buf33
del buf33
buf41 = buf40
del buf40
buf42 = buf35
del buf35
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_4[grid
(64)](buf41, buf36, buf39, arg0_1, buf37, buf42, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf36
del buf39
buf43 = torch.ops.aten.digamma.default(buf42)
buf44 = buf43
del buf43
buf45 = buf37
del buf37
buf46 = buf42
del buf42
triton_poi_fused_add_div_log_mean_mul_pow_reciprocal_rsub_sub_5[grid
(64)](buf45, buf46, buf41, buf44, arg0_1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
del buf41
del buf44
del buf45
return buf46,
class GammaScaleMapNew(nn.Module):
"""
Compute Gamma Scale on a 4D tensor (The hard way). This acts as a standard PyTorch layer.
Gamma Scale is computed independantly for each batch item at each location x,y
Input should be:
(1) A tensor of size [batch x channels x height x width]
(2) A tensor with only positive values. (After a ReLU)
Output is a 3D tensor of size [batch x height x width]
"""
def __init__(self, run_relu=False):
super(GammaScaleMapNew, self).__init__()
"""
SMOE Scale must take in values > 0. Optionally, we can run a ReLU to do that.
"""
if run_relu:
self.relu = nn.ReLU(inplace=False)
else:
self.relu = None
def _trigamma(self, x):
"""
We need this line since recursion is not good for x < 1.0
Note that we take + torch.reciprocal(x.pow(2)) at the end because:
trigamma(z) = trigamma(z + 1) + 1/z^2
"""
z = x + 1.0
zz = z.pow(2)
a = 0.2 - torch.reciprocal(7.0 * zz)
b = 1.0 - a / zz
c = 1.0 + b / (3.0 * z)
d = 1.0 + c / (2.0 * z)
e = d / z
e = e + torch.reciprocal(x.pow(2.0))
return e
def _k_update(self, k, s):
nm = torch.log(k) - torch.digamma(k) - s
dn = torch.reciprocal(k) - self._trigamma(k)
k2 = k - nm / dn
return k2
def _compute_k_est(self, x, i=10, dim=1):
"""
Calculate s
"""
s = torch.log(torch.mean(x, dim=dim)) - torch.mean(torch.log(x),
dim=dim)
"""
Get estimate of k to within 1.5%
NOTE: K gets smaller as log variance s increases
"""
s3 = s - 3.0
rt = torch.sqrt(s3.pow(2) + 24.0 * s)
nm = 3.0 - s + rt
dn = 12.0 * s
k = nm / dn + 1e-07
"""
Do i Newton-Raphson steps to get closer than 1.5%
For i=5 gets us within 4 or 5 decimal places
"""
for _ in range(i):
k = self._k_update(k, s)
return k
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
GammaScaleMap
| false
| 8,434
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
L2Norm
|
import torch
from math import sqrt as sqrt
from itertools import product as product
import torch.nn as nn
import torch.nn.init as init
class L2Norm(nn.Module):
def __init__(self, n_channels, scale):
super(L2Norm, self).__init__()
self.n_channels = n_channels
self.gamma = scale or None
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.reset_parameters()
def reset_parameters(self):
init.constant(self.weight, self.gamma)
def forward(self, x):
norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.eps
x /= norm
out = self.weight.unsqueeze(0).unsqueeze(2).unsqueeze(3).expand_as(x
) * x
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_channels': 4, 'scale': 1.0}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from math import sqrt as sqrt
from itertools import product as product
import torch.nn as nn
import torch.nn.init as init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mul_pow_sqrt_sum_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-10
tmp14 = tmp12 + tmp13
tmp15 = tmp0 / tmp14
tmp17 = tmp16 * tmp15
tl.store(out_ptr0 + x3, tmp15, xmask)
tl.store(out_ptr1 + x3, tmp17, xmask)
tl.store(out_ptr2 + x3, tmp15, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mul_pow_sqrt_sum_0[grid(256)](primals_1,
primals_2, buf0, buf1, primals_1, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_1
del primals_2
return buf1, buf0
class L2NormNew(nn.Module):
def __init__(self, n_channels, scale):
super(L2NormNew, self).__init__()
self.n_channels = n_channels
self.gamma = scale or None
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.reset_parameters()
def reset_parameters(self):
init.constant(self.weight, self.gamma)
def forward(self, input_0):
primals_2 = self.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
Kalana304/realtime-action-detection
|
L2Norm
| false
| 8,435
|
[
"MIT"
] | 26
|
a40178c749d60c135290c40a8ac658bac253f0d4
|
https://github.com/Kalana304/realtime-action-detection/tree/a40178c749d60c135290c40a8ac658bac253f0d4
|
AdaptiveInstanceNorm
|
import torch
import torch.nn as nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaptiveInstanceNorm(nn.Module):
def __init__(self, in_channel, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channel)
self.style = EqualLinear(style_dim, in_channel * 2)
self.style.linear.bias.data[:in_channel] = 1
self.style.linear.bias.data[in_channel:] = 0
def forward(self, input, style):
style = self.style(style).unsqueeze(2).unsqueeze(3)
gamma, beta = style.chunk(chunks=2, dim=1)
out = self.norm(input)
out = gamma * out + beta
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channel': 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
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from math 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_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_mul_1(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp22 = tl.load(in_ptr1 + (x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr1 + (4 + x2 + 8 * x3), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr2 + (4 + x2), xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = 16.0
tmp18 = tmp16 / tmp17
tmp19 = 1e-05
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tmp24 = tmp22 + tmp23
tmp25 = tmp0 - tmp10
tmp26 = tmp25 * tmp21
tmp27 = tmp24 * tmp26
tmp30 = tmp28 + tmp29
tmp31 = tmp27 + tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp21, xmask)
tl.store(out_ptr1 + (r1 + 16 * x0), tmp31, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (8, 4), (4, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((8, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(32)](primals_1, buf0, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(buf0, (4, 8), (1, 4
), 0), out=buf1)
buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 1, 1), torch.float32)
buf3 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf5 = reinterpret_tensor(buf3, (1, 16, 1, 1), (16, 1, 1, 1), 0)
del buf3
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused__native_batch_norm_legit_add_mul_1[grid(16)](buf5,
primals_4, buf1, primals_2, buf2, buf6, 16, 16, XBLOCK=8,
num_warps=2, num_stages=1)
del buf1
del primals_2
return buf6, buf0, primals_3, primals_4, buf2, buf5
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaptiveInstanceNormNew(nn.Module):
def __init__(self, in_channel, style_dim):
super().__init__()
self.norm = nn.InstanceNorm2d(in_channel)
self.style = EqualLinear(style_dim, in_channel * 2)
self.style.linear.bias.data[:in_channel] = 1
self.style.linear.bias.data[in_channel:] = 0
def forward(self, input_0, input_1):
primals_2 = self.style.linear.bias
primals_1 = self.style.linear.weight_orig
primals_4 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
KwonGihyun/DiagonalGAN
|
AdaptiveInstanceNorm
| false
| 8,437
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
AdaptiveAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaptiveAttention(nn.Module):
def __init__(self, img_dim, style_dim):
super().__init__()
self.img_dim = img_dim
self.fc = EqualLinear(style_dim, img_dim ** 2)
self.gamma = nn.Parameter(torch.ones(1, 1, 1, 1))
def forward(self, x, p):
h = self.fc(p)
h = h.view(h.size(0), 1, self.img_dim, self.img_dim)
h = F.sigmoid(h)
return self.gamma * (h * x) + x
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'img_dim': 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 torch.nn as nn
from math 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_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.sigmoid(tmp2)
tmp5 = tmp3 * tmp4
tmp6 = tmp1 * tmp5
tmp7 = tmp6 + tmp4
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, (16, 4), (4, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (1, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_2, primals_3, reinterpret_tensor(buf0,
(4, 16), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_1[grid(64)](primals_4, buf1,
primals_5, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
return buf2, buf0, primals_3, primals_4, primals_5, buf1
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
class AdaptiveAttentionNew(nn.Module):
def __init__(self, img_dim, style_dim):
super().__init__()
self.img_dim = img_dim
self.fc = EqualLinear(style_dim, img_dim ** 2)
self.gamma = nn.Parameter(torch.ones(1, 1, 1, 1))
def forward(self, input_0, input_1):
primals_4 = self.gamma
primals_2 = self.fc.linear.bias
primals_1 = self.fc.linear.weight_orig
primals_3 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
KwonGihyun/DiagonalGAN
|
AdaptiveAttention
| false
| 8,438
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
ConvTemporalGraphical
|
import torch
import torch.nn as nn
class ConvTemporalGraphical(nn.Module):
"""The basic module for applying a graph convolution.
Args:
in_channels (int): Number of channels in the input sequence data
out_channels (int): Number of channels produced by the convolution
kernel_size (int): Size of the graph convolving kernel
t_kernel_size (int): Size of the temporal convolving kernel
t_stride (int, optional): Stride of the temporal convolution. Default: 1
t_padding (int, optional): Temporal zero-padding added to both sides of
the input. Default: 0
t_dilation (int, optional): Spacing between temporal kernel elements.
Default: 1
bias (bool, optional): If ``True``, adds a learnable bias to the output.
Default: ``True``
Shape:
- Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format
- Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format
- Output[0]: Outpu graph sequence in :math:`(N, out_channels, T_{out}, V)` format
- Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format
where
:math:`N` is a batch size,
:math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`,
:math:`T_{in}/T_{out}` is a length of input/output sequence,
:math:`V` is the number of graph nodes.
"""
def __init__(self, in_channels, out_channels, kernel_size,
t_kernel_size=1, t_stride=1, t_padding=0, t_dilation=1, bias=True):
super().__init__()
self.kernel_size = kernel_size
self.conv = nn.Conv2d(in_channels, out_channels * kernel_size,
kernel_size=(t_kernel_size, 1), padding=(t_padding, 0), stride=
(t_stride, 1), dilation=(t_dilation, 1), bias=bias)
def forward(self, x, A):
assert A.size(0) == self.kernel_size
x = self.conv(x)
n, kc, t, v = x.size()
x = x.view(n, self.kernel_size, kc // self.kernel_size, t, v)
x = torch.einsum('nkctv,kvw->nctw', (x, A))
return x.contiguous(), A
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([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
assert_size_stride = torch._C._dynamo.guards.assert_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 = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x4 = xindex // 256
x5 = xindex // 16 % 16
x3 = xindex // 64 % 4
x6 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x5 + 64 * x1 + 256 * x4), xmask)
tmp1 = tl.load(in_ptr1 + (x3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x6, tmp2, 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, (16, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (16,), (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 = extern_kernels.convolution(primals_4, primals_2, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 16, 4, 4), (256, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 4, 4, 1), (256, 64, 16, 4, 1, 1
), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(1024)](buf0, primals_3, buf1, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_3
buf2 = empty_strided_cuda((1, 64, 4), (256, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (1, 64, 16), (0, 16, 1),
0), reinterpret_tensor(primals_1, (1, 16, 4), (64, 4, 1), 0),
out=buf2)
del buf1
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_2, primals_4, reinterpret_tensor(primals_1, (1, 4, 16),
(64, 1, 4), 0)
class ConvTemporalGraphicalNew(nn.Module):
"""The basic module for applying a graph convolution.
Args:
in_channels (int): Number of channels in the input sequence data
out_channels (int): Number of channels produced by the convolution
kernel_size (int): Size of the graph convolving kernel
t_kernel_size (int): Size of the temporal convolving kernel
t_stride (int, optional): Stride of the temporal convolution. Default: 1
t_padding (int, optional): Temporal zero-padding added to both sides of
the input. Default: 0
t_dilation (int, optional): Spacing between temporal kernel elements.
Default: 1
bias (bool, optional): If ``True``, adds a learnable bias to the output.
Default: ``True``
Shape:
- Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format
- Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format
- Output[0]: Outpu graph sequence in :math:`(N, out_channels, T_{out}, V)` format
- Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format
where
:math:`N` is a batch size,
:math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`,
:math:`T_{in}/T_{out}` is a length of input/output sequence,
:math:`V` is the number of graph nodes.
"""
def __init__(self, in_channels, out_channels, kernel_size,
t_kernel_size=1, t_stride=1, t_padding=0, t_dilation=1, bias=True):
super().__init__()
self.kernel_size = kernel_size
self.conv = nn.Conv2d(in_channels, out_channels * kernel_size,
kernel_size=(t_kernel_size, 1), padding=(t_padding, 0), stride=
(t_stride, 1), dilation=(t_dilation, 1), bias=bias)
def forward(self, input_0, input_1):
primals_2 = self.conv.weight
primals_3 = self.conv.bias
primals_4 = input_0
primals_1 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
Levigty/AimCLR
|
ConvTemporalGraphical
| false
| 8,439
|
[
"MIT"
] | 25
|
6cd73767f17748792508647355fa324fa63e235d
|
https://github.com/Levigty/AimCLR/tree/6cd73767f17748792508647355fa324fa63e235d
|
DropBlockT_1d
|
import torch
import torch.nn as nn
class DropBlockT_1d(nn.Module):
def __init__(self, keep_prob=0.9):
super(DropBlockT_1d, self).__init__()
self.keep_prob = keep_prob
def forward(self, input, mask):
n, c, t, v = input.size()
input1 = input.permute(0, 1, 3, 2).contiguous().view(n, c * v, t)
mask[mask >= self.keep_prob] = 2.0
mask[mask < self.keep_prob] = 1.0
mask[mask == 2.0] = 0.0
return (input1 * mask * mask.numel() / mask.sum()).view(n, c, v, t
).permute(0, 1, 3, 2)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 16, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_index_put_lift_fresh_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.9
tmp2 = tmp0 >= tmp1
tmp3 = 2.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.9
tmp2 = tmp0 < tmp1
tmp3 = 1.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_per_fused_index_put_lift_fresh_sum_2(in_ptr0, out_ptr0, out_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 2.0
tmp2 = tmp0 == tmp1
tmp3 = 0.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tl.store(out_ptr0 + tl.broadcast_to(r0, [RBLOCK]), tmp4, None)
tl.store(out_ptr1 + tl.full([1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_poi_fused_div_mul_3(in_ptr0, in_ptr1, in_ptr2, 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 + (4 * x2 + 16 * (y0 // 4) + 64 * y1 + y0 % 4),
xmask & ymask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr2 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, YBLOCK])
tmp2 = tmp0 * tmp1
tmp3 = 256.0
tmp4 = tmp2 * tmp3
tmp7 = tmp4 / tmp6
tl.store(out_ptr0 + (x2 + 4 * y3), tmp7, 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, 16, 4), (64, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
get_raw_stream(0)
triton_poi_fused_index_put_lift_fresh_0[grid(256)](arg1_1, arg1_1,
256, XBLOCK=128, num_warps=4, num_stages=1)
triton_poi_fused_index_put_lift_fresh_1[grid(256)](arg1_1, arg1_1,
256, XBLOCK=256, num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_index_put_lift_fresh_sum_2[grid(1)](arg1_1, arg1_1,
buf6, 1, 256, num_warps=2, num_stages=1)
buf7 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
triton_poi_fused_div_mul_3[grid(64, 4)](arg0_1, arg1_1, buf6, buf7,
64, 4, XBLOCK=4, YBLOCK=64, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
del buf6
return reinterpret_tensor(buf7, (4, 4, 4, 4), (64, 16, 1, 4), 0),
class DropBlockT_1dNew(nn.Module):
def __init__(self, keep_prob=0.9):
super(DropBlockT_1dNew, self).__init__()
self.keep_prob = keep_prob
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Levigty/AimCLR
|
DropBlockT_1d
| false
| 8,440
|
[
"MIT"
] | 25
|
6cd73767f17748792508647355fa324fa63e235d
|
https://github.com/Levigty/AimCLR/tree/6cd73767f17748792508647355fa324fa63e235d
|
GaussNorm2D
|
import torch
import torch.nn as nn
import torch.autograd
class GaussNorm2D(nn.Module):
"""
This will normalize a saliency map to range from 0 to 1 via normal cumulative distribution function.
Input and output will be a 3D tensor of size [batch size x height x width].
Input can be any real valued number (supported by hardware)
Output will range from 0 to 1
Notes:
(1) GammaNorm2D will produce slightly better results
The sum ROAR/KAR will improve from 1.44 to 1.45 for FastCAM using GradCAM.
(2) This method is a bit less expensive than GammaNorm2D.
"""
def __init__(self, const_mean=None, const_std=None):
super(GaussNorm2D, self).__init__()
assert isinstance(const_mean, float) or const_mean is None
assert isinstance(const_std, float) or const_std is None
self.const_mean = const_mean
self.const_std = const_std
def forward(self, x):
"""
Input:
x: A Torch Tensor image with shape [batch size x height x width] e.g. [64,7,7]
Return:
x: x Normalized by computing mean and std over each individual batch item and squashed with a
Normal/Gaussian CDF.
"""
assert torch.is_tensor(x), 'Input must be a Torch Tensor'
assert len(x.size()
) == 3, 'Input should be sizes [batch size x height x width]'
s0 = x.size()[0]
s1 = x.size()[1]
s2 = x.size()[2]
x = x.reshape(s0, s1 * s2)
"""
Compute Mean
"""
if self.const_mean is None:
m = x.mean(dim=1)
m = m.reshape(m.size()[0], 1)
else:
m = self.const_mean
"""
Compute Standard Deviation
"""
if self.const_std is None:
s = x.std(dim=1)
s = s.reshape(s.size()[0], 1)
else:
s = self.const_std
"""
The normal cumulative distribution function is used to squash the values from within the range of 0 to 1
"""
x = 0.5 * (1.0 + torch.erf((x - m) / (s * torch.sqrt(torch.tensor(
2.0)))))
x = x.reshape(s0, s1, s2)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_erf_mean_mul_sqrt_std_sub_0(in_ptr0, out_ptr2,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 16.0
tmp20 = tmp4 / tmp19
tmp21 = tmp0 - tmp20
tmp22 = 15.0
tmp23 = tmp18 / tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = 1.4142135381698608
tmp26 = tmp24 * tmp25
tmp27 = tmp21 / tmp26
tmp28 = libdevice.erf(tmp27)
tmp29 = 1.0
tmp30 = tmp28 + tmp29
tmp31 = 0.5
tmp32 = tmp30 * tmp31
tl.store(out_ptr2 + (r1 + 16 * x0), tmp32, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf4 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_erf_mean_mul_sqrt_std_sub_0[grid(4)](arg0_1,
buf4, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
return reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0),
class GaussNorm2DNew(nn.Module):
"""
This will normalize a saliency map to range from 0 to 1 via normal cumulative distribution function.
Input and output will be a 3D tensor of size [batch size x height x width].
Input can be any real valued number (supported by hardware)
Output will range from 0 to 1
Notes:
(1) GammaNorm2D will produce slightly better results
The sum ROAR/KAR will improve from 1.44 to 1.45 for FastCAM using GradCAM.
(2) This method is a bit less expensive than GammaNorm2D.
"""
def __init__(self, const_mean=None, const_std=None):
super(GaussNorm2DNew, self).__init__()
assert isinstance(const_mean, float) or const_mean is None
assert isinstance(const_std, float) or const_std is None
self.const_mean = const_mean
self.const_std = const_std
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LLNL/fastcam
|
GaussNorm2D
| false
| 8,441
|
[
"BSD-3-Clause"
] | 25
|
99cefe37528014247319468cf05f54fef259d3bf
|
https://github.com/LLNL/fastcam/tree/99cefe37528014247319468cf05f54fef259d3bf
|
FirstNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class FirstNet(nn.Module):
def __init__(self):
super(FirstNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=
3, padding=1, stride=1)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = F.max_pool2d(x, 2, 2)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2, 2)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
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_1(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 256
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (y0 + 64 * x2 + 262144 * y1), tmp4, ymask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_2(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 64
x1 = xindex // 64 % 32
x2 = xindex // 2048
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x1 + 8192 * x2), None)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 128 * x1 + 8192 * x2), None)
tmp3 = tl.load(in_ptr0 + (4096 + x0 + 128 * x1 + 8192 * x2), None)
tmp5 = tl.load(in_ptr0 + (4160 + x0 + 128 * x1 + 8192 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_4(in_ptr0, out_ptr0, out_ptr1,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 128
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
x3 = xindex
y0 = yindex % 16
y4 = yindex // 16
y2 = yindex // 256
y5 = yindex % 256
y6 = yindex
tmp0 = tl.load(in_ptr0 + (x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (128 + x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (4096 + x3 + 256 * y0 + 8192 * y4), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (4224 + x3 + 256 * y0 + 8192 * y4), 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], 1, tl.int8)
tmp9 = tl.full([1, 1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1, 1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1, 1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (y5 + 256 * x3 + 32768 * y2), tmp6, xmask)
tl.store(out_ptr1 + (x3 + 128 * y6), tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (64, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (128,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(8192, 9)](primals_4, buf0, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf1 = 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(buf1, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf2 = empty_strided_cuda((4, 64, 64, 64), (262144, 1, 4096, 64),
torch.float32)
triton_poi_fused_convolution_relu_1[grid(256, 4096)](buf1,
primals_2, buf2, 256, 4096, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
del buf1
del primals_2
buf3 = empty_strided_cuda((4, 64, 32, 32), (65536, 1, 2048, 64),
torch.float32)
buf4 = empty_strided_cuda((4, 64, 32, 32), (65536, 1, 2048, 64),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_2[grid(262144)](buf2, buf3,
buf4, 262144, XBLOCK=512, num_warps=8, num_stages=1)
buf5 = extern_kernels.convolution(buf3, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 128, 32, 32), (131072, 1, 4096, 128))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_3[grid(524288)](buf6, primals_5,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf7 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.float32)
buf8 = empty_strided_cuda((4, 128, 16, 16), (32768, 1, 2048, 128),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_4[grid(1024, 128)](buf6,
buf7, buf8, 1024, 128, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
return buf7, primals_1, primals_3, buf0, buf2, buf3, buf4, buf6, buf8
class FirstNetNew(nn.Module):
def __init__(self):
super(FirstNetNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=
3, padding=1, stride=1)
self.conv2 = nn.Conv2d(64, 128, 3, padding=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]
|
Koukyosyumei/AIJack
|
FirstNet
| false
| 8,442
|
[
"MIT"
] | 24
|
9545d3828907b54965ede85e0e12cb32eef54294
|
https://github.com/Koukyosyumei/AIJack/tree/9545d3828907b54965ede85e0e12cb32eef54294
|
FusedDownsample
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
class FusedDownsample(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, padding=0):
super().__init__()
weight = torch.randn(out_channel, in_channel, kernel_size, kernel_size)
bias = torch.zeros(out_channel)
fan_in = in_channel * kernel_size * kernel_size
self.multiplier = sqrt(2 / fan_in)
self.weight = nn.Parameter(weight)
self.bias = nn.Parameter(bias)
self.pad = padding
def forward(self, input):
weight = F.pad(self.weight * self.multiplier, [1, 1, 1, 1])
weight = (weight[:, :, 1:, 1:] + weight[:, :, :-1, 1:] + weight[:,
:, 1:, :-1] + weight[:, :, :-1, :-1]) / 4
out = F.conv2d(input, weight, self.bias, stride=2, padding=self.pad)
return out
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 5 % 5
x0 = xindex % 5
x2 = xindex // 25
x4 = xindex
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp10 & xmask, other=0.0
)
tmp12 = 0.1767766952966369
tmp13 = tmp11 * tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp10, tmp13, tmp14)
tmp16 = -1 + x1
tmp17 = tmp16 >= tmp1
tmp18 = tmp16 < tmp3
tmp19 = tmp17 & tmp18
tmp20 = tmp19 & tmp6
tmp21 = tmp20 & tmp7
tmp22 = tl.load(in_ptr0 + (-4 + x0 + 4 * x1 + 16 * x2), tmp21 & xmask,
other=0.0)
tmp23 = tmp22 * tmp12
tmp24 = tl.full(tmp23.shape, 0.0, tmp23.dtype)
tmp25 = tl.where(tmp21, tmp23, tmp24)
tmp26 = tmp15 + tmp25
tmp27 = -1 + x0
tmp28 = tmp27 >= tmp1
tmp29 = tmp27 < tmp3
tmp30 = tmp8 & tmp28
tmp31 = tmp30 & tmp29
tmp32 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1 + 16 * x2), tmp31 & xmask,
other=0.0)
tmp33 = tmp32 * tmp12
tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype)
tmp35 = tl.where(tmp31, tmp33, tmp34)
tmp36 = tmp26 + tmp35
tmp37 = tmp19 & tmp28
tmp38 = tmp37 & tmp29
tmp39 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp38 & xmask,
other=0.0)
tmp40 = tmp39 * tmp12
tmp41 = tl.full(tmp40.shape, 0.0, tmp40.dtype)
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp36 + tmp42
tmp44 = 0.25
tmp45 = tmp43 * tmp44
tl.store(in_out_ptr0 + x4, tmp45, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 14400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 900 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 64, 64), (16384, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_div_0[grid(400)](buf1, primals_1, 400, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_1
buf2 = extern_kernels.convolution(primals_3, buf1, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 30, 30), (3600, 900, 30, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(14400)](buf3, primals_2, 14400,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf3, primals_3, buf1
class FusedDownsampleNew(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, padding=0):
super().__init__()
weight = torch.randn(out_channel, in_channel, kernel_size, kernel_size)
bias = torch.zeros(out_channel)
fan_in = in_channel * kernel_size * kernel_size
self.multiplier = sqrt(2 / fan_in)
self.weight = nn.Parameter(weight)
self.bias = nn.Parameter(bias)
self.pad = padding
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]
|
KwonGihyun/DiagonalGAN
|
FusedDownsample
| false
| 8,443
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
AttentionCrossEntropy
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class AttentionCrossEntropy(nn.Module):
def __init__(self):
super(AttentionCrossEntropy, self).__init__()
def forward(self, input, target):
cross_loss = torch.mul(target.float(), F.log_softmax(input, dim=1))
loss = torch.neg(torch.mean(cross_loss))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_mean_mul_neg_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_ptr1 + r3, None)
tmp2 = tl.load(in_ptr1 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr1 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr1 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr1 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp3 = tl_math.exp(tmp2)
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp3 + tmp5
tmp8 = tl_math.exp(tmp7)
tmp9 = tmp6 + tmp8
tmp11 = tl_math.exp(tmp10)
tmp12 = tmp9 + tmp11
tmp13 = tl_math.log(tmp12)
tmp14 = tmp1 - tmp13
tmp15 = tmp0 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = 256.0
tmp20 = tmp18 / tmp19
tmp21 = -tmp20
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, 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_mean_mul_neg_1[grid(1)](buf2, arg0_1,
buf0, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class AttentionCrossEntropyNew(nn.Module):
def __init__(self):
super(AttentionCrossEntropyNew, 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]
|
LindgeW/sentiment-analysis-based-on-attention
|
AttentionCrossEntropy
| false
| 8,444
|
[
"Apache-2.0"
] | 13
|
82ea37c8ef84eec56082d60001b1179b4c12f416
|
https://github.com/LindgeW/sentiment-analysis-based-on-attention/tree/82ea37c8ef84eec56082d60001b1179b4c12f416
|
CausalConv1d
|
import torch
from torch import nn
class CausalConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=2, dilation=2):
super(CausalConv1d, self).__init__()
self.padding = dilation
self.causal_conv = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=self.padding, dilation=dilation)
def forward(self, minibatch):
return self.causal_conv(minibatch)[:, :, :-self.padding]
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 96
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 6 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,),
padding=(2,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 6), (24, 6, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(96)](buf1, primals_2, 96,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4), (24, 6, 1), 0
), primals_1, primals_3
class CausalConv1dNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=2, dilation=2):
super(CausalConv1dNew, self).__init__()
self.padding = dilation
self.causal_conv = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=self.padding, dilation=dilation)
def forward(self, input_0):
primals_1 = self.causal_conv.weight
primals_2 = self.causal_conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LittleGuoKe/Entity-Concept-enhanced-Few-shot-Relation-Extraction
|
CausalConv1d
| false
| 8,445
|
[
"MIT"
] | 19
|
b41386bdc70a3b84731bdbf700ff1ba4eda6675d
|
https://github.com/LittleGuoKe/Entity-Concept-enhanced-Few-shot-Relation-Extraction/tree/b41386bdc70a3b84731bdbf700ff1ba4eda6675d
|
MultiHeadAttention
|
import math
import torch
from torch import nn
from torch.nn import functional as F
from numpy import inf
from math import inf
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.0)
return m
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, d_qk, d_v, num_head):
super().__init__()
self.d_model = d_model
self.num_head = num_head
self.d_qk = d_qk
self.d_v = d_v
self.W_Q = Linear(d_model, num_head * d_qk)
self.W_K = Linear(d_model, num_head * d_qk)
self.W_V = Linear(d_model, num_head * d_v)
self.W_out = Linear(d_v * num_head, d_model)
def ScaledDotProductAttention(self, query, keys, values, mask=None):
score = torch.matmul(query, keys.transpose(-1, -2)) / math.sqrt(self
.d_model)
if mask is not None:
score.masked_fill_(mask.unsqueeze(1), -inf)
weight = F.softmax(score, dim=-1)
return torch.matmul(weight, values)
def forward(self, Q, K, V, mask=None):
batch_size = Q.size(0)
query = self.W_Q(Q).view(batch_size, Q.size(1), self.num_head, self
.d_qk)
keys = self.W_K(K).view(batch_size, K.size(1), self.num_head, self.d_qk
)
values = self.W_V(V).view(batch_size, V.size(1), self.num_head,
self.d_v)
query.transpose_(1, 2)
keys.transpose_(1, 2)
values.transpose_(1, 2)
outputs = self.ScaledDotProductAttention(query, keys, values, mask)
del query, keys, values
outputs = outputs.transpose(1, 2).contiguous().view(batch_size, -1,
self.d_v * self.num_head)
return self.W_out(outputs)
def cal_one_vector(self, vector, memory, memory_new, i):
batch_size = vector.size(0)
query = self.W_Q(vector).view(batch_size, vector.size(1), self.
num_head, self.d_qk)
key = self.W_K(vector).view(batch_size, vector.size(1), self.
num_head, self.d_qk)
value = self.W_V(vector).view(batch_size, vector.size(1), self.
num_head, self.d_v)
query.transpose_(1, 2)
key.transpose_(1, 2)
value.transpose_(1, 2)
outputs = torch.cat((key.unsqueeze(-1), value.unsqueeze(-1)), dim=-1)
del key, value
if memory is not None:
if memory_new is None:
memory_new = torch.cat((memory[:, i, ...], outputs), dim=2
).unsqueeze(1)
else:
_m = torch.cat((memory[:, i, ...], outputs), dim=2)
memory_new = torch.cat((memory_new, _m.unsqueeze(1)), dim=1)
elif memory_new is None:
memory_new = outputs.unsqueeze(1)
else:
memory_new = torch.cat((memory_new, outputs.unsqueeze(1)), dim=1)
outputs = self.ScaledDotProductAttention(query, memory_new[:, i,
..., 0], memory_new[:, i, ..., 1])
outputs = outputs.transpose(1, 2).contiguous().view(batch_size, -1,
self.d_v * self.num_head)
return self.W_out(outputs), memory_new
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'d_model': 4, 'd_qk': 4, 'd_v': 4, 'num_head': 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
from torch import nn
from torch.nn import functional as F
from numpy import inf
from math import inf
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (16, 4), (4, 1))
assert_size_stride(primals_3, (16,), (1,))
assert_size_stride(primals_4, (16, 4), (4, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (16, 4), (4, 1))
assert_size_stride(primals_8, (16,), (1,))
assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_10, (4, 16), (16, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (16,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (16,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(primals_9, (16,
4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf2)
del primals_7
del primals_8
buf3 = torch.ops.aten._scaled_dot_product_efficient_attention.default(
reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0),
reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0),
reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), None,
True, scale=0.5)
buf4 = buf3[0]
buf5 = buf3[1]
buf6 = buf3[2]
buf7 = buf3[3]
del buf3
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf4, buf8, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf8, (16, 16),
(16, 1), 0), reinterpret_tensor(primals_10, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf9)
del primals_11
return reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
), reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0
), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0
), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0
), buf4, buf5, buf6, buf7, reinterpret_tensor(buf8, (16, 16), (16,
1), 0), primals_10
def Linear(in_features, out_features, bias=True):
m = nn.Linear(in_features, out_features, bias)
nn.init.xavier_uniform_(m.weight)
if bias:
nn.init.constant_(m.bias, 0.0)
return m
class MultiHeadAttentionNew(nn.Module):
def __init__(self, d_model, d_qk, d_v, num_head):
super().__init__()
self.d_model = d_model
self.num_head = num_head
self.d_qk = d_qk
self.d_v = d_v
self.W_Q = Linear(d_model, num_head * d_qk)
self.W_K = Linear(d_model, num_head * d_qk)
self.W_V = Linear(d_model, num_head * d_v)
self.W_out = Linear(d_v * num_head, d_model)
def ScaledDotProductAttention(self, query, keys, values, mask=None):
score = torch.matmul(query, keys.transpose(-1, -2)) / math.sqrt(self
.d_model)
if mask is not None:
score.masked_fill_(mask.unsqueeze(1), -inf)
weight = F.softmax(score, dim=-1)
return torch.matmul(weight, values)
def cal_one_vector(self, vector, memory, memory_new, i):
batch_size = vector.size(0)
query = self.W_Q(vector).view(batch_size, vector.size(1), self.
num_head, self.d_qk)
key = self.W_K(vector).view(batch_size, vector.size(1), self.
num_head, self.d_qk)
value = self.W_V(vector).view(batch_size, vector.size(1), self.
num_head, self.d_v)
query.transpose_(1, 2)
key.transpose_(1, 2)
value.transpose_(1, 2)
outputs = torch.cat((key.unsqueeze(-1), value.unsqueeze(-1)), dim=-1)
del key, value
if memory is not None:
if memory_new is None:
memory_new = torch.cat((memory[:, i, ...], outputs), dim=2
).unsqueeze(1)
else:
_m = torch.cat((memory[:, i, ...], outputs), dim=2)
memory_new = torch.cat((memory_new, _m.unsqueeze(1)), dim=1)
elif memory_new is None:
memory_new = outputs.unsqueeze(1)
else:
memory_new = torch.cat((memory_new, outputs.unsqueeze(1)), dim=1)
outputs = self.ScaledDotProductAttention(query, memory_new[:, i,
..., 0], memory_new[:, i, ..., 1])
outputs = outputs.transpose(1, 2).contiguous().view(batch_size, -1,
self.d_v * self.num_head)
return self.W_out(outputs), memory_new
def forward(self, input_0, input_1, input_2):
primals_2 = self.W_Q.weight
primals_3 = self.W_Q.bias
primals_4 = self.W_K.weight
primals_5 = self.W_K.bias
primals_7 = self.W_V.weight
primals_8 = self.W_V.bias
primals_10 = self.W_out.weight
primals_11 = self.W_out.bias
primals_1 = input_0
primals_6 = input_1
primals_9 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
L-Zhe/FasySeq
|
MultiHeadAttention
| false
| 8,446
|
[
"Apache-2.0"
] | 34
|
2cd2abd290666b1e118d8ad11c973b58ca4f0573
|
https://github.com/L-Zhe/FasySeq/tree/2cd2abd290666b1e118d8ad11c973b58ca4f0573
|
DenseBlock
|
import torch
from torch import nn
from torch.nn import functional as F
class CausalConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=2, dilation=2):
super(CausalConv1d, self).__init__()
self.padding = dilation
self.causal_conv = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=self.padding, dilation=dilation)
def forward(self, minibatch):
return self.causal_conv(minibatch)[:, :, :-self.padding]
class DenseBlock(nn.Module):
def __init__(self, in_channels, filters, dilation=2):
super(DenseBlock, self).__init__()
self.causal_conv1 = CausalConv1d(in_channels, filters, dilation=
dilation)
self.causal_conv2 = CausalConv1d(in_channels, filters, dilation=
dilation)
def forward(self, minibatch):
tanh = F.tanh(self.causal_conv1(minibatch))
sig = F.sigmoid(self.causal_conv2(minibatch))
out = torch.cat([minibatch, tanh * sig], dim=1)
return out
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'filters': 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_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 96
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 6 % 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_cat_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 8
x0 = xindex % 4
x2 = xindex // 32
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 6 * (-4 + x1) + 24 * x2), tmp6 & xmask,
other=0.0)
tmp10 = libdevice.tanh(tmp9)
tmp11 = tl.load(in_ptr2 + (x0 + 6 * (-4 + x1) + 24 * x2), tmp6 & xmask,
other=0.0)
tmp12 = tl.sigmoid(tmp11)
tmp13 = tmp10 * tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp6, tmp13, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x3, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 2), (8, 2, 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, 2), (8, 2, 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,),
padding=(2,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 6), (24, 6, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(96)](buf1, primals_2, 96,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(primals_3, primals_4, stride=(1,),
padding=(2,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 6), (24, 6, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(96)](buf3, primals_5, 96,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 8, 4), (32, 4, 1), torch.float32)
triton_poi_fused_cat_1[grid(128)](primals_3, buf1, buf3, buf4, 128,
XBLOCK=128, num_warps=4, num_stages=1)
return buf4, primals_1, primals_3, primals_4, buf1, buf3
class CausalConv1d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=2, dilation=2):
super(CausalConv1d, self).__init__()
self.padding = dilation
self.causal_conv = nn.Conv1d(in_channels, out_channels, kernel_size,
padding=self.padding, dilation=dilation)
def forward(self, minibatch):
return self.causal_conv(minibatch)[:, :, :-self.padding]
class DenseBlockNew(nn.Module):
def __init__(self, in_channels, filters, dilation=2):
super(DenseBlockNew, self).__init__()
self.causal_conv1 = CausalConv1d(in_channels, filters, dilation=
dilation)
self.causal_conv2 = CausalConv1d(in_channels, filters, dilation=
dilation)
def forward(self, input_0):
primals_1 = self.causal_conv1.causal_conv.weight
primals_2 = self.causal_conv1.causal_conv.bias
primals_4 = self.causal_conv2.causal_conv.weight
primals_5 = self.causal_conv2.causal_conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
LittleGuoKe/Entity-Concept-enhanced-Few-shot-Relation-Extraction
|
DenseBlock
| false
| 8,447
|
[
"MIT"
] | 19
|
b41386bdc70a3b84731bdbf700ff1ba4eda6675d
|
https://github.com/LittleGuoKe/Entity-Concept-enhanced-Few-shot-Relation-Extraction/tree/b41386bdc70a3b84731bdbf700ff1ba4eda6675d
|
NoiseInjection
|
import torch
import torch.nn as nn
class NoiseInjection(nn.Module):
def __init__(self, channel):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))
def forward(self, image, noise):
return image + self.weight * noise
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'channel': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x3, xmask)
tmp3 = tmp1 * tmp2
tmp4 = tmp0 + tmp3
tl.store(out_ptr0 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(256)](primals_3, primals_1,
primals_2, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_3
return buf0, primals_2
class NoiseInjectionNew(nn.Module):
def __init__(self, channel):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1, channel, 1, 1))
def forward(self, input_0, input_1):
primals_1 = self.weight
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
KwonGihyun/DiagonalGAN
|
NoiseInjection
| false
| 8,448
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
SymmetricPad2d
|
import torch
import torch.nn as nn
class SymmetricPad2d(nn.Module):
"""symmetric 0-pad to splited tensors and concat"""
def __init__(self, pad=1):
super(SymmetricPad2d, self).__init__()
self.padding1 = nn.ZeroPad2d((pad, 0, pad, 0))
self.padding2 = nn.ZeroPad2d((pad, 0, 0, pad))
self.padding3 = nn.ZeroPad2d((0, pad, pad, 0))
self.padding4 = nn.ZeroPad2d((0, pad, 0, pad))
def forward(self, x):
sub = x.shape[1] // 4
x1, x2, x3, x4 = x[:, :sub], x[:, sub:2 * sub], x[:, 2 * sub:3 * sub
], x[:, 3 * sub:]
x1, x2, x3, x4 = self.padding1(x1), self.padding2(x2), self.padding3(x3
), self.padding4(x4)
x = torch.cat((x1, x2, x3, x4), dim=1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 25 % 4
x1 = xindex // 5 % 5
x0 = xindex % 5
x3 = xindex // 100
x6 = xindex
tmp0 = x2
tmp1 = tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -1 + x1
tmp6 = tmp5 >= tmp1
tmp7 = -1 + x0
tmp8 = tmp7 >= tmp1
tmp9 = tmp6 & tmp8
tmp10 = tmp9 & tmp4
tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 64 * x3), tmp10 & xmask,
eviction_policy='evict_last', other=0.0)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tmp15 = tl.full([1], 2, tl.int64)
tmp16 = tmp0 < tmp15
tmp17 = tmp14 & tmp16
tmp18 = x1
tmp19 = tl.full([1], 4, tl.int64)
tmp20 = tmp18 < tmp19
tmp21 = tmp20 & tmp8
tmp22 = tmp21 & tmp17
tmp23 = tl.load(in_ptr0 + (15 + x0 + 4 * x1 + 64 * x3), tmp22 & xmask,
eviction_policy='evict_last', other=0.0)
tmp24 = tl.full(tmp23.shape, 0.0, tmp23.dtype)
tmp25 = tl.where(tmp17, tmp23, tmp24)
tmp26 = tmp0 >= tmp15
tmp27 = tl.full([1], 3, tl.int64)
tmp28 = tmp0 < tmp27
tmp29 = tmp26 & tmp28
tmp30 = x0
tmp31 = tmp30 < tmp19
tmp32 = tmp6 & tmp31
tmp33 = tmp32 & tmp29
tmp34 = tl.load(in_ptr0 + (28 + x0 + 4 * x1 + 64 * x3), tmp33 & xmask,
eviction_policy='evict_last', other=0.0)
tmp35 = tl.full(tmp34.shape, 0.0, tmp34.dtype)
tmp36 = tl.where(tmp29, tmp34, tmp35)
tmp37 = tmp0 >= tmp27
tmp39 = tmp20 & tmp31
tmp40 = tmp39 & tmp37
tmp41 = tl.load(in_ptr0 + (48 + x0 + 4 * x1 + 64 * x3), tmp40 & xmask,
eviction_policy='evict_last', other=0.0)
tmp42 = tl.full(tmp41.shape, 0.0, tmp41.dtype)
tmp43 = tl.where(tmp37, tmp41, tmp42)
tmp44 = tl.where(tmp29, tmp36, tmp43)
tmp45 = tl.where(tmp17, tmp25, tmp44)
tmp46 = tl.where(tmp4, tmp13, tmp45)
tl.store(out_ptr0 + x6, tmp46, 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, 5, 5), (100, 25, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(400)](arg0_1, buf0, 400, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SymmetricPad2dNew(nn.Module):
"""symmetric 0-pad to splited tensors and concat"""
def __init__(self, pad=1):
super(SymmetricPad2dNew, self).__init__()
self.padding1 = nn.ZeroPad2d((pad, 0, pad, 0))
self.padding2 = nn.ZeroPad2d((pad, 0, 0, pad))
self.padding3 = nn.ZeroPad2d((0, pad, pad, 0))
self.padding4 = nn.ZeroPad2d((0, pad, 0, pad))
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Lee-Gihun/Micronet_GSJ
|
SymmetricPad2d
| false
| 8,449
|
[
"MIT"
] | 12
|
72289bb66507b6c3b4d14f2e5916dec718a1b198
|
https://github.com/Lee-Gihun/Micronet_GSJ/tree/72289bb66507b6c3b4d14f2e5916dec718a1b198
|
FusedUpsample
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
class FusedUpsample(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, padding=0):
super().__init__()
weight = torch.randn(in_channel, out_channel, kernel_size, kernel_size)
bias = torch.zeros(out_channel)
fan_in = in_channel * kernel_size * kernel_size
self.multiplier = sqrt(2 / fan_in)
self.weight = nn.Parameter(weight)
self.bias = nn.Parameter(bias)
self.pad = padding
def forward(self, input):
weight = F.pad(self.weight * self.multiplier, [1, 1, 1, 1])
weight = (weight[:, :, 1:, 1:] + weight[:, :, :-1, 1:] + weight[:,
:, 1:, :-1] + weight[:, :, :-1, :-1]) / 4
out = F.conv_transpose2d(input, weight, self.bias, stride=2,
padding=self.pad)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from math import sqrt
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 5 % 5
x0 = xindex % 5
x2 = xindex // 25
x4 = xindex
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp10 & xmask, other=0.0
)
tmp12 = 0.1767766952966369
tmp13 = tmp11 * tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp10, tmp13, tmp14)
tmp16 = -1 + x1
tmp17 = tmp16 >= tmp1
tmp18 = tmp16 < tmp3
tmp19 = tmp17 & tmp18
tmp20 = tmp19 & tmp6
tmp21 = tmp20 & tmp7
tmp22 = tl.load(in_ptr0 + (-4 + x0 + 4 * x1 + 16 * x2), tmp21 & xmask,
other=0.0)
tmp23 = tmp22 * tmp12
tmp24 = tl.full(tmp23.shape, 0.0, tmp23.dtype)
tmp25 = tl.where(tmp21, tmp23, tmp24)
tmp26 = tmp15 + tmp25
tmp27 = -1 + x0
tmp28 = tmp27 >= tmp1
tmp29 = tmp27 < tmp3
tmp30 = tmp8 & tmp28
tmp31 = tmp30 & tmp29
tmp32 = tl.load(in_ptr0 + (-1 + x0 + 4 * x1 + 16 * x2), tmp31 & xmask,
other=0.0)
tmp33 = tmp32 * tmp12
tmp34 = tl.full(tmp33.shape, 0.0, tmp33.dtype)
tmp35 = tl.where(tmp31, tmp33, tmp34)
tmp36 = tmp26 + tmp35
tmp37 = tmp19 & tmp28
tmp38 = tmp37 & tmp29
tmp39 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp38 & xmask,
other=0.0)
tmp40 = tmp39 * tmp12
tmp41 = tl.full(tmp40.shape, 0.0, tmp40.dtype)
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp36 + tmp42
tmp44 = 0.25
tmp45 = tmp43 * tmp44
tl.store(in_out_ptr0 + x4, tmp45, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 1936
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 121 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_div_0[grid(400)](buf1, primals_1, 400, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_1
buf2 = extern_kernels.convolution(primals_3, buf1, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 11, 11), (484, 121, 11, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(1936)](buf3, primals_2, 1936,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return buf3, primals_3, buf1
class FusedUpsampleNew(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, padding=0):
super().__init__()
weight = torch.randn(in_channel, out_channel, kernel_size, kernel_size)
bias = torch.zeros(out_channel)
fan_in = in_channel * kernel_size * kernel_size
self.multiplier = sqrt(2 / fan_in)
self.weight = nn.Parameter(weight)
self.bias = nn.Parameter(bias)
self.pad = padding
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]
|
KwonGihyun/DiagonalGAN
|
FusedUpsample
| false
| 8,450
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
LogitCond
|
import torch
import torch.nn as nn
class LogitCond(nn.Module):
"""
from the softmax outputs, decides whether the samples are above or below threshold.
"""
def __init__(self, thres=1.0):
super(LogitCond, self).__init__()
self.thres = thres
self.softmax = nn.Softmax(dim=1)
def forward(self, outputs):
logits = self.softmax(outputs)
max_logits, _ = torch.max(logits, dim=1)
cond_up = max_logits > self.thres
cond_down = max_logits <= self.thres
return cond_up, cond_down
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__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_gt_le_max_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 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 = tmp0 / tmp6
tmp8 = tmp1 / tmp6
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tmp3 / tmp6
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = tmp5 / tmp6
tmp13 = triton_helpers.maximum(tmp11, tmp12)
tmp14 = 1.0
tmp15 = tmp13 > tmp14
tmp16 = tmp13 <= tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused__softmax_gt_le_max_1[grid(64)](buf0, buf1, buf2,
64, XBLOCK=64, num_warps=1, num_stages=1)
del buf0
return buf1, buf2
class LogitCondNew(nn.Module):
"""
from the softmax outputs, decides whether the samples are above or below threshold.
"""
def __init__(self, thres=1.0):
super(LogitCondNew, self).__init__()
self.thres = thres
self.softmax = nn.Softmax(dim=1)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1]
|
Lee-Gihun/Micronet_GSJ
|
LogitCond
| false
| 8,451
|
[
"MIT"
] | 12
|
72289bb66507b6c3b4d14f2e5916dec718a1b198
|
https://github.com/Lee-Gihun/Micronet_GSJ/tree/72289bb66507b6c3b4d14f2e5916dec718a1b198
|
softCrossEntropy
|
import torch
from torch import nn
from torch.nn import functional as F
class softCrossEntropy(nn.Module):
def __init__(self, reduce=True):
super(softCrossEntropy, self).__init__()
self.reduce = reduce
return
def forward(self, inputs, target):
"""
:param inputs: predictions
:param target: target labels in vector form
:return: loss
"""
log_likelihood = -F.log_softmax(inputs, dim=1)
sample_num, _class_num = target.shape
if self.reduce:
loss = torch.sum(torch.mul(log_likelihood, target)) / sample_num
else:
loss = torch.sum(torch.mul(log_likelihood, target), 1)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__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_mul_neg_sum_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp14 = -tmp13
tmp16 = tmp14 * tmp15
tmp17 = tl.broadcast_to(tmp16, [RBLOCK])
tmp19 = triton_helpers.promote_to_tensor(tl.sum(tmp17, 0))
tmp20 = 0.25
tmp21 = tmp19 * tmp20
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, 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, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__log_softmax_div_mul_neg_sum_1[grid(1)](buf2, buf0,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg1_1
del buf0
return buf2,
class softCrossEntropyNew(nn.Module):
def __init__(self, reduce=True):
super(softCrossEntropyNew, self).__init__()
self.reduce = reduce
return
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Lingkai-Kong/Calibrated-BERT-Fine-Tuning
|
softCrossEntropy
| false
| 8,452
|
[
"Apache-2.0"
] | 29
|
34b8dbf1bfb0d1e466621f149622933bfeab1555
|
https://github.com/Lingkai-Kong/Calibrated-BERT-Fine-Tuning/tree/34b8dbf1bfb0d1e466621f149622933bfeab1555
|
DropBlock_Ske
|
import torch
import torch.nn as nn
class DropBlock_Ske(nn.Module):
def __init__(self, num_point=25, keep_prob=0.9):
super(DropBlock_Ske, self).__init__()
self.keep_prob = keep_prob
self.num_point = num_point
def forward(self, input, mask):
n, _c, _t, _v = input.size()
mask[mask >= self.keep_prob] = 2.0
mask[mask < self.keep_prob] = 1.0
mask[mask == 2.0] = 0.0
mask = mask.view(n, 1, 1, self.num_point)
return input * mask * mask.numel() / mask.sum()
def get_inputs():
return [torch.rand([4, 1, 1, 25]), torch.rand([4, 1, 1, 25])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_index_put_lift_fresh_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 100
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.9
tmp2 = tmp0 >= tmp1
tmp3 = 2.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 100
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.9
tmp2 = tmp0 < tmp1
tmp3 = 1.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_per_fused_div_index_put_lift_fresh_mul_sum_2(in_ptr0, in_ptr1,
out_ptr0, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
rnumel = 100
RBLOCK: tl.constexpr = 128
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, rmask, other=0.0)
tmp9 = tl.load(in_ptr1 + r0, rmask, other=0.0)
tmp1 = 2.0
tmp2 = tmp0 == tmp1
tmp3 = 0.0
tmp4 = tl.where(tmp2, tmp3, tmp0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp7 = tl.where(rmask, tmp5, 0)
tmp8 = tl.sum(tmp7, 1)[:, None]
tmp10 = tmp9 * tmp4
tmp11 = 100.0
tmp12 = tmp10 * tmp11
tmp13 = tmp12 / tmp8
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp4, rmask)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp13, rmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 1, 1, 25), (25, 25, 25, 1))
assert_size_stride(arg1_1, (4, 1, 1, 25), (25, 25, 25, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
get_raw_stream(0)
triton_poi_fused_index_put_lift_fresh_0[grid(100)](arg1_1, arg1_1,
100, XBLOCK=128, num_warps=4, num_stages=1)
triton_poi_fused_index_put_lift_fresh_1[grid(100)](arg1_1, arg1_1,
100, XBLOCK=128, num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 1, 1, 25), (25, 25, 25, 1), torch.float32
)
triton_per_fused_div_index_put_lift_fresh_mul_sum_2[grid(1)](arg1_1,
arg0_1, arg1_1, buf7, 1, 100, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf7,
class DropBlock_SkeNew(nn.Module):
def __init__(self, num_point=25, keep_prob=0.9):
super(DropBlock_SkeNew, self).__init__()
self.keep_prob = keep_prob
self.num_point = num_point
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
Levigty/AimCLR
|
DropBlock_Ske
| false
| 8,453
|
[
"MIT"
] | 25
|
6cd73767f17748792508647355fa324fa63e235d
|
https://github.com/Levigty/AimCLR/tree/6cd73767f17748792508647355fa324fa63e235d
|
ImageEncoderV4
|
import torch
from torch import nn
import torch.nn.functional as F
class ImageEncoderV4(nn.Module):
"""
Outputs a 5 x 5 x 32 feature map that preserves spatial information.
"""
def __init__(self, input_channels=3, init_scale=1.0, no_weight_init=
False, init_method='ortho', activation='relu'):
super(ImageEncoderV4, self).__init__()
self.activation = activation
self.conv1 = nn.Conv2d(input_channels, 32, kernel_size=5, stride=2)
self.conv2 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
if not no_weight_init:
for layer in (self.conv1, self.conv2, self.conv3):
if init_method == 'ortho':
nn.init.orthogonal_(layer.weight, init_scale)
elif init_method == 'normal':
nn.init.normal_(layer.weight, mean=0.0, std=1.0)
elif init_method == 'xavier_normal':
nn.init.xavier_normal_(layer.weight, 1.0)
else:
assert init_method == 'default'
def forward(self, imgs):
if self.activation == 'relu':
ac = F.relu
elif self.activation == 'tanh':
ac = torch.tanh
else:
raise RuntimeError()
x = ac(self.conv1(imgs))
x = ac(self.conv2(x))
x = ac(self.conv3(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
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_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 115200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 900 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 21632
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 169 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_2(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
x3 = xindex
x1 = xindex // 25 % 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)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + 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, (32, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (32, 32, 5, 5), (800, 25, 5, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 32, 5, 5), (800, 25, 5, 1))
assert_size_stride(primals_7, (32,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2,
2), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 30, 30), (28800, 900, 30, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(115200)](buf1, primals_2,
115200, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 13, 13), (5408, 169, 13, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_1[grid(21632)](buf3, primals_5,
21632, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 5, 5), (800, 25, 5, 1))
buf5 = buf4
del buf4
buf6 = empty_strided_cuda((4, 32, 5, 5), (800, 25, 5, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_2[grid(3200)](buf5
, primals_7, buf6, 3200, XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
return buf5, primals_1, primals_3, primals_4, primals_6, buf1, buf3, buf6
class ImageEncoderV4New(nn.Module):
"""
Outputs a 5 x 5 x 32 feature map that preserves spatial information.
"""
def __init__(self, input_channels=3, init_scale=1.0, no_weight_init=
False, init_method='ortho', activation='relu'):
super(ImageEncoderV4New, self).__init__()
self.activation = activation
self.conv1 = nn.Conv2d(input_channels, 32, kernel_size=5, stride=2)
self.conv2 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
if not no_weight_init:
for layer in (self.conv1, self.conv2, self.conv3):
if init_method == 'ortho':
nn.init.orthogonal_(layer.weight, init_scale)
elif init_method == 'normal':
nn.init.normal_(layer.weight, mean=0.0, std=1.0)
elif init_method == 'xavier_normal':
nn.init.xavier_normal_(layer.weight, 1.0)
else:
assert init_method == 'default'
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
KH-Kyle/rmp_nav
|
ImageEncoderV4
| false
| 8,454
|
[
"MIT"
] | 30
|
d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551
|
https://github.com/KH-Kyle/rmp_nav/tree/d598fe70664a4cdc0e9b9dd4b52e84aa3de1b551
|
FocalLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(FocalLoss, self).__init__()
def forward(self, inputs: 'torch.Tensor', targets: 'torch.Tensor',
alpha: 'float'=0.5, gamma: 'float'=0.5, smooth: 'int'=1):
inputs = inputs.view(-1)
targets = targets.view(-1)
BCE = F.binary_cross_entropy_with_logits(inputs, targets, reduction
='mean')
BCE_EXP = torch.exp(-BCE)
focal_loss = alpha * (1 - BCE_EXP) ** gamma * BCE
return focal_loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_binary_cross_entropy_with_logits_exp_mul_neg_pow_rsub_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp2 * tmp3
tmp5 = 0.0
tmp6 = triton_helpers.minimum(tmp5, tmp3)
tmp7 = tl_math.abs(tmp3)
tmp8 = -tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = libdevice.log1p(tmp9)
tmp11 = tmp6 - tmp10
tmp12 = tmp4 - tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tmp18 = -tmp17
tmp19 = tl_math.exp(tmp18)
tmp20 = tmp1 - tmp19
tmp21 = libdevice.sqrt(tmp20)
tmp22 = 0.5
tmp23 = tmp21 * tmp22
tmp24 = tmp23 * tmp17
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp24, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_with_logits_exp_mul_neg_pow_rsub_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 FocalLossNew(nn.Module):
def __init__(self, weight=None, size_average=True):
super(FocalLossNew, 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]
|
Latterlig96/DCUnet
|
FocalLoss
| false
| 8,455
|
[
"MIT"
] | 11
|
87d1c137a60177d6daf1dfff0483678d5580fda0
|
https://github.com/Latterlig96/DCUnet/tree/87d1c137a60177d6daf1dfff0483678d5580fda0
|
DiceBCELoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class DiceBCELoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(DiceBCELoss, self).__init__()
def forward(self, inputs: 'torch.Tensor', targets: 'torch.Tensor',
smooth: 'int'=1):
inputs = inputs.view(-1)
targets = targets.view(-1)
intersection = (inputs * targets).sum()
dice_loss = 1 - (2.0 * intersection + smooth) / (inputs.sum() +
targets.sum() + smooth)
BCE = F.binary_cross_entropy_with_logits(inputs, targets, reduction
='mean')
Dice_BCE = BCE + dice_loss
return Dice_BCE
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_binary_cross_entropy_with_logits_div_mul_rsub_sum_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp2 * tmp3
tmp5 = 0.0
tmp6 = triton_helpers.minimum(tmp5, tmp3)
tmp7 = tl_math.abs(tmp3)
tmp8 = -tmp7
tmp9 = tl_math.exp(tmp8)
tmp10 = libdevice.log1p(tmp9)
tmp11 = tmp6 - tmp10
tmp12 = tmp4 - tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = tmp3 * tmp0
tmp17 = tl.broadcast_to(tmp16, [RBLOCK])
tmp19 = triton_helpers.promote_to_tensor(tl.sum(tmp17, 0))
tmp20 = tl.broadcast_to(tmp3, [RBLOCK])
tmp22 = triton_helpers.promote_to_tensor(tl.sum(tmp20, 0))
tmp23 = tl.broadcast_to(tmp0, [RBLOCK])
tmp25 = triton_helpers.promote_to_tensor(tl.sum(tmp23, 0))
tmp26 = 256.0
tmp27 = tmp15 / tmp26
tmp28 = 2.0
tmp29 = tmp19 * tmp28
tmp30 = tmp29 + tmp1
tmp31 = tmp22 + tmp25
tmp32 = tmp31 + tmp1
tmp33 = tmp30 / tmp32
tmp34 = tmp1 - tmp33
tmp35 = tmp27 + tmp34
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp35, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf4 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_binary_cross_entropy_with_logits_div_mul_rsub_sum_0[
grid(1)](buf4, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf4,
class DiceBCELossNew(nn.Module):
def __init__(self, weight=None, size_average=True):
super(DiceBCELossNew, 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]
|
Latterlig96/DCUnet
|
DiceBCELoss
| false
| 8,456
|
[
"MIT"
] | 11
|
87d1c137a60177d6daf1dfff0483678d5580fda0
|
https://github.com/Latterlig96/DCUnet/tree/87d1c137a60177d6daf1dfff0483678d5580fda0
|
ConvTranspose
|
import torch
from typing import Union
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple
def autopad(k, p=None):
if p is None:
p = k // 2 if isinstance(k, int) else [(x // 2) for x in k]
return p
class ConvTranspose(nn.Module):
def __init__(self, input_channels: 'int', output_channels: 'int',
kernel_size: 'Tuple[int, int]'=(2, 2), stride: 'Tuple[int, int]'=(2,
2), padding: 'Union[int, None]'=None, **kwargs):
super(ConvTranspose, self).__init__()
self.input_channels = input_channels
self.output_channels = output_channels
self.transpose = nn.ConvTranspose2d(in_channels=self.input_channels,
out_channels=self.output_channels, kernel_size=kernel_size,
stride=stride, padding=autopad(k=kernel_size, p=padding), **kwargs)
def forward(self, x1: 'torch.Tensor', x2: 'torch.Tensor') ->torch.Tensor:
out = self.transpose(x1)
diffY = x2.size()[2] - out.size()[2]
diffX = x2.size()[3] - out.size()[3]
out = F.pad(out, [diffX // 2, diffX - diffX // 2, diffY // 2, diffY -
diffY // 2])
out = torch.cat([x2, out], dim=1)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_channels': 4, 'output_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 typing import Union
import torch.nn as nn
from typing import Tuple
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, 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 // 16 % 8
x3 = xindex // 128
x4 = xindex % 16
x1 = xindex // 4 % 4
x0 = xindex % 4
x7 = xindex
tmp0 = x2
tmp1 = tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x4 + 16 * x2 + 64 * x3), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = 1 + x1
tmp10 = tmp9 >= tmp1
tmp11 = tl.full([1], 6, tl.int64)
tmp12 = tmp9 < tmp11
tmp13 = 1 + x0
tmp14 = tmp13 >= tmp1
tmp15 = tmp13 < tmp11
tmp16 = tmp10 & tmp12
tmp17 = tmp16 & tmp14
tmp18 = tmp17 & tmp15
tmp19 = tmp18 & tmp6
tmp20 = tl.load(in_ptr1 + (7 + x0 + 6 * x1 + 36 * (-4 + x2) + 144 * x3),
tmp19 & xmask, other=0.0)
tmp21 = tl.load(in_ptr2 + (-4 + x2), tmp19 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp22 = tmp20 + tmp21
tmp23 = tl.full(tmp22.shape, 0.0, tmp22.dtype)
tmp24 = tl.where(tmp19, tmp22, tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp6, tmp24, tmp25)
tmp27 = tl.where(tmp4, tmp5, tmp26)
tl.store(out_ptr0 + x7, tmp27, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 2, 2), (16, 4, 2, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2,
2), padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 6, 6), (144, 36, 6, 1))
buf1 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](primals_4, buf0, primals_2, buf1,
512, XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_2
del primals_4
return buf1, primals_1, primals_3
def autopad(k, p=None):
if p is None:
p = k // 2 if isinstance(k, int) else [(x // 2) for x in k]
return p
class ConvTransposeNew(nn.Module):
def __init__(self, input_channels: 'int', output_channels: 'int',
kernel_size: 'Tuple[int, int]'=(2, 2), stride: 'Tuple[int, int]'=(2,
2), padding: 'Union[int, None]'=None, **kwargs):
super(ConvTransposeNew, self).__init__()
self.input_channels = input_channels
self.output_channels = output_channels
self.transpose = nn.ConvTranspose2d(in_channels=self.input_channels,
out_channels=self.output_channels, kernel_size=kernel_size,
stride=stride, padding=autopad(k=kernel_size, p=padding), **kwargs)
def forward(self, input_0, input_1):
primals_1 = self.transpose.weight
primals_2 = self.transpose.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Latterlig96/DCUnet
|
ConvTranspose
| false
| 8,457
|
[
"MIT"
] | 11
|
87d1c137a60177d6daf1dfff0483678d5580fda0
|
https://github.com/Latterlig96/DCUnet/tree/87d1c137a60177d6daf1dfff0483678d5580fda0
|
EqualLinear
|
import torch
import torch.nn as nn
from math import sqrt
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input):
return self.linear(input)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
from math 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_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.7071067811865476
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_1
buf1 = 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(buf0, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf0, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
def equal_lr(module, name='weight'):
EqualLR.apply(module, name)
return module
class EqualLR:
def __init__(self, name):
self.name = name
def compute_weight(self, module):
weight = getattr(module, self.name + '_orig')
fan_in = weight.data.size(1) * weight.data[0][0].numel()
return weight * sqrt(2 / fan_in)
@staticmethod
def apply(module, name):
fn = EqualLR(name)
weight = getattr(module, name)
del module._parameters[name]
module.register_parameter(name + '_orig', nn.Parameter(weight.data))
module.register_forward_pre_hook(fn)
return fn
def __call__(self, module, input):
weight = self.compute_weight(module)
setattr(module, self.name, weight)
class EqualLinearNew(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
linear = nn.Linear(in_dim, out_dim)
linear.weight.data.normal_()
linear.bias.data.zero_()
self.linear = equal_lr(linear)
def forward(self, input_0):
primals_2 = self.linear.bias
primals_1 = self.linear.weight_orig
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
KwonGihyun/DiagonalGAN
|
EqualLinear
| false
| 8,458
|
[
"MIT"
] | 13
|
9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
https://github.com/KwonGihyun/DiagonalGAN/tree/9e401c00e741d700f85df2c715ee11c1e66e1d1c
|
AdaptiveBilinear
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class AdaptiveBilinear(nn.Module):
def __init__(self):
super(AdaptiveBilinear, self).__init__()
def forward(self, x1, x2):
"""
:param x1: (b, l1, dim1)
:param x2: (b, l2, dim2)
:return:
"""
assert x1.size(-1) == x2.size(-1)
x_1 = F.softmax(x1 @ x1.transpose(1, 2), dim=-1)
x_2 = F.softmax(x2 @ x2.transpose(1, 2), dim=-1)
x_12 = x1 @ x2.transpose(1, 2)
x_12 = x_1 @ x_12 @ x_2.transpose(1, 2)
return x_12
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_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused__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_clone_2(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
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
tl.store(out_ptr1 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x5 = xindex // 4
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
tmp0 = tl.load(in_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x5, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x5), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x5), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x5), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), tmp8, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg0_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1), 0), out
=buf1)
buf2 = buf0
del buf0
triton_poi_fused__softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_2[grid(256)](arg1_1, buf3, buf7, 256, XBLOCK
=256, num_warps=4, num_stages=1)
buf4 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg0_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1), 0), out
=buf4)
del arg0_1
buf5 = buf3
del buf3
triton_poi_fused__softmax_3[grid(256)](buf2, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1),
0), buf4, out=buf6)
del buf4
buf8 = reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1), 0)
del buf5
extern_kernels.bmm(reinterpret_tensor(arg1_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1), 0), out
=buf8)
del arg1_1
buf9 = buf7
del buf7
triton_poi_fused__softmax_1[grid(256)](buf8, buf9, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf10 = reinterpret_tensor(buf8, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf8
triton_poi_fused_clone_4[grid(256)](buf9, buf10, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4, 4), (16, 4, 1), 0)
del buf9
extern_kernels.bmm(buf6, reinterpret_tensor(buf10, (16, 4, 4), (16,
4, 1), 0), out=buf11)
del buf10
del buf6
return reinterpret_tensor(buf11, (4, 4, 4, 4), (64, 16, 4, 1), 0),
class AdaptiveBilinearNew(nn.Module):
def __init__(self):
super(AdaptiveBilinearNew, 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]
|
LindgeW/BiaffineNER
|
AdaptiveBilinear
| false
| 8,459
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
OverHaulLoss
|
import torch
import torch.nn as nn
from torch.nn import functional as F
class LabelSmoothingLoss(nn.Module):
def __init__(self, classes, smoothing=0.0, dim=-1):
super(LabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = classes
self.dim = dim
def forward(self, pred, target):
pred = pred.log_softmax(dim=self.dim)
with torch.no_grad():
true_dist = torch.zeros_like(pred)
true_dist.fill_(self.smoothing / (self.cls - 1))
true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
return torch.mean(torch.sum(-true_dist * pred, dim=self.dim))
class SoftLabelSmoothingLoss(nn.Module):
def __init__(self, classes=100, smoothing=0.0, target=False, dim=-1):
super(SoftLabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = classes
self.target = target
self.dim = dim
def forward(self, output, target):
logits = F.softmax(output, dim=1)
if not self.target:
max_softval, _ = torch.max(logits, dim=1)
else:
target_softval = logits[range(logits.shape[0]), target]
log_logits = logits.log()
with torch.no_grad():
smooth_target = torch.zeros_like(output)
smooth_target.fill_(self.smoothing / (self.cls - 1))
smooth_target.scatter_(1, target.data.unsqueeze(1), self.confidence
)
if self.smoothing:
loss = torch.sum((1 + logits) * (-smooth_target * log_logits),
dim=self.dim)
else:
loss = torch.sum(-smooth_target * log_logits, dim=self.dim)
if not self.target:
loss = loss * (1 + max_softval)
else:
loss = loss * (1 + target_softval)
loss = loss.mean()
return loss
class OverHaulLoss(nn.Module):
def __init__(self, soft_label_smoothing=False, label_smoothing=False,
classes=100, smoothing=0.0):
super(OverHaulLoss, self).__init__()
self.label_smoothing = label_smoothing
self.soft_label_smoothing = soft_label_smoothing
if soft_label_smoothing:
self.loss = SoftLabelSmoothingLoss(classes, smoothing=smoothing)
elif label_smoothing:
self.loss = LabelSmoothingLoss(classes, smoothing=smoothing)
else:
self.loss = nn.CrossEntropyLoss()
def forward(self, output, target):
if len(output) == 2:
output = output[0]
loss = self.loss(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 import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from torch.nn import functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__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_mul_neg_sum_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + r3, None)
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = -tmp18
tmp20 = 0.015625
tmp21 = tmp19 * tmp20
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__log_softmax_div_mul_neg_sum_1[grid(1)](buf2, buf0,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg1_1
del buf0
return buf2,
class LabelSmoothingLoss(nn.Module):
def __init__(self, classes, smoothing=0.0, dim=-1):
super(LabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = classes
self.dim = dim
def forward(self, pred, target):
pred = pred.log_softmax(dim=self.dim)
with torch.no_grad():
true_dist = torch.zeros_like(pred)
true_dist.fill_(self.smoothing / (self.cls - 1))
true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence)
return torch.mean(torch.sum(-true_dist * pred, dim=self.dim))
class SoftLabelSmoothingLoss(nn.Module):
def __init__(self, classes=100, smoothing=0.0, target=False, dim=-1):
super(SoftLabelSmoothingLoss, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
self.cls = classes
self.target = target
self.dim = dim
def forward(self, output, target):
logits = F.softmax(output, dim=1)
if not self.target:
max_softval, _ = torch.max(logits, dim=1)
else:
target_softval = logits[range(logits.shape[0]), target]
log_logits = logits.log()
with torch.no_grad():
smooth_target = torch.zeros_like(output)
smooth_target.fill_(self.smoothing / (self.cls - 1))
smooth_target.scatter_(1, target.data.unsqueeze(1), self.confidence
)
if self.smoothing:
loss = torch.sum((1 + logits) * (-smooth_target * log_logits),
dim=self.dim)
else:
loss = torch.sum(-smooth_target * log_logits, dim=self.dim)
if not self.target:
loss = loss * (1 + max_softval)
else:
loss = loss * (1 + target_softval)
loss = loss.mean()
return loss
class OverHaulLossNew(nn.Module):
def __init__(self, soft_label_smoothing=False, label_smoothing=False,
classes=100, smoothing=0.0):
super(OverHaulLossNew, self).__init__()
self.label_smoothing = label_smoothing
self.soft_label_smoothing = soft_label_smoothing
if soft_label_smoothing:
self.loss = SoftLabelSmoothingLoss(classes, smoothing=smoothing)
elif label_smoothing:
self.loss = LabelSmoothingLoss(classes, smoothing=smoothing)
else:
self.loss = 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]
|
Lee-Gihun/Micronet_GSJ
|
OverHaulLoss
| false
| 8,460
|
[
"MIT"
] | 12
|
72289bb66507b6c3b4d14f2e5916dec718a1b198
|
https://github.com/Lee-Gihun/Micronet_GSJ/tree/72289bb66507b6c3b4d14f2e5916dec718a1b198
|
length_evolution
|
import torch
import torch.nn as nn
class length_evolution(nn.Module):
"""
calcaulate the length of evolution curve by the gradient
"""
def __init__(self, func='l1'):
super(length_evolution, self).__init__()
self.func = func
def forward(self, mask_score, class_weight):
gradient_H = torch.abs(mask_score[:, :, 1:, :] - mask_score[:, :, :
-1, :])
gradient_W = torch.abs(mask_score[:, :, :, 1:] - mask_score[:, :, :,
:-1])
if self.func == 'l2':
gradient_H = gradient_H * gradient_H
gradient_W = gradient_W * gradient_W
curve_length = torch.sum(class_weight * gradient_H) + torch.sum(
class_weight * gradient_W)
return curve_length
def get_inputs():
return [torch.rand([4, 4, 2, 2]), torch.rand([4, 4, 2, 2])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_add_mul_sub_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r4 = rindex
r0 = rindex % 2
r2 = rindex // 4
r3 = rindex // 2
tmp0 = tl.load(in_ptr0 + r4, None)
tmp1 = tl.load(in_ptr1 + (2 + r0 + 4 * r2), None, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr1 + (r0 + 4 * r2), None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (1 + 2 * r3), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + 2 * r3, None, eviction_policy='evict_last')
tmp3 = tmp1 - tmp2
tmp4 = tl_math.abs(tmp3)
tmp5 = tmp0 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tmp11 = tmp9 - tmp10
tmp12 = tl_math.abs(tmp11)
tmp13 = tmp0 * tmp12
tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
tmp16 = tl.sum(tmp14, 1)[:, None]
tmp17 = tmp8 + tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 2, 2), (16, 4, 2, 1))
assert_size_stride(arg1_1, (4, 4, 2, 2), (16, 4, 2, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf2 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_abs_add_mul_sub_sum_0[grid(1)](buf2, arg1_1,
arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class length_evolutionNew(nn.Module):
"""
calcaulate the length of evolution curve by the gradient
"""
def __init__(self, func='l1'):
super(length_evolutionNew, self).__init__()
self.func = func
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
LiWentomng/boxlevelset
|
length_evolution
| false
| 8,461
|
[
"Apache-2.0"
] | 25
|
8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
https://github.com/LiWentomng/boxlevelset/tree/8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
evolution_area
|
import torch
import torch.nn as nn
class evolution_area(nn.Module):
"""
calcaulate the area of evolution curve
"""
def __init__(self):
super(evolution_area, self).__init__()
def forward(self, mask_score, class_weight):
curve_area = torch.sum(class_weight * mask_score)
return curve_area
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp5, 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)
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(1)](arg0_1, arg1_1, buf0, 1, 256,
num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class evolution_areaNew(nn.Module):
"""
calcaulate the area of evolution curve
"""
def __init__(self):
super(evolution_areaNew, 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]
|
LiWentomng/boxlevelset
|
evolution_area
| false
| 8,462
|
[
"Apache-2.0"
] | 25
|
8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
https://github.com/LiWentomng/boxlevelset/tree/8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
DotProductAttention
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class DotProductAttention(nn.Module):
def __init__(self, k_dim):
super(DotProductAttention, self).__init__()
self.scale = 1.0 / k_dim ** 0.5
def forward(self, hn, enc_out, mask=None):
"""
:param hn: query - rnn的末隐层状态 [batch_size, hidden_size]
:param enc_out: key - rnn的输出 [batch_size, seq_len, hidden_size]
:param mask: [batch_size, seq_len] 0对应pad
:return: att_out [batch_size, hidden_size]
"""
att_score = torch.matmul(hn.unsqueeze(1), enc_out.transpose(1, 2)
).squeeze(1)
att_score.mul_(self.scale)
if mask is not None:
att_score = att_score.masked_fill(~mask, -1000000000.0)
att_weights = F.softmax(att_score, dim=1)
att_out = torch.matmul(att_weights.unsqueeze(1), enc_out).squeeze(1)
"""
# type 2
# (bz, hidden_size, 1)
hidden = hn.reshape(hn.size(0), -1, 1)
# (bz, n_step, hidden_size) * (bz, hidden_size, 1) -> (bz, n_step)
att_score = torch.matmul(enc_out, hidden).squeeze(2)
att_score.mul_(self.scale)
if mask is not None:
att_score = att_score.masked_fill(~mask, -1e9)
attn_weights = F.softmax(att_score, dim=1)
# (bz, hidden_sze, n_step) * (bz, n_step, 1) -> (bz, hidden_size, 1)
att_out = torch.matmul(enc_out.transpose(1, 2), attn_weights.unsqueeze(2)).squeeze(2)
"""
return att_out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'k_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x2 = xindex // 256
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64 % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask,
eviction_policy='evict_last')
tl.store(out_ptr0 + x5, tmp0, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x5 = xindex
x3 = xindex // 256
x6 = xindex % 64
x0 = xindex % 16
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x5, xmask)
tmp3 = tl.load(in_ptr0 + (x6 + 256 * x3), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (64 + x0 + 16 * x1 + 256 * x3 + 256 * ((4 + x1
) // 16)), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (128 + x0 + 16 * x1 + 256 * x3 + 256 * ((8 +
x1) // 16)), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (192 + x0 + 16 * x1 + 256 * x3 + 256 * ((12 +
x1) // 16)), xmask, eviction_policy='evict_last')
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tl_math.exp(tmp14)
tl.store(out_ptr0 + x5, tmp15, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 64
x2 = xindex // 256
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (64 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (128 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (192 + x0 + 256 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 256
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(1024)](arg0_1, buf0, 1024, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_clone_1[grid(1024)](arg1_1, buf1, 1024, XBLOCK=256,
num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((64, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf1, (64, 4, 4), (16, 4, 1), 0), out=buf2)
buf3 = buf1
del buf1
triton_poi_fused__softmax_2[grid(1024)](buf2, buf3, 1024, XBLOCK=
256, num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0
)
del buf2
triton_poi_fused__softmax_3[grid(1024)](buf3, buf4, 1024, XBLOCK=
256, num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 1, 4, 4, 4, 4), (256, 256, 64,
16, 4, 1), 0)
del buf3
triton_poi_fused_clone_4[grid(1024)](arg1_1, buf5, 1024, XBLOCK=256,
num_warps=4, num_stages=1)
del arg1_1
buf6 = reinterpret_tensor(buf0, (64, 4, 4), (16, 4, 1), 0)
del buf0
extern_kernels.bmm(reinterpret_tensor(buf4, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf5, (64, 4, 4), (16, 4, 1), 0), out=buf6)
del buf4
del buf5
return reinterpret_tensor(buf6, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0),
class DotProductAttentionNew(nn.Module):
def __init__(self, k_dim):
super(DotProductAttentionNew, self).__init__()
self.scale = 1.0 / k_dim ** 0.5
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
LindgeW/BiaffineNER
|
DotProductAttention
| false
| 8,463
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
Bilinear
|
import torch
import torch.nn as nn
class Bilinear(nn.Module):
def __init__(self, in_dim1, in_dim2, label_dim=1, use_input_bias=False):
super(Bilinear, self).__init__()
self.label_dim = label_dim
self.use_input_bias = use_input_bias
if self.use_input_bias:
in_dim1 += 1
in_dim2 += 1
self.U = nn.Parameter(torch.randn(label_dim, in_dim1, in_dim2))
self.bias = nn.Parameter(torch.zeros(1))
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.U)
nn.init.zeros_(self.bias)
def forward(self, x1, x2):
"""
:param x1: (bs, len1, in_dim1)
:param x2: (bs, len2, in_dim2)
:return: (bs, len1, len2, label_dim)
"""
if self.use_input_bias:
bias1 = x1.new_ones(x1.size()[:-1] + (1,))
bias2 = x2.new_ones(x2.size()[:-1] + (1,))
x1 = torch.cat((x1, bias1), dim=-1)
x2 = torch.cat((x2, bias2), dim=-1)
tmp = torch.matmul(x1.unsqueeze(1), self.U)
out = torch.matmul(tmp, x2.unsqueeze(1).transpose(2, 3).contiguous())
final = out.squeeze(1) + self.bias
if self.label_dim > 1:
final = final.permute(0, 2, 3, 1)
return final
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim1': 4, 'in_dim2': 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, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (16, 4, 4), (16, 4,
1), 0), reinterpret_tensor(primals_2, (16, 4, 4), (0, 4, 1), 0),
out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 1, 4, 4, 4), (64, 1, 16, 4, 1), torch
.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](primals_3, buf1, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf0, reinterpret_tensor(buf1, (16, 4, 4), (16,
4, 1), 0), out=buf2)
del buf0
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_add_1[grid(256)](buf3, primals_4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_4
return buf3, reinterpret_tensor(buf1, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(primals_1, (16, 4, 4), (16, 1, 4), 0)
class BilinearNew(nn.Module):
def __init__(self, in_dim1, in_dim2, label_dim=1, use_input_bias=False):
super(BilinearNew, self).__init__()
self.label_dim = label_dim
self.use_input_bias = use_input_bias
if self.use_input_bias:
in_dim1 += 1
in_dim2 += 1
self.U = nn.Parameter(torch.randn(label_dim, in_dim1, in_dim2))
self.bias = nn.Parameter(torch.zeros(1))
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.U)
nn.init.zeros_(self.bias)
def forward(self, input_0, input_1):
primals_2 = self.U
primals_4 = self.bias
primals_1 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
LindgeW/BiaffineNER
|
Bilinear
| false
| 8,464
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
MaxPooling
|
import torch
from typing import Union
import torch.nn as nn
from typing import Tuple
def autopad(k, p=None):
if p is None:
p = k // 2 if isinstance(k, int) else [(x // 2) for x in k]
return p
class MaxPooling(nn.Module):
def __init__(self, input_channels: 'int', kernel_size:
'Tuple[int, int]'=(2, 2), padding: 'Union[int, None]'=None, **kwargs):
super(MaxPooling, self).__init__()
self.input_channels = input_channels
self.pool = nn.MaxPool2d(kernel_size=kernel_size, padding=autopad(k
=kernel_size, p=padding), **kwargs)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
out = self.pool(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from typing import Union
import torch.nn as nn
from typing import Tuple
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 3 % 3
x0 = xindex % 3
x2 = xindex // 9
x4 = xindex
tmp0 = -1 + 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 * x1 + 16 * x2), 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 * x1 + 16 * x2), tmp16 &
xmask, eviction_policy='evict_last', other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 2 * x1
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp22 & tmp9
tmp24 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x1 + 16 * x2), tmp23 &
xmask, eviction_policy='evict_last', other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = tmp22 & tmp15
tmp27 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2), tmp26 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp28 = triton_helpers.maximum(tmp27, tmp25)
tl.store(out_ptr0 + x4, tmp28, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_pool2d_with_indices_0[grid(144)](arg0_1, buf0,
144, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def autopad(k, p=None):
if p is None:
p = k // 2 if isinstance(k, int) else [(x // 2) for x in k]
return p
class MaxPoolingNew(nn.Module):
def __init__(self, input_channels: 'int', kernel_size:
'Tuple[int, int]'=(2, 2), padding: 'Union[int, None]'=None, **kwargs):
super(MaxPoolingNew, self).__init__()
self.input_channels = input_channels
self.pool = nn.MaxPool2d(kernel_size=kernel_size, padding=autopad(k
=kernel_size, p=padding), **kwargs)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Latterlig96/DCUnet
|
MaxPooling
| false
| 8,465
|
[
"MIT"
] | 11
|
87d1c137a60177d6daf1dfff0483678d5580fda0
|
https://github.com/Latterlig96/DCUnet/tree/87d1c137a60177d6daf1dfff0483678d5580fda0
|
FocalTverskyLoss
|
import torch
import torch.nn as nn
class FocalTverskyLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(FocalTverskyLoss, self).__init__()
def forward(self, inputs: 'torch.Tensor', targets: 'torch.Tensor',
smooth: 'int'=1, alpha: 'float'=0.5, beta: 'float'=0.5, gamma: 'int'=1
):
inputs = torch.sigmoid(inputs)
inputs = inputs.view(-1)
targets = targets.view(-1)
TP = (inputs * targets).sum()
FP = ((1 - targets) * inputs).sum()
FN = (targets * (1 - inputs)).sum()
Tversky = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth)
FocalTversky = (1 - Tversky) ** gamma
return FocalTversky
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_mul_rsub_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = 1.0
tmp8 = tmp7 - tmp2
tmp9 = tmp8 * tmp1
tmp10 = tl.broadcast_to(tmp9, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp13 = tmp7 - tmp1
tmp14 = tmp2 * tmp13
tmp15 = tl.broadcast_to(tmp14, [RBLOCK])
tmp17 = triton_helpers.promote_to_tensor(tl.sum(tmp15, 0))
tmp18 = tmp6 + tmp7
tmp19 = 0.5
tmp20 = tmp12 * tmp19
tmp21 = tmp6 + tmp20
tmp22 = tmp17 * tmp19
tmp23 = tmp21 + tmp22
tmp24 = tmp23 + tmp7
tmp25 = tmp18 / tmp24
tmp26 = tmp7 - tmp25
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp26, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mul_rsub_sum_0[grid(1)](buf3, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf3,
class FocalTverskyLossNew(nn.Module):
def __init__(self, weight=None, size_average=True):
super(FocalTverskyLossNew, 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]
|
Latterlig96/DCUnet
|
FocalTverskyLoss
| false
| 8,466
|
[
"MIT"
] | 11
|
87d1c137a60177d6daf1dfff0483678d5580fda0
|
https://github.com/Latterlig96/DCUnet/tree/87d1c137a60177d6daf1dfff0483678d5580fda0
|
AdditiveAttention
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class AdditiveAttention(nn.Module):
def __init__(self, k_size, v_size, hidden_size=None, bias=True):
super(AdditiveAttention, self).__init__()
if hidden_size is None:
hidden_size = v_size
self.W1 = nn.Linear(k_size, hidden_size, bias=False)
self.W2 = nn.Linear(v_size, hidden_size, bias=bias)
self.V = nn.Linear(hidden_size, 1, bias=False)
self.reset_params()
def reset_params(self):
nn.init.xavier_normal_(self.W1.weight)
nn.init.xavier_normal_(self.W2.weight)
nn.init.xavier_uniform_(self.V.weight)
def forward(self, q, v, mask=None):
"""
:param q: (bz, hidden_size)
:param v: (bz, n_step, hidden_size)
:param mask: (bz, n_step)
:return:
"""
expand_q = q.unsqueeze(1)
att_score = self.V(torch.tanh(self.W1(expand_q) + self.W2(v)))
if mask is not None:
att_score = att_score.masked_fill(~mask.unsqueeze(-1), -
1000000000.0)
att_weights = F.softmax(att_score, dim=1)
attn_dist = att_weights.squeeze(dim=-1)
att_out = (att_weights * v).sum(dim=1)
return att_out, attn_dist
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'k_size': 4, 'v_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_tanh_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex // 256
x4 = xindex % 64
x5 = xindex % 256
x0 = xindex % 4
x6 = xindex
tmp0 = tl.load(in_ptr0 + (x4 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp5 = libdevice.tanh(tmp4)
tl.store(out_ptr0 + x6, tmp5, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_sum_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 16
x2 = xindex // 64
x3 = xindex % 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr1 + (64 + x3), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr1 + (128 + x3), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr1 + (192 + x3), xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x4, tmp14, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, 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, 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_6, (1, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_5, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_add_tanh_0[grid(1024)](buf0, buf1, primals_4, buf2,
1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_4
buf3 = reinterpret_tensor(buf1, (256, 1), (1, 1), 0)
del buf1
extern_kernels.mm(reinterpret_tensor(buf2, (256, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 1), (1, 4), 0), out=buf3)
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4, 1), (64, 16, 4, 1, 256), 0
)
del buf0
triton_poi_fused__softmax_1[grid(256)](buf3, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4, 1), (64, 16, 4, 1, 1), 0)
del buf3
triton_poi_fused__softmax_2[grid(256)](buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused_mul_sum_3[grid(256)](buf5, primals_5, buf6, 256,
XBLOCK=128, num_warps=4, num_stages=1)
return buf6, reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_5, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf2, buf5, primals_6
class AdditiveAttentionNew(nn.Module):
def __init__(self, k_size, v_size, hidden_size=None, bias=True):
super(AdditiveAttentionNew, self).__init__()
if hidden_size is None:
hidden_size = v_size
self.W1 = nn.Linear(k_size, hidden_size, bias=False)
self.W2 = nn.Linear(v_size, hidden_size, bias=bias)
self.V = nn.Linear(hidden_size, 1, bias=False)
self.reset_params()
def reset_params(self):
nn.init.xavier_normal_(self.W1.weight)
nn.init.xavier_normal_(self.W2.weight)
nn.init.xavier_uniform_(self.V.weight)
def forward(self, input_0, input_1):
primals_2 = self.W1.weight
primals_3 = self.W2.weight
primals_4 = self.W2.bias
primals_6 = self.V.weight
primals_1 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0], output[1]
|
LindgeW/BiaffineNER
|
AdditiveAttention
| false
| 8,467
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
DilatedCircularConv
|
import torch
import torch.nn as nn
class DilatedCircularConv(nn.Module):
def __init__(self, state_dim, out_state_dim=None, n_adj=4, dilation=1):
super(DilatedCircularConv, self).__init__()
self.n_adj = n_adj
self.dilation = dilation
out_state_dim = state_dim if out_state_dim is None else out_state_dim
self.fc = nn.Conv1d(state_dim, out_state_dim, kernel_size=self.
n_adj * 2 + 1, dilation=self.dilation)
def forward(self, input):
if self.n_adj != 0:
input = torch.cat([input[..., -self.n_adj * self.dilation:],
input, input[..., :self.n_adj * self.dilation]], dim=2)
return self.fc(input)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'state_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
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
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr0 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr0 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 9), (36, 9, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 12), (48, 12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(192)](primals_1, buf0, 192, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return buf2, primals_2, buf0
class DilatedCircularConvNew(nn.Module):
def __init__(self, state_dim, out_state_dim=None, n_adj=4, dilation=1):
super(DilatedCircularConvNew, self).__init__()
self.n_adj = n_adj
self.dilation = dilation
out_state_dim = state_dim if out_state_dim is None else out_state_dim
self.fc = nn.Conv1d(state_dim, out_state_dim, kernel_size=self.
n_adj * 2 + 1, dilation=self.dilation)
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]
|
LiWentomng/boxlevelset
|
DilatedCircularConv
| false
| 8,468
|
[
"Apache-2.0"
] | 25
|
8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
https://github.com/LiWentomng/boxlevelset/tree/8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
CrossEntropyLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def mask_cross_entropy(pred, target, label):
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
pred_slice = pred[inds, label].squeeze(1)
return F.binary_cross_entropy_with_logits(pred_slice, target, reduction
='mean')[None]
def _expand_binary_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(labels >= 1).squeeze()
if inds.numel() > 0:
bin_labels[inds, labels[inds] - 1] = 1
bin_label_weights = label_weights.view(-1, 1).expand(label_weights.size
(0), label_channels)
return bin_labels, bin_label_weights
def weighted_binary_cross_entropy(pred, label, weight, avg_factor=None):
if pred.dim() != label.dim():
label, weight = _expand_binary_labels(label, weight, pred.size(-1))
if avg_factor is None:
avg_factor = max(torch.sum(weight > 0).float().item(), 1.0)
return F.binary_cross_entropy_with_logits(pred, label.float(), weight.
float(), reduction='sum')[None] / avg_factor
def weighted_cross_entropy(pred, label, weight, avg_factor=None, reduce=True):
if avg_factor is None:
avg_factor = max(torch.sum(weight > 0).float().item(), 1.0)
raw = F.cross_entropy(pred, label, reduction='none')
if reduce:
return torch.sum(raw * weight)[None] / avg_factor
else:
return raw * weight / avg_factor
class CrossEntropyLoss(nn.Module):
def __init__(self, use_sigmoid=False, use_mask=False, loss_weight=1.0):
super(CrossEntropyLoss, self).__init__()
assert use_sigmoid is False or use_mask is False
self.use_sigmoid = use_sigmoid
self.use_mask = use_mask
self.loss_weight = loss_weight
if self.use_sigmoid:
self.cls_criterion = weighted_binary_cross_entropy
elif self.use_mask:
self.cls_criterion = mask_cross_entropy
else:
self.cls_criterion = weighted_cross_entropy
def forward(self, cls_score, label, label_weight, *args, **kwargs):
loss_cls = self.loss_weight * self.cls_criterion(cls_score, label,
label_weight, *args, **kwargs)
return loss_cls
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
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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_mul_neg_sum_1(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp13 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp16 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp20 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp24 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp1 = tl_math.exp(tmp0)
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 + tmp3
tmp6 = tl_math.exp(tmp5)
tmp7 = tmp4 + tmp6
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = tmp0 - tmp11
tmp14 = tmp12 * tmp13
tmp15 = tmp2 - tmp11
tmp17 = tmp15 * tmp16
tmp18 = tmp14 + tmp17
tmp19 = tmp5 - tmp11
tmp21 = tmp19 * tmp20
tmp22 = tmp18 + tmp21
tmp23 = tmp8 - tmp11
tmp25 = tmp23 * tmp24
tmp26 = tmp22 + tmp25
tmp27 = -tmp26
tl.store(out_ptr0 + x2, tmp27, xmask)
@triton.jit
def triton_per_fused__log_softmax_div_mul_neg_sum_2(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex % 64
r2 = rindex
tmp0 = tl.load(in_ptr0 + r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + r2, None)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp6 = 0.00390625
tmp7 = tmp5 * tmp6
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp7, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_mul_neg_sum_1[grid(64)](buf0, arg0_1,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del buf0
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = reinterpret_tensor(buf2, (1,), (1,), 0)
del buf2
triton_per_fused__log_softmax_div_mul_neg_sum_2[grid(1)](buf3, buf1,
arg2_1, 1, 256, num_warps=2, num_stages=1)
del arg2_1
del buf1
return buf3,
def mask_cross_entropy(pred, target, label):
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
pred_slice = pred[inds, label].squeeze(1)
return F.binary_cross_entropy_with_logits(pred_slice, target, reduction
='mean')[None]
def _expand_binary_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(labels >= 1).squeeze()
if inds.numel() > 0:
bin_labels[inds, labels[inds] - 1] = 1
bin_label_weights = label_weights.view(-1, 1).expand(label_weights.size
(0), label_channels)
return bin_labels, bin_label_weights
def weighted_binary_cross_entropy(pred, label, weight, avg_factor=None):
if pred.dim() != label.dim():
label, weight = _expand_binary_labels(label, weight, pred.size(-1))
if avg_factor is None:
avg_factor = max(torch.sum(weight > 0).float().item(), 1.0)
return F.binary_cross_entropy_with_logits(pred, label.float(), weight.
float(), reduction='sum')[None] / avg_factor
def weighted_cross_entropy(pred, label, weight, avg_factor=None, reduce=True):
if avg_factor is None:
avg_factor = max(torch.sum(weight > 0).float().item(), 1.0)
raw = F.cross_entropy(pred, label, reduction='none')
if reduce:
return torch.sum(raw * weight)[None] / avg_factor
else:
return raw * weight / avg_factor
class CrossEntropyLossNew(nn.Module):
def __init__(self, use_sigmoid=False, use_mask=False, loss_weight=1.0):
super(CrossEntropyLossNew, self).__init__()
assert use_sigmoid is False or use_mask is False
self.use_sigmoid = use_sigmoid
self.use_mask = use_mask
self.loss_weight = loss_weight
if self.use_sigmoid:
self.cls_criterion = weighted_binary_cross_entropy
elif self.use_mask:
self.cls_criterion = mask_cross_entropy
else:
self.cls_criterion = weighted_cross_entropy
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]
|
LiWentomng/boxlevelset
|
CrossEntropyLoss
| false
| 8,469
|
[
"Apache-2.0"
] | 25
|
8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
https://github.com/LiWentomng/boxlevelset/tree/8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
SmoothL1Loss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def smooth_l1_loss(pred, target, beta=1.0, reduction='mean'):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta
)
reduction_enum = F._Reduction.get_enum(reduction)
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.sum() / pred.numel()
elif reduction_enum == 2:
return loss.sum()
def weighted_smoothl1(pred, target, weight, beta=1.0, avg_factor=None):
if avg_factor is None:
avg_factor = torch.sum(weight > 0).float().item() / 4 + 1e-06
loss = smooth_l1_loss(pred, target, beta, reduction='none')
return torch.sum(loss * weight)[None] / avg_factor
class SmoothL1Loss(nn.Module):
def __init__(self, beta=1.0, loss_weight=1.0):
super(SmoothL1Loss, self).__init__()
self.beta = beta
self.loss_weight = loss_weight
def forward(self, pred, target, weight, *args, **kwargs):
loss_bbox = self.loss_weight * weighted_smoothl1(pred, target,
weight, *args, beta=self.beta, **kwargs)
return loss_bbox
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
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_abs_div_lt_mul_sub_sum_where_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp12 = tl.load(in_ptr2 + r0, None)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = 1.0
tmp5 = tmp3 < tmp4
tmp6 = 0.5
tmp7 = tmp3 * tmp6
tmp8 = tmp7 * tmp3
tmp9 = tmp8 * tmp4
tmp10 = tmp3 - tmp6
tmp11 = tl.where(tmp5, tmp9, tmp10)
tmp13 = tmp11 * tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = 0.015624999755859379
tmp18 = tmp16 * tmp17
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp18, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = reinterpret_tensor(buf0, (1,), (1,), 0)
del buf0
get_raw_stream(0)
triton_per_fused_abs_div_lt_mul_sub_sum_where_0[grid(1)](buf1,
arg0_1, arg1_1, arg2_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf1,
def smooth_l1_loss(pred, target, beta=1.0, reduction='mean'):
assert beta > 0
assert pred.size() == target.size() and target.numel() > 0
diff = torch.abs(pred - target)
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta
)
reduction_enum = F._Reduction.get_enum(reduction)
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.sum() / pred.numel()
elif reduction_enum == 2:
return loss.sum()
def weighted_smoothl1(pred, target, weight, beta=1.0, avg_factor=None):
if avg_factor is None:
avg_factor = torch.sum(weight > 0).float().item() / 4 + 1e-06
loss = smooth_l1_loss(pred, target, beta, reduction='none')
return torch.sum(loss * weight)[None] / avg_factor
class SmoothL1LossNew(nn.Module):
def __init__(self, beta=1.0, loss_weight=1.0):
super(SmoothL1LossNew, self).__init__()
self.beta = beta
self.loss_weight = loss_weight
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
LiWentomng/boxlevelset
|
SmoothL1Loss
| false
| 8,470
|
[
"Apache-2.0"
] | 25
|
8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
https://github.com/LiWentomng/boxlevelset/tree/8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
Biaffine
|
import torch
import torch.nn as nn
class Biaffine(nn.Module):
def __init__(self, in_features, out_features=1, bias=(True, True)):
super(Biaffine, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.bias = bias
self.linear_input_size = in_features + bias[0]
self.linear_output_size = out_features * (in_features + bias[1])
self.linear = nn.Linear(in_features=self.linear_input_size,
out_features=self.linear_output_size, bias=False)
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.linear.weight)
def forward(self, input1, input2):
batch_size, len1, _dim1 = input1.size()
batch_size, len2, _dim2 = input2.size()
if self.bias[0]:
ones = input1.data.new_ones(batch_size, len1, 1)
input1 = torch.cat((input1, ones), dim=-1)
if self.bias[1]:
ones = input2.data.new_ones(batch_size, len2, 1)
input2 = torch.cat((input2, ones), dim=-1)
affine = self.linear(input1)
affine = affine.reshape(batch_size, len1 * self.out_features, -1)
biaffine = torch.bmm(affine, input2.transpose(1, 2)).transpose(1, 2
).contiguous()
biaffine = biaffine.reshape((batch_size, len2, len1, -1)).squeeze(-1)
return biaffine
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
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, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
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], 5, tl.int64)
tmp9 = 1.0
tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
tmp11 = tl.where(tmp6, tmp9, tmp10)
tmp12 = tl.where(tmp4, tmp5, tmp11)
tl.store(out_ptr0 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (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 = 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, (5, 5), (5, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(80)](primals_1, buf0, 80, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 5), (5, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 5), (5, 1), 0),
reinterpret_tensor(primals_3, (5, 5), (1, 5), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
triton_poi_fused_cat_0[grid(80)](primals_2, buf2, 80, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (4, 4, 5), (20, 5, 1),
0), reinterpret_tensor(buf2, (4, 5, 4), (20, 1, 5), 0), out=buf3)
del buf1
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(16, 4)](buf3, buf4, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf3
return buf4, reinterpret_tensor(buf0, (16, 5), (5, 1), 0), buf2
class BiaffineNew(nn.Module):
def __init__(self, in_features, out_features=1, bias=(True, True)):
super(BiaffineNew, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.bias = bias
self.linear_input_size = in_features + bias[0]
self.linear_output_size = out_features * (in_features + bias[1])
self.linear = nn.Linear(in_features=self.linear_input_size,
out_features=self.linear_output_size, bias=False)
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.linear.weight)
def forward(self, input_0, input_1):
primals_3 = self.linear.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LindgeW/BiaffineNER
|
Biaffine
| false
| 8,471
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
BiaffineScorer
|
import torch
import torch.nn as nn
def timestep_dropout(inputs, p=0.5, batch_first=True):
"""
:param inputs: (bz, time_step, feature_size)
:param p: probability p mask out output nodes
:param batch_first: default True
:return:
"""
if not batch_first:
inputs = inputs.transpose(0, 1)
batch_size, _time_step, feature_size = inputs.size()
drop_mask = inputs.data.new_full((batch_size, feature_size), 1 - p)
drop_mask = torch.bernoulli(drop_mask).div(1 - p)
drop_mask = drop_mask.unsqueeze(1)
return inputs * drop_mask
class Biaffine(nn.Module):
def __init__(self, in_features, out_features=1, bias=(True, True)):
super(Biaffine, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.bias = bias
self.linear_input_size = in_features + bias[0]
self.linear_output_size = out_features * (in_features + bias[1])
self.linear = nn.Linear(in_features=self.linear_input_size,
out_features=self.linear_output_size, bias=False)
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.linear.weight)
def forward(self, input1, input2):
batch_size, len1, _dim1 = input1.size()
batch_size, len2, _dim2 = input2.size()
if self.bias[0]:
ones = input1.data.new_ones(batch_size, len1, 1)
input1 = torch.cat((input1, ones), dim=-1)
if self.bias[1]:
ones = input2.data.new_ones(batch_size, len2, 1)
input2 = torch.cat((input2, ones), dim=-1)
affine = self.linear(input1)
affine = affine.reshape(batch_size, len1 * self.out_features, -1)
biaffine = torch.bmm(affine, input2.transpose(1, 2)).transpose(1, 2
).contiguous()
biaffine = biaffine.reshape((batch_size, len2, len1, -1)).squeeze(-1)
return biaffine
class NonlinearMLP(nn.Module):
def __init__(self, in_feature, out_feature, activation=None, bias=True):
super(NonlinearMLP, self).__init__()
if activation is None:
self.activation = lambda x: x
else:
assert callable(activation)
self.activation = activation
self.bias = bias
self.linear = nn.Linear(in_features=in_feature, out_features=
out_feature, bias=bias)
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.linear.weight)
if self.bias:
nn.init.zeros_(self.linear.bias)
def forward(self, inputs):
linear_out = self.linear(inputs)
return self.activation(linear_out)
class BiaffineScorer(nn.Module):
def __init__(self, input_size, ffnn_size, num_cls, ffnn_drop=0.33):
super(BiaffineScorer, self).__init__()
self.ffnn_size = ffnn_size
self.ffnn_drop = ffnn_drop
self._act = nn.ELU()
self.mlp_start = NonlinearMLP(in_feature=input_size, out_feature=
ffnn_size, activation=self._act)
self.mlp_end = NonlinearMLP(in_feature=input_size, out_feature=
ffnn_size, activation=self._act)
self.span_biaff = Biaffine(ffnn_size, num_cls, bias=(True, True))
def forward(self, enc_hn):
start_feat = self.mlp_start(enc_hn)
end_feat = self.mlp_end(enc_hn)
if self.training:
start_feat = timestep_dropout(start_feat, self.ffnn_drop)
end_feat = timestep_dropout(end_feat, self.ffnn_drop)
span_score = self.span_biaff(start_feat, end_feat)
return span_score
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'ffnn_size': 4, 'num_cls': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = 0.0
tmp7 = tmp5 > tmp6
tmp8 = 1.0
tmp9 = tmp5 * tmp8
tmp10 = libdevice.expm1(tmp9)
tmp11 = tmp10 * tmp8
tmp12 = tl.where(tmp7, tmp9, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tl.full([1], 5, tl.int64)
tmp18 = tl.full(tmp8.shape, 0.0, tmp8.dtype)
tmp19 = tl.where(tmp15, tmp8, tmp18)
tmp20 = tl.where(tmp4, tmp14, tmp19)
tl.store(out_ptr0 + x2, tmp20, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 64 * y1), xmask & ymask)
tl.store(out_ptr0 + (x2 + 16 * y3), tmp0, xmask & ymask)
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), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (20, 5), (5, 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((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_3, (16,
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, 5), (20, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(80)](buf0, buf2, 80, XBLOCK=128,
num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((16, 20), (20, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 5), (5, 1), 0),
reinterpret_tensor(primals_6, (5, 20), (1, 5), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
triton_poi_fused_cat_0[grid(80)](buf1, buf4, 80, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (4, 16, 5), (80, 5, 1),
0), reinterpret_tensor(buf4, (4, 5, 4), (20, 1, 5), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_clone_1[grid(16, 16)](buf5, buf6, 16, 16, XBLOCK=
16, YBLOCK=16, num_warps=4, num_stages=1)
del buf5
return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf0, buf1, reinterpret_tensor(buf2, (16, 5), (5, 1), 0
), reinterpret_tensor(buf3, (4, 5, 16), (80, 1, 5), 0), buf4, primals_6
def timestep_dropout(inputs, p=0.5, batch_first=True):
"""
:param inputs: (bz, time_step, feature_size)
:param p: probability p mask out output nodes
:param batch_first: default True
:return:
"""
if not batch_first:
inputs = inputs.transpose(0, 1)
batch_size, _time_step, feature_size = inputs.size()
drop_mask = inputs.data.new_full((batch_size, feature_size), 1 - p)
drop_mask = torch.bernoulli(drop_mask).div(1 - p)
drop_mask = drop_mask.unsqueeze(1)
return inputs * drop_mask
class Biaffine(nn.Module):
def __init__(self, in_features, out_features=1, bias=(True, True)):
super(Biaffine, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.bias = bias
self.linear_input_size = in_features + bias[0]
self.linear_output_size = out_features * (in_features + bias[1])
self.linear = nn.Linear(in_features=self.linear_input_size,
out_features=self.linear_output_size, bias=False)
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.linear.weight)
def forward(self, input1, input2):
batch_size, len1, _dim1 = input1.size()
batch_size, len2, _dim2 = input2.size()
if self.bias[0]:
ones = input1.data.new_ones(batch_size, len1, 1)
input1 = torch.cat((input1, ones), dim=-1)
if self.bias[1]:
ones = input2.data.new_ones(batch_size, len2, 1)
input2 = torch.cat((input2, ones), dim=-1)
affine = self.linear(input1)
affine = affine.reshape(batch_size, len1 * self.out_features, -1)
biaffine = torch.bmm(affine, input2.transpose(1, 2)).transpose(1, 2
).contiguous()
biaffine = biaffine.reshape((batch_size, len2, len1, -1)).squeeze(-1)
return biaffine
class NonlinearMLP(nn.Module):
def __init__(self, in_feature, out_feature, activation=None, bias=True):
super(NonlinearMLP, self).__init__()
if activation is None:
self.activation = lambda x: x
else:
assert callable(activation)
self.activation = activation
self.bias = bias
self.linear = nn.Linear(in_features=in_feature, out_features=
out_feature, bias=bias)
self.reset_params()
def reset_params(self):
nn.init.xavier_uniform_(self.linear.weight)
if self.bias:
nn.init.zeros_(self.linear.bias)
def forward(self, inputs):
linear_out = self.linear(inputs)
return self.activation(linear_out)
class BiaffineScorerNew(nn.Module):
def __init__(self, input_size, ffnn_size, num_cls, ffnn_drop=0.33):
super(BiaffineScorerNew, self).__init__()
self.ffnn_size = ffnn_size
self.ffnn_drop = ffnn_drop
self._act = nn.ELU()
self.mlp_start = NonlinearMLP(in_feature=input_size, out_feature=
ffnn_size, activation=self._act)
self.mlp_end = NonlinearMLP(in_feature=input_size, out_feature=
ffnn_size, activation=self._act)
self.span_biaff = Biaffine(ffnn_size, num_cls, bias=(True, True))
def forward(self, input_0):
primals_1 = self.mlp_start.linear.weight
primals_2 = self.mlp_start.linear.bias
primals_4 = self.mlp_end.linear.weight
primals_5 = self.mlp_end.linear.bias
primals_6 = self.span_biaff.linear.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
LindgeW/BiaffineNER
|
BiaffineScorer
| false
| 8,472
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
ILN
|
import torch
import torch.utils.data
import torch.utils.data.distributed
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class ILN(nn.Module):
def __init__(self, num_features, eps=1e-05):
super(ILN, self).__init__()
self.eps = eps
self.rho = Parameter(torch.Tensor(1, num_features, 1, 1))
self.gamma = Parameter(torch.Tensor(1, num_features, 1, 1))
self.beta = Parameter(torch.Tensor(1, num_features, 1, 1))
self.rho.data.fill_(0.0)
self.gamma.data.fill_(1.0)
self.beta.data.fill_(0.0)
def forward(self, x):
in_mean, in_var = torch.mean(x, dim=[2, 3], keepdim=True), torch.var(x,
dim=[2, 3], keepdim=True)
out_in = (x - in_mean) / torch.sqrt(in_var + self.eps)
ln_mean, ln_var = torch.mean(x, dim=[1, 2, 3], keepdim=True
), torch.var(x, dim=[1, 2, 3], keepdim=True)
out_ln = (x - ln_mean) / torch.sqrt(ln_var + self.eps)
out = self.rho.expand(x.shape[0], -1, -1, -1) * out_in + (1 - self.
rho.expand(x.shape[0], -1, -1, -1)) * out_ln
out = out * self.gamma.expand(x.shape[0], -1, -1, -1
) + self.beta.expand(x.shape[0], -1, -1, -1)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.utils.data
import torch.utils.data.distributed
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_mean_sqrt_var_0(in_out_ptr0, in_out_ptr1, in_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 64.0
tmp20 = tmp4 / tmp19
tmp21 = 63.0
tmp22 = tmp18 / tmp21
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.sqrt(tmp24)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp25, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_sqrt_sub_var_1(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp26 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr3 + x3, xmask, eviction_policy='evict_last')
tmp38 = tl.load(in_ptr4 + x2, xmask, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr5 + x2, xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 16.0
tmp20 = tmp4 / tmp19
tmp21 = 15.0
tmp22 = tmp18 / tmp21
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.sqrt(tmp24)
tmp27 = tmp0 - tmp20
tmp28 = tmp27 / tmp25
tmp29 = tmp26 * tmp28
tmp30 = 1.0
tmp31 = tmp30 - tmp26
tmp33 = tmp0 - tmp32
tmp35 = tmp33 / tmp34
tmp36 = tmp31 * tmp35
tmp37 = tmp29 + tmp36
tmp39 = tmp37 * tmp38
tmp41 = tmp39 + tmp40
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp25, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp41, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_4, (1, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf6 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf9 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf7 = reinterpret_tensor(buf6, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf6
buf11 = reinterpret_tensor(buf9, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf9
get_raw_stream(0)
triton_per_fused_add_mean_sqrt_var_0[grid(4)](buf7, buf11,
primals_1, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
buf5 = reinterpret_tensor(buf3, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf3
buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused_add_div_mean_mul_rsub_sqrt_sub_var_1[grid(16)](buf1,
buf5, primals_1, primals_2, buf7, buf11, primals_3, primals_4,
buf12, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del primals_4
return buf12, primals_1, primals_2, primals_3, buf1, buf5, buf7, buf11
class ILNNew(nn.Module):
def __init__(self, num_features, eps=1e-05):
super(ILNNew, self).__init__()
self.eps = eps
self.rho = Parameter(torch.Tensor(1, num_features, 1, 1))
self.gamma = Parameter(torch.Tensor(1, num_features, 1, 1))
self.beta = Parameter(torch.Tensor(1, num_features, 1, 1))
self.rho.data.fill_(0.0)
self.gamma.data.fill_(1.0)
self.beta.data.fill_(0.0)
def forward(self, input_0):
primals_2 = self.rho
primals_3 = self.gamma
primals_4 = self.beta
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
Lornatang/UGATIT_PyTorch
|
ILN
| false
| 8,473
|
[
"Apache-2.0"
] | 25
|
03519e4829b85ceee67c031a28d5a9318ac932b5
|
https://github.com/Lornatang/UGATIT_PyTorch/tree/03519e4829b85ceee67c031a28d5a9318ac932b5
|
MedianPool2d
|
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn.modules.utils import _pair
from torch.nn.modules.utils import _quadruple
class MedianPool2d(nn.Module):
"""Median pool (usable as median filter when stride=1) module.
Args:
kernel_size: size of pooling kernel, int or 2-tuple
stride: pool stride, int or 2-tuple
padding: pool padding, int or 4-tuple (l, r, t, b) as in pytorch F.pad
same: override padding and enforce same padding, boolean
"""
def __init__(self, kernel_size=3, stride=1, padding=0, same=True):
"""Initialize with kernel_size, stride, padding."""
super().__init__()
self.k = _pair(kernel_size)
self.stride = _pair(stride)
self.padding = _quadruple(padding)
self.same = same
def _padding(self, x):
if self.same:
ih, iw = x.size()[2:]
if ih % self.stride[0] == 0:
ph = max(self.k[0] - self.stride[0], 0)
else:
ph = max(self.k[0] - ih % self.stride[0], 0)
if iw % self.stride[1] == 0:
pw = max(self.k[1] - self.stride[1], 0)
else:
pw = max(self.k[1] - iw % self.stride[1], 0)
pl = pw // 2
pr = pw - pl
pt = ph // 2
pb = ph - pt
padding = pl, pr, pt, pb
else:
padding = self.padding
return padding
def forward(self, x):
x = F.pad(x, self._padding(x), mode='reflect')
x = x.unfold(2, self.k[0], self.stride[0]).unfold(3, self.k[1],
self.stride[1])
x = x.contiguous().view(x.size()[:4] + (-1,)).median(dim=-1)[0]
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 math as tl_math
import torch.nn as nn
from torch.nn.modules.utils import _pair
from torch.nn.modules.utils import _quadruple
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 2304
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 3
x1 = xindex // 3 % 3
x2 = xindex // 9 % 4
x3 = xindex // 36 % 4
x4 = xindex // 144
x5 = xindex
tmp0 = tl.load(in_ptr0 + (15 + -1 * tl_math.abs(-3 + tl_math.abs(-1 +
x0 + x2)) + -4 * tl_math.abs(-3 + tl_math.abs(-1 + x1 + x3)) + 16 *
x4), xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x5, tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 3, 3), (576, 144, 36, 9, 3,
1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(2304)](arg0_1, buf0, 2304, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
buf1 = torch.ops.aten.median.dim(reinterpret_tensor(buf0, (4, 4, 4,
4, 9), (576, 144, 36, 9, 1), 0), -1)
del buf0
buf2 = buf1[0]
del buf1
return buf2,
class MedianPool2dNew(nn.Module):
"""Median pool (usable as median filter when stride=1) module.
Args:
kernel_size: size of pooling kernel, int or 2-tuple
stride: pool stride, int or 2-tuple
padding: pool padding, int or 4-tuple (l, r, t, b) as in pytorch F.pad
same: override padding and enforce same padding, boolean
"""
def __init__(self, kernel_size=3, stride=1, padding=0, same=True):
"""Initialize with kernel_size, stride, padding."""
super().__init__()
self.k = _pair(kernel_size)
self.stride = _pair(stride)
self.padding = _quadruple(padding)
self.same = same
def _padding(self, x):
if self.same:
ih, iw = x.size()[2:]
if ih % self.stride[0] == 0:
ph = max(self.k[0] - self.stride[0], 0)
else:
ph = max(self.k[0] - ih % self.stride[0], 0)
if iw % self.stride[1] == 0:
pw = max(self.k[1] - self.stride[1], 0)
else:
pw = max(self.k[1] - iw % self.stride[1], 0)
pl = pw // 2
pr = pw - pl
pt = ph // 2
pb = ph - pt
padding = pl, pr, pt, pb
else:
padding = self.padding
return padding
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LuckMonkeys/ATSPrivacy
|
MedianPool2d
| false
| 8,474
|
[
"MIT"
] | 14
|
6b580942c6b98b6348d313f2bf90202ec19cefce
|
https://github.com/LuckMonkeys/ATSPrivacy/tree/6b580942c6b98b6348d313f2bf90202ec19cefce
|
MaskedLanguageModel
|
import torch
import torch.optim.lr_scheduler
import torch.nn as nn
import torch.optim
import torch.onnx.operators
class MaskedLanguageModel(nn.Module):
"""
predicting origin token from masked input sequence
n-class classification problem, n-class = vocab_size
"""
def __init__(self, hidden, vocab_size):
"""
:param hidden: output size of BERT model
:param vocab_size: total vocab size
"""
super().__init__()
self.linear = nn.Linear(hidden, vocab_size)
self.softmax = nn.LogSoftmax(dim=-1)
def forward(self, x):
return self.softmax(self.linear(x))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden': 4, 'vocab_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.optim.lr_scheduler
import torch.nn as nn
import torch.optim
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](buf0, buf1, 256, XBLOCK=
256, num_warps=4, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused__log_softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del buf1
return buf2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf2
class MaskedLanguageModelNew(nn.Module):
"""
predicting origin token from masked input sequence
n-class classification problem, n-class = vocab_size
"""
def __init__(self, hidden, vocab_size):
"""
:param hidden: output size of BERT model
:param vocab_size: total vocab size
"""
super().__init__()
self.linear = nn.Linear(hidden, vocab_size)
self.softmax = nn.LogSoftmax(dim=-1)
def forward(self, input_0):
primals_1 = self.linear.weight
primals_2 = self.linear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LogIntelligence/LogADEmpirical
|
MaskedLanguageModel
| false
| 8,475
|
[
"MIT"
] | 11
|
48458aee65c1c84466b04dd4092fae79a7f341fd
|
https://github.com/LogIntelligence/LogADEmpirical/tree/48458aee65c1c84466b04dd4092fae79a7f341fd
|
ToRGB
|
from torch.autograd import Function
import abc
import math
import torch
from torch import nn
import torch.nn.functional as F
from collections import abc
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, channel, in_h, in_w = input.shape
input = input.reshape(-1, in_h, in_w, 1)
_, in_h, in_w, minor = input.shape
kernel_h, kernel_w = kernel.shape
out = input.view(-1, in_h, 1, in_w, 1, minor)
out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
out = out.view(-1, in_h * up_y, in_w * up_x, minor)
out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0),
max(pad_y1, 0)])
out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(-
pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :]
out = out.permute(0, 3, 1, 2)
out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x +
pad_x0 + pad_x1])
w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
out = F.conv2d(out, w)
out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h +
1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1)
out = out.permute(0, 2, 3, 1)
out = out[:, ::down_y, ::down_x, :]
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h + down_y) // down_y
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w + down_x) // down_x
return out.view(-1, channel, out_h, out_w)
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if not isinstance(up, abc.Iterable):
up = up, up
if not isinstance(down, abc.Iterable):
down = down, down
if len(pad) == 2:
pad = pad[0], pad[1], pad[0], pad[1]
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, *up, *down, *pad)
else:
out = UpFirDn2d.apply(input, kernel, up, down, pad)
return out
def fused_leaky_relu(input, bias=None, negative_slope=0.2, scale=2 ** 0.5):
if input.device.type == 'cpu':
if bias is not None:
rest_dim = [1] * (input.ndim - bias.ndim - 1)
return F.leaky_relu(input + bias.view(1, bias.shape[0], *
rest_dim), negative_slope=0.2) * scale
else:
return F.leaky_relu(input, negative_slope=0.2) * scale
else:
return FusedLeakyReLUFunction.apply(input.contiguous(), bias,
negative_slope, scale)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h + down_y) // down_y
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w + down_x) // down_x
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = None
if ctx.needs_input_grad[0]:
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.
in_size, ctx.out_size)
return grad_input, None, None, None, None
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * factor ** 2
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = pad0, pad1
def forward(self, input):
out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=
self.pad)
return out
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, input):
out = upfirdn2d(input, self.kernel, pad=self.pad)
return out
class FusedLeakyReLUFunctionBackward(Function):
@staticmethod
def forward(ctx, grad_output, out, bias, negative_slope, scale):
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
empty = grad_output.new_empty(0)
grad_input = fused.fused_bias_act(grad_output.contiguous(), empty,
out, 3, 1, negative_slope, scale)
dim = [0]
if grad_input.ndim > 2:
dim += list(range(2, grad_input.ndim))
if bias:
grad_bias = grad_input.sum(dim).detach()
else:
grad_bias = empty
return grad_input, grad_bias
@staticmethod
def backward(ctx, gradgrad_input, gradgrad_bias):
out, = ctx.saved_tensors
gradgrad_out = fused.fused_bias_act(gradgrad_input.contiguous(),
gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale)
return gradgrad_out, None, None, None, None
class FusedLeakyReLUFunction(Function):
@staticmethod
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
ctx.bias = bias is not None
if bias is None:
bias = empty
out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope,
scale)
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
return out
@staticmethod
def backward(ctx, grad_output):
out, = ctx.saved_tensors
grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(
grad_output, out, ctx.bias, ctx.negative_slope, ctx.scale)
if not ctx.bias:
grad_bias = None
return grad_input, grad_bias, None, None
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, input):
if self.activation:
out = F.linear(input, self.weight * self.scale)
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
out = F.linear(input, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=[1,
3, 3, 1], fused=True):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2 + 1
self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor
=factor)
if downsample:
factor = 2
p = len(blur_kernel) - factor + (kernel_size - 1)
pad0 = (p + 1) // 2
pad1 = p // 2
self.blur = Blur(blur_kernel, pad=(pad0, pad1))
fan_in = in_channel * kernel_size ** 2
self.scale = 1 / math.sqrt(fan_in)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
self.fused = fused
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, input, style):
batch, in_channel, height, width = input.shape
if not self.fused:
weight = self.scale * self.weight.squeeze(0)
style = self.modulation(style)
if self.demodulate:
w = weight.unsqueeze(0) * style.view(batch, 1, in_channel, 1, 1
)
dcoefs = (w.square().sum((2, 3, 4)) + 1e-08).rsqrt()
input = input * style.reshape(batch, in_channel, 1, 1)
if self.upsample:
weight = weight.transpose(0, 1)
out = F.conv_transpose2d(input, weight, padding=0, stride=2)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
out = F.conv2d(input, weight, padding=0, stride=2)
else:
out = F.conv2d(input, weight, padding=self.padding)
if self.demodulate:
out = out * dcoefs.view(batch, -1, 1, 1)
return out
style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
weight = self.scale * self.weight * style
if self.demodulate:
demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-08)
weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)
weight = weight.view(batch * self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
if self.upsample:
input = input.view(1, batch * in_channel, height, width)
weight = weight.view(batch, self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
weight = weight.transpose(1, 2).reshape(batch * in_channel,
self.out_channel, self.kernel_size, self.kernel_size)
out = F.conv_transpose2d(input, weight, padding=0, stride=2,
groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
_, _, height, width = input.shape
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=0, stride=2, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
else:
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=self.padding, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
return out
class ToRGB(nn.Module):
def __init__(self, in_channel, image_channel, style_dim, upsample=True,
blur_kernel=[1, 3, 3, 1]):
super().__init__()
if upsample:
self.upsample = Upsample(blur_kernel)
self.conv = ModulatedConv2d(in_channel, image_channel, 1, style_dim,
demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, image_channel, 1, 1))
def forward(self, input, style, skip=None):
out = self.conv(input, style)
out = out + self.bias
if skip is not None:
skip = self.upsample(skip)
out = out + skip
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'image_channel': 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
from torch.autograd import Function
import abc
import math
from torch import nn
import torch.nn.functional as F
from collections import abc
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 16
x0 = xindex % 4
x2 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x4, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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, 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, (1, 4, 4, 1, 1), (16, 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)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, primals_4, reinterpret_tensor(buf0, (4,
4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del buf0
del buf1
buf3 = empty_strided_cuda((4, 4, 4, 1, 1), (16, 4, 1, 1, 1), torch.
float32)
triton_poi_fused_mul_2[grid(64)](primals_5, buf2, buf3, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf4 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf3, (16, 4,
1, 1), (4, 1, 0, 0), 0), stride=(1, 1), padding=(0, 0),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf4, (1, 16, 4, 4), (256, 16, 4, 1))
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused_add_3[grid(256)](buf5, primals_6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_6
return buf5, primals_4, primals_5, buf2, reinterpret_tensor(buf3, (16,
4, 1, 1), (4, 1, 1, 1), 0), reinterpret_tensor(primals_1, (1, 16, 4,
4), (256, 16, 4, 1), 0)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
return k
def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0,
pad_x1, pad_y0, pad_y1):
_, channel, in_h, in_w = input.shape
input = input.reshape(-1, in_h, in_w, 1)
_, in_h, in_w, minor = input.shape
kernel_h, kernel_w = kernel.shape
out = input.view(-1, in_h, 1, in_w, 1, minor)
out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
out = out.view(-1, in_h * up_y, in_w * up_x, minor)
out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0),
max(pad_y1, 0)])
out = out[:, max(-pad_y0, 0):out.shape[1] - max(-pad_y1, 0), max(-
pad_x0, 0):out.shape[2] - max(-pad_x1, 0), :]
out = out.permute(0, 3, 1, 2)
out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x +
pad_x0 + pad_x1])
w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
out = F.conv2d(out, w)
out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h +
1, in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1)
out = out.permute(0, 2, 3, 1)
out = out[:, ::down_y, ::down_x, :]
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h + down_y) // down_y
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w + down_x) // down_x
return out.view(-1, channel, out_h, out_w)
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
if not isinstance(up, abc.Iterable):
up = up, up
if not isinstance(down, abc.Iterable):
down = down, down
if len(pad) == 2:
pad = pad[0], pad[1], pad[0], pad[1]
if input.device.type == 'cpu':
out = upfirdn2d_native(input, kernel, *up, *down, *pad)
else:
out = UpFirDn2d.apply(input, kernel, up, down, pad)
return out
def fused_leaky_relu(input, bias=None, negative_slope=0.2, scale=2 ** 0.5):
if input.device.type == 'cpu':
if bias is not None:
rest_dim = [1] * (input.ndim - bias.ndim - 1)
return F.leaky_relu(input + bias.view(1, bias.shape[0], *
rest_dim), negative_slope=0.2) * scale
else:
return F.leaky_relu(input, negative_slope=0.2) * scale
else:
return FusedLeakyReLUFunction.apply(input.contiguous(), bias,
negative_slope, scale)
class UpFirDn2dBackward(Function):
@staticmethod
def forward(ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad,
in_size, out_size):
up_x, up_y = up
down_x, down_y = down
g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad
grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1)
grad_input = upfirdn2d_op.upfirdn2d(grad_output, grad_kernel,
down_x, down_y, up_x, up_y, g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1)
grad_input = grad_input.view(in_size[0], in_size[1], in_size[2],
in_size[3])
ctx.save_for_backward(kernel)
pad_x0, pad_x1, pad_y0, pad_y1 = pad
ctx.up_x = up_x
ctx.up_y = up_y
ctx.down_x = down_x
ctx.down_y = down_y
ctx.pad_x0 = pad_x0
ctx.pad_x1 = pad_x1
ctx.pad_y0 = pad_y0
ctx.pad_y1 = pad_y1
ctx.in_size = in_size
ctx.out_size = out_size
return grad_input
@staticmethod
def backward(ctx, gradgrad_input):
kernel, = ctx.saved_tensors
gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.
in_size[3], 1)
gradgrad_out = upfirdn2d_op.upfirdn2d(gradgrad_input, kernel, ctx.
up_x, ctx.up_y, ctx.down_x, ctx.down_y, ctx.pad_x0, ctx.pad_x1,
ctx.pad_y0, ctx.pad_y1)
gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.in_size[1],
ctx.out_size[0], ctx.out_size[1])
return gradgrad_out, None, None, None, None, None, None, None, None
class UpFirDn2d(Function):
@staticmethod
def forward(ctx, input, kernel, up, down, pad):
up_x, up_y = up
down_x, down_y = down
pad_x0, pad_x1, pad_y0, pad_y1 = pad
kernel_h, kernel_w = kernel.shape
_batch, channel, in_h, in_w = input.shape
ctx.in_size = input.shape
input = input.reshape(-1, in_h, in_w, 1)
ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1]))
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h + down_y) // down_y
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w + down_x) // down_x
ctx.out_size = out_h, out_w
ctx.up = up_x, up_y
ctx.down = down_x, down_y
ctx.pad = pad_x0, pad_x1, pad_y0, pad_y1
g_pad_x0 = kernel_w - pad_x0 - 1
g_pad_y0 = kernel_h - pad_y0 - 1
g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1
g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1
ctx.g_pad = g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1
out = upfirdn2d_op.upfirdn2d(input, kernel, up_x, up_y, down_x,
down_y, pad_x0, pad_x1, pad_y0, pad_y1)
out = out.view(-1, channel, out_h, out_w)
return out
@staticmethod
def backward(ctx, grad_output):
kernel, grad_kernel = ctx.saved_tensors
grad_input = None
if ctx.needs_input_grad[0]:
grad_input = UpFirDn2dBackward.apply(grad_output, kernel,
grad_kernel, ctx.up, ctx.down, ctx.pad, ctx.g_pad, ctx.
in_size, ctx.out_size)
return grad_input, None, None, None, None
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * factor ** 2
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = pad0, pad1
def forward(self, input):
out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=
self.pad)
return out
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, input):
out = upfirdn2d(input, self.kernel, pad=self.pad)
return out
class FusedLeakyReLUFunctionBackward(Function):
@staticmethod
def forward(ctx, grad_output, out, bias, negative_slope, scale):
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
empty = grad_output.new_empty(0)
grad_input = fused.fused_bias_act(grad_output.contiguous(), empty,
out, 3, 1, negative_slope, scale)
dim = [0]
if grad_input.ndim > 2:
dim += list(range(2, grad_input.ndim))
if bias:
grad_bias = grad_input.sum(dim).detach()
else:
grad_bias = empty
return grad_input, grad_bias
@staticmethod
def backward(ctx, gradgrad_input, gradgrad_bias):
out, = ctx.saved_tensors
gradgrad_out = fused.fused_bias_act(gradgrad_input.contiguous(),
gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale)
return gradgrad_out, None, None, None, None
class FusedLeakyReLUFunction(Function):
@staticmethod
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
ctx.bias = bias is not None
if bias is None:
bias = empty
out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope,
scale)
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
return out
@staticmethod
def backward(ctx, grad_output):
out, = ctx.saved_tensors
grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(
grad_output, out, ctx.bias, ctx.negative_slope, ctx.scale)
if not ctx.bias:
grad_bias = None
return grad_input, grad_bias, None, None
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, input):
if self.activation:
out = F.linear(input, self.weight * self.scale)
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
out = F.linear(input, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=[1,
3, 3, 1], fused=True):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2 + 1
self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor
=factor)
if downsample:
factor = 2
p = len(blur_kernel) - factor + (kernel_size - 1)
pad0 = (p + 1) // 2
pad1 = p // 2
self.blur = Blur(blur_kernel, pad=(pad0, pad1))
fan_in = in_channel * kernel_size ** 2
self.scale = 1 / math.sqrt(fan_in)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
self.fused = fused
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, input, style):
batch, in_channel, height, width = input.shape
if not self.fused:
weight = self.scale * self.weight.squeeze(0)
style = self.modulation(style)
if self.demodulate:
w = weight.unsqueeze(0) * style.view(batch, 1, in_channel, 1, 1
)
dcoefs = (w.square().sum((2, 3, 4)) + 1e-08).rsqrt()
input = input * style.reshape(batch, in_channel, 1, 1)
if self.upsample:
weight = weight.transpose(0, 1)
out = F.conv_transpose2d(input, weight, padding=0, stride=2)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
out = F.conv2d(input, weight, padding=0, stride=2)
else:
out = F.conv2d(input, weight, padding=self.padding)
if self.demodulate:
out = out * dcoefs.view(batch, -1, 1, 1)
return out
style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
weight = self.scale * self.weight * style
if self.demodulate:
demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-08)
weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)
weight = weight.view(batch * self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
if self.upsample:
input = input.view(1, batch * in_channel, height, width)
weight = weight.view(batch, self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
weight = weight.transpose(1, 2).reshape(batch * in_channel,
self.out_channel, self.kernel_size, self.kernel_size)
out = F.conv_transpose2d(input, weight, padding=0, stride=2,
groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
_, _, height, width = input.shape
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=0, stride=2, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
else:
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=self.padding, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
return out
class ToRGBNew(nn.Module):
def __init__(self, in_channel, image_channel, style_dim, upsample=True,
blur_kernel=[1, 3, 3, 1]):
super().__init__()
if upsample:
self.upsample = Upsample(blur_kernel)
self.conv = ModulatedConv2d(in_channel, image_channel, 1, style_dim,
demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, image_channel, 1, 1))
def forward(self, input_0, input_1):
primals_6 = self.bias
primals_5 = self.conv.weight
primals_2 = self.conv.modulation.weight
primals_3 = self.conv.modulation.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
LizhenWangT/FaceVerse
|
ToRGB
| false
| 8,476
|
[
"BSD-2-Clause",
"MIT"
] | 20
|
bb4a5d3e52fb10b34bbe94f055ff637095bf9152
|
https://github.com/LizhenWangT/FaceVerse/tree/bb4a5d3e52fb10b34bbe94f055ff637095bf9152
|
HausdorffLoss
|
import torch
import torch.nn as nn
class HausdorffLoss(nn.Module):
def __init__(self, loss_weight=1.0):
super(HausdorffLoss, self).__init__()
self.weight = loss_weight
def forward(self, set1, set2):
"""
Compute the Averaged Hausdorff Distance function
between two unordered sets of points (the function is symmetric).
Batches are not supported, so squeeze your inputs first!
:param set1: Tensor where each row is an N-dimensional point.
:param set2: Tensor where each row is an N-dimensional point.
:return: The Averaged Hausdorff Distance between set1 and set2.
"""
assert set1.ndimension() == 3, 'got %s' % set1.ndimension()
assert set2.ndimension() == 3, 'got %s' % set2.ndimension()
if set1.shape[0] > 0:
assert set1.size()[1] == set2.size()[1
], 'The points in both sets must have the same number of dimensions, got %s and %s.' % (
set1.size()[1], set2.size()[1])
""" the second implement to avoid the CUDA out of the memory
need the size to be set1: (N, 40, 2), set2:(N, 40, 2)"""
d2_matrix = torch.stack([self.cdist(item1, item2) for item1,
item2 in zip(set1, set2)], dim=0)
term_1 = torch.mean(torch.min(d2_matrix, 2)[0], -1)
term_2 = torch.mean(torch.min(d2_matrix, 1)[0], -1)
res = term_1 + term_2
else:
res = set1.sum() * 0
return res * self.weight
def cdist(self, x, y):
"""
Compute distance between each pair of the two collections of inputs.
:param x: Nxd Tensor
:param y: Mxd Tensor
:res: NxM matrix where dist[i,j] is the norm between x[i,:] and y[j,:],
i.e. dist[i,j] = ||x[i,:]-y[j,:]||
"""
differences = x.unsqueeze(1) - y.unsqueeze(0)
distances = torch.sum(differences ** 2, -1).sqrt()
return distances
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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_stack_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
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + 4 * x1, tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + 4 * x0, tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tmp5 - tmp6
tmp8 = tmp7 * tmp7
tmp9 = tl.load(in_ptr0 + (1 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp10 = tl.load(in_ptr1 + (1 + 4 * x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp14 = tl.load(in_ptr0 + (2 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tl.load(in_ptr1 + (2 + 4 * x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tl.load(in_ptr0 + (3 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = tl.load(in_ptr1 + (3 + 4 * x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp21 = tmp19 - tmp20
tmp22 = tmp21 * tmp21
tmp23 = tmp18 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp4, tmp24, tmp25)
tmp27 = tmp0 >= tmp3
tmp28 = tl.full([1], 8, tl.int64)
tmp29 = tmp0 < tmp28
tmp30 = tmp27 & tmp29
tmp31 = tl.load(in_ptr0 + (16 + 4 * (-4 + x1)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp32 = tl.load(in_ptr1 + (16 + 4 * x0), tmp30 & xmask, eviction_policy
='evict_last', other=0.0)
tmp33 = tmp31 - tmp32
tmp34 = tmp33 * tmp33
tmp35 = tl.load(in_ptr0 + (17 + 4 * (-4 + x1)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp36 = tl.load(in_ptr1 + (17 + 4 * x0), tmp30 & xmask, eviction_policy
='evict_last', other=0.0)
tmp37 = tmp35 - tmp36
tmp38 = tmp37 * tmp37
tmp39 = tmp34 + tmp38
tmp40 = tl.load(in_ptr0 + (18 + 4 * (-4 + x1)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp41 = tl.load(in_ptr1 + (18 + 4 * x0), tmp30 & xmask, eviction_policy
='evict_last', other=0.0)
tmp42 = tmp40 - tmp41
tmp43 = tmp42 * tmp42
tmp44 = tmp39 + tmp43
tmp45 = tl.load(in_ptr0 + (19 + 4 * (-4 + x1)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp46 = tl.load(in_ptr1 + (19 + 4 * x0), tmp30 & xmask, eviction_policy
='evict_last', other=0.0)
tmp47 = tmp45 - tmp46
tmp48 = tmp47 * tmp47
tmp49 = tmp44 + tmp48
tmp50 = libdevice.sqrt(tmp49)
tmp51 = tl.full(tmp50.shape, 0.0, tmp50.dtype)
tmp52 = tl.where(tmp30, tmp50, tmp51)
tmp53 = tmp0 >= tmp28
tmp54 = tl.full([1], 12, tl.int64)
tmp55 = tmp0 < tmp54
tmp56 = tmp53 & tmp55
tmp57 = tl.load(in_ptr0 + (32 + 4 * (-8 + x1)), tmp56 & xmask,
eviction_policy='evict_last', other=0.0)
tmp58 = tl.load(in_ptr1 + (32 + 4 * x0), tmp56 & xmask, eviction_policy
='evict_last', other=0.0)
tmp59 = tmp57 - tmp58
tmp60 = tmp59 * tmp59
tmp61 = tl.load(in_ptr0 + (33 + 4 * (-8 + x1)), tmp56 & xmask,
eviction_policy='evict_last', other=0.0)
tmp62 = tl.load(in_ptr1 + (33 + 4 * x0), tmp56 & xmask, eviction_policy
='evict_last', other=0.0)
tmp63 = tmp61 - tmp62
tmp64 = tmp63 * tmp63
tmp65 = tmp60 + tmp64
tmp66 = tl.load(in_ptr0 + (34 + 4 * (-8 + x1)), tmp56 & xmask,
eviction_policy='evict_last', other=0.0)
tmp67 = tl.load(in_ptr1 + (34 + 4 * x0), tmp56 & xmask, eviction_policy
='evict_last', other=0.0)
tmp68 = tmp66 - tmp67
tmp69 = tmp68 * tmp68
tmp70 = tmp65 + tmp69
tmp71 = tl.load(in_ptr0 + (35 + 4 * (-8 + x1)), tmp56 & xmask,
eviction_policy='evict_last', other=0.0)
tmp72 = tl.load(in_ptr1 + (35 + 4 * x0), tmp56 & xmask, eviction_policy
='evict_last', other=0.0)
tmp73 = tmp71 - tmp72
tmp74 = tmp73 * tmp73
tmp75 = tmp70 + tmp74
tmp76 = libdevice.sqrt(tmp75)
tmp77 = tl.full(tmp76.shape, 0.0, tmp76.dtype)
tmp78 = tl.where(tmp56, tmp76, tmp77)
tmp79 = tmp0 >= tmp54
tl.full([1], 16, tl.int64)
tmp82 = tl.load(in_ptr0 + (48 + 4 * (-12 + x1)), tmp79 & xmask,
eviction_policy='evict_last', other=0.0)
tmp83 = tl.load(in_ptr1 + (48 + 4 * x0), tmp79 & xmask, eviction_policy
='evict_last', other=0.0)
tmp84 = tmp82 - tmp83
tmp85 = tmp84 * tmp84
tmp86 = tl.load(in_ptr0 + (49 + 4 * (-12 + x1)), tmp79 & xmask,
eviction_policy='evict_last', other=0.0)
tmp87 = tl.load(in_ptr1 + (49 + 4 * x0), tmp79 & xmask, eviction_policy
='evict_last', other=0.0)
tmp88 = tmp86 - tmp87
tmp89 = tmp88 * tmp88
tmp90 = tmp85 + tmp89
tmp91 = tl.load(in_ptr0 + (50 + 4 * (-12 + x1)), tmp79 & xmask,
eviction_policy='evict_last', other=0.0)
tmp92 = tl.load(in_ptr1 + (50 + 4 * x0), tmp79 & xmask, eviction_policy
='evict_last', other=0.0)
tmp93 = tmp91 - tmp92
tmp94 = tmp93 * tmp93
tmp95 = tmp90 + tmp94
tmp96 = tl.load(in_ptr0 + (51 + 4 * (-12 + x1)), tmp79 & xmask,
eviction_policy='evict_last', other=0.0)
tmp97 = tl.load(in_ptr1 + (51 + 4 * x0), tmp79 & xmask, eviction_policy
='evict_last', other=0.0)
tmp98 = tmp96 - tmp97
tmp99 = tmp98 * tmp98
tmp100 = tmp95 + tmp99
tmp101 = libdevice.sqrt(tmp100)
tmp102 = tl.full(tmp101.shape, 0.0, tmp101.dtype)
tmp103 = tl.where(tmp79, tmp101, tmp102)
tmp104 = tl.where(tmp56, tmp78, tmp103)
tmp105 = tl.where(tmp30, tmp52, tmp104)
tmp106 = tl.where(tmp4, tmp26, tmp105)
tl.store(out_ptr0 + x2, tmp106, xmask)
@triton.jit
def triton_poi_fused_add_mean_min_mul_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_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp7 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp8 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp10 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp20 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp24 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp26 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp28 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = triton_helpers.minimum(tmp0, tmp1)
tmp4 = triton_helpers.minimum(tmp2, tmp3)
tmp6 = triton_helpers.minimum(tmp4, tmp5)
tmp9 = triton_helpers.minimum(tmp7, tmp8)
tmp11 = triton_helpers.minimum(tmp9, tmp10)
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tmp14 = tmp6 + tmp13
tmp17 = triton_helpers.minimum(tmp15, tmp16)
tmp19 = triton_helpers.minimum(tmp17, tmp18)
tmp21 = triton_helpers.minimum(tmp19, tmp20)
tmp22 = tmp14 + tmp21
tmp25 = triton_helpers.minimum(tmp23, tmp24)
tmp27 = triton_helpers.minimum(tmp25, tmp26)
tmp29 = triton_helpers.minimum(tmp27, tmp28)
tmp30 = tmp22 + tmp29
tmp31 = 4.0
tmp32 = tmp30 / tmp31
tmp33 = triton_helpers.minimum(tmp0, tmp7)
tmp34 = triton_helpers.minimum(tmp33, tmp15)
tmp35 = triton_helpers.minimum(tmp34, tmp23)
tmp36 = triton_helpers.minimum(tmp1, tmp8)
tmp37 = triton_helpers.minimum(tmp36, tmp16)
tmp38 = triton_helpers.minimum(tmp37, tmp24)
tmp39 = tmp35 + tmp38
tmp40 = triton_helpers.minimum(tmp3, tmp10)
tmp41 = triton_helpers.minimum(tmp40, tmp18)
tmp42 = triton_helpers.minimum(tmp41, tmp26)
tmp43 = tmp39 + tmp42
tmp44 = triton_helpers.minimum(tmp5, tmp12)
tmp45 = triton_helpers.minimum(tmp44, tmp20)
tmp46 = triton_helpers.minimum(tmp45, tmp28)
tmp47 = tmp43 + tmp46
tmp48 = tmp47 / tmp31
tmp49 = tmp32 + tmp48
tmp50 = 1.0
tmp51 = tmp49 * tmp50
tl.store(in_out_ptr0 + x0, tmp51, 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((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_stack_0[grid(64)](arg0_1, arg1_1, buf0, 64, XBLOCK
=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf3 = buf1
del buf1
triton_poi_fused_add_mean_min_mul_1[grid(4)](buf3, buf0, 4, XBLOCK=
4, num_warps=1, num_stages=1)
del buf0
return buf3,
class HausdorffLossNew(nn.Module):
def __init__(self, loss_weight=1.0):
super(HausdorffLossNew, self).__init__()
self.weight = loss_weight
def cdist(self, x, y):
"""
Compute distance between each pair of the two collections of inputs.
:param x: Nxd Tensor
:param y: Mxd Tensor
:res: NxM matrix where dist[i,j] is the norm between x[i,:] and y[j,:],
i.e. dist[i,j] = ||x[i,:]-y[j,:]||
"""
differences = x.unsqueeze(1) - y.unsqueeze(0)
distances = torch.sum(differences ** 2, -1).sqrt()
return distances
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
LiWentomng/boxlevelset
|
HausdorffLoss
| false
| 8,477
|
[
"Apache-2.0"
] | 25
|
8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
https://github.com/LiWentomng/boxlevelset/tree/8cc40bf6ae4a343c482c676c72259cc12c29d31c
|
Generator
|
import torch
import torch.optim.lr_scheduler
import torch.nn as nn
import torch.optim
import torch.onnx.operators
def masked_softmax(vector: 'torch.Tensor', mask: 'torch.Tensor', dim: 'int'
=-1, memory_efficient: 'bool'=False, mask_fill_value: 'float'=-1e+32
) ->torch.Tensor:
"""
``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular softmax.
``vector`` can have an arbitrary number of dimensions; the only requirement is that ``mask`` is
broadcastable to ``vector's`` shape. If ``mask`` has fewer dimensions than ``vector``, we will
unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,
do it yourself before passing the mask into this function.
If ``memory_efficient`` is set to true, we will simply use a very large negative number for those
masked positions so that the probabilities of those positions would be approximately 0.
This is not accurate in math, but works for most cases and consumes less memory.
In the case that the input vector is completely masked and ``memory_efficient`` is false, this function
returns an array of ``0.0``. This behavior may cause ``NaN`` if this is used as the last layer of
a model that uses categorical cross-entropy loss. Instead, if ``memory_efficient`` is true, this function
will treat every element as equal, and do softmax over equal numbers.
"""
if mask is None:
result = torch.nn.functional.softmax(vector, dim=dim)
else:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
if not memory_efficient:
result = torch.nn.functional.softmax(vector * mask, dim=dim)
result = result * mask
result = result / (result.sum(dim=dim, keepdim=True) + 1e-13)
else:
masked_vector = vector.masked_fill((1 - mask).byte(),
mask_fill_value)
result = torch.nn.functional.softmax(masked_vector, dim=dim)
return result
class Generator(torch.nn.Module):
"""
An ``Attention`` takes two inputs: a (batched) vector and a matrix, plus an optional mask on the
rows of the matrix. We compute the similarity between the vector and each row in the matrix,
and then (optionally) perform a softmax over rows using those computed similarities.
Inputs:
- vector: shape ``(batch_size, embedding_dim)``
- matrix: shape ``(batch_size, num_rows, embedding_dim)``
- matrix_mask: shape ``(batch_size, num_rows)``, specifying which rows are just padding.
Output:
- attention: shape ``(batch_size, num_rows)``.
Parameters
----------
normalize : ``bool``, optional (default: ``True``)
If true, we normalize the computed similarities with a softmax, to return a probability
distribution for your attention. If false, this is just computing a similarity score.
"""
def __init__(self, tensor_1_dim: 'int', tensor_2_dim: 'int'):
super(Generator, self).__init__()
self.project = nn.Linear(in_features=tensor_1_dim, out_features=
tensor_2_dim)
def forward(self, vector: 'torch.Tensor', matrix: 'torch.Tensor',
matrix_mask: 'torch.Tensor'=None) ->torch.Tensor:
trans_vec = self.project(vector)
_batch, length, _dim = matrix.size()
new_vec = torch.unsqueeze(trans_vec, dim=2).expand(-1, -1, length)
new_vec = new_vec.transpose(1, 2)
product = new_vec * matrix
similarities = torch.sum(product, dim=2)
probs = masked_softmax(similarities, matrix_mask)
return probs
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'tensor_1_dim': 4, 'tensor_2_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.optim.lr_scheduler
import torch.nn as nn
import torch.optim
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_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_sum_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + 4 * x2, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + 1)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp10 = tl.load(in_ptr2 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + 2)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp17 = tl.load(in_ptr2 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + 3)
tmp22 = tl.broadcast_to(tmp21, [XBLOCK])
tmp24 = tl.load(in_ptr2 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp3 = tmp0 + tmp2
tmp5 = tmp3 * tmp4
tmp9 = tmp6 + tmp8
tmp11 = tmp9 * tmp10
tmp12 = tmp5 + tmp11
tmp16 = tmp13 + tmp15
tmp18 = tmp16 * tmp17
tmp19 = tmp12 + tmp18
tmp23 = tmp20 + tmp22
tmp25 = tmp23 * tmp24
tmp26 = tmp19 + tmp25
tl.store(out_ptr0 + x2, tmp26, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((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, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sum_0[grid(16)](buf0, primals_2, primals_4,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf2 = buf0
del buf0
triton_poi_fused__softmax_1[grid(16)](buf1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf3 = buf1
del buf1
triton_poi_fused__softmax_2[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf2
return buf3, primals_3, primals_4, buf3
def masked_softmax(vector: 'torch.Tensor', mask: 'torch.Tensor', dim: 'int'
=-1, memory_efficient: 'bool'=False, mask_fill_value: 'float'=-1e+32
) ->torch.Tensor:
"""
``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular softmax.
``vector`` can have an arbitrary number of dimensions; the only requirement is that ``mask`` is
broadcastable to ``vector's`` shape. If ``mask`` has fewer dimensions than ``vector``, we will
unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,
do it yourself before passing the mask into this function.
If ``memory_efficient`` is set to true, we will simply use a very large negative number for those
masked positions so that the probabilities of those positions would be approximately 0.
This is not accurate in math, but works for most cases and consumes less memory.
In the case that the input vector is completely masked and ``memory_efficient`` is false, this function
returns an array of ``0.0``. This behavior may cause ``NaN`` if this is used as the last layer of
a model that uses categorical cross-entropy loss. Instead, if ``memory_efficient`` is true, this function
will treat every element as equal, and do softmax over equal numbers.
"""
if mask is None:
result = torch.nn.functional.softmax(vector, dim=dim)
else:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
if not memory_efficient:
result = torch.nn.functional.softmax(vector * mask, dim=dim)
result = result * mask
result = result / (result.sum(dim=dim, keepdim=True) + 1e-13)
else:
masked_vector = vector.masked_fill((1 - mask).byte(),
mask_fill_value)
result = torch.nn.functional.softmax(masked_vector, dim=dim)
return result
class GeneratorNew(torch.nn.Module):
"""
An ``Attention`` takes two inputs: a (batched) vector and a matrix, plus an optional mask on the
rows of the matrix. We compute the similarity between the vector and each row in the matrix,
and then (optionally) perform a softmax over rows using those computed similarities.
Inputs:
- vector: shape ``(batch_size, embedding_dim)``
- matrix: shape ``(batch_size, num_rows, embedding_dim)``
- matrix_mask: shape ``(batch_size, num_rows)``, specifying which rows are just padding.
Output:
- attention: shape ``(batch_size, num_rows)``.
Parameters
----------
normalize : ``bool``, optional (default: ``True``)
If true, we normalize the computed similarities with a softmax, to return a probability
distribution for your attention. If false, this is just computing a similarity score.
"""
def __init__(self, tensor_1_dim: 'int', tensor_2_dim: 'int'):
super(GeneratorNew, self).__init__()
self.project = nn.Linear(in_features=tensor_1_dim, out_features=
tensor_2_dim)
def forward(self, input_0, input_1):
primals_1 = self.project.weight
primals_2 = self.project.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
LogIntelligence/LogADEmpirical
|
Generator
| false
| 8,478
|
[
"MIT"
] | 11
|
48458aee65c1c84466b04dd4092fae79a7f341fd
|
https://github.com/LogIntelligence/LogADEmpirical/tree/48458aee65c1c84466b04dd4092fae79a7f341fd
|
NextSentencePrediction
|
import torch
import torch.optim.lr_scheduler
import torch.nn as nn
import torch.optim
import torch.onnx.operators
class NextSentencePrediction(nn.Module):
"""
2-class classification model : is_next, is_not_next
"""
def __init__(self, hidden):
"""
:param hidden: BERT model output size
"""
super().__init__()
self.linear = nn.Linear(hidden, 2)
self.softmax = nn.LogSoftmax(dim=-1)
def forward(self, x):
return self.softmax(self.linear(x[:, 0]))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.optim.lr_scheduler
import torch.nn as nn
import torch.optim
import torch.onnx.operators
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused__log_softmax_add_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
x1 = xindex // 2
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp7 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + 1)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp6 = tmp3 + tmp5
tmp10 = tmp7 + tmp9
tmp11 = triton_helpers.maximum(tmp6, tmp10)
tmp12 = tmp2 - tmp11
tl.store(out_ptr0 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 2
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp6 = tl_math.log(tmp5)
tmp7 = tmp0 - tmp6
tl.store(out_ptr0 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (2, 4), (4, 1))
assert_size_stride(primals_3, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 2), (1, 4), 0), out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32)
triton_poi_fused__log_softmax_add_1[grid(32)](buf1, primals_3, buf2,
32, XBLOCK=32, num_warps=1, num_stages=1)
del primals_3
buf3 = reinterpret_tensor(buf1, (4, 4, 2), (8, 2, 1), 0)
del buf1
triton_poi_fused__log_softmax_2[grid(32)](buf2, buf3, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del buf2
return buf3, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf3
class NextSentencePredictionNew(nn.Module):
"""
2-class classification model : is_next, is_not_next
"""
def __init__(self, hidden):
"""
:param hidden: BERT model output size
"""
super().__init__()
self.linear = nn.Linear(hidden, 2)
self.softmax = nn.LogSoftmax(dim=-1)
def forward(self, input_0):
primals_2 = self.linear.weight
primals_3 = self.linear.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LogIntelligence/LogADEmpirical
|
NextSentencePrediction
| false
| 8,479
|
[
"MIT"
] | 11
|
48458aee65c1c84466b04dd4092fae79a7f341fd
|
https://github.com/LogIntelligence/LogADEmpirical/tree/48458aee65c1c84466b04dd4092fae79a7f341fd
|
FCLayer
|
import torch
from torch import nn
class FCLayer(nn.Module):
def __init__(self, input_dim, output_dim, dropout_rate=0.0,
use_activation=True):
super(FCLayer, self).__init__()
self.use_activation = use_activation
self.dropout = nn.Dropout(dropout_rate)
self.linear = nn.Linear(input_dim, output_dim)
self.tanh = nn.Tanh()
def forward(self, x):
x = self.dropout(x)
if self.use_activation:
x = self.tanh(x)
return self.linear(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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)
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(buf0, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del primals_2
del primals_3
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0)
class FCLayerNew(nn.Module):
def __init__(self, input_dim, output_dim, dropout_rate=0.0,
use_activation=True):
super(FCLayerNew, self).__init__()
self.use_activation = use_activation
self.dropout = nn.Dropout(dropout_rate)
self.linear = nn.Linear(input_dim, output_dim)
self.tanh = nn.Tanh()
def forward(self, input_0):
primals_2 = self.linear.weight
primals_3 = self.linear.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LostCow/KLUE
|
FCLayer
| false
| 8,480
|
[
"MIT"
] | 18
|
73b1b0526cf6b1b6f5ef535b9527d8abe6ca1a77
|
https://github.com/LostCow/KLUE/tree/73b1b0526cf6b1b6f5ef535b9527d8abe6ca1a77
|
psi
|
import torch
import torch.nn as nn
class psi(nn.Module):
def __init__(self, block_size):
super(psi, self).__init__()
self.block_size = block_size
self.block_size_sq = block_size * block_size
def inverse(self, input):
output = input.permute(0, 2, 3, 1)
batch_size, d_height, d_width, d_depth = output.size()
s_depth = int(d_depth / self.block_size_sq)
s_width = int(d_width * self.block_size)
s_height = int(d_height * self.block_size)
t_1 = output.contiguous().view(batch_size, d_height, d_width, self.
block_size_sq, s_depth)
spl = t_1.split(self.block_size, 3)
stack = [t_t.contiguous().view(batch_size, d_height, s_width,
s_depth) for t_t in spl]
output = torch.stack(stack, 0).transpose(0, 1).permute(0, 2, 1, 3, 4
).contiguous().view(batch_size, s_height, s_width, s_depth)
output = output.permute(0, 3, 1, 2)
return output.contiguous()
def forward(self, input):
output = input.permute(0, 2, 3, 1)
batch_size, s_height, _s_width, s_depth = output.size()
d_depth = s_depth * self.block_size_sq
d_height = int(s_height / self.block_size)
t_1 = output.split(self.block_size, 2)
stack = [t_t.contiguous().view(batch_size, d_height, d_depth) for
t_t in t_1]
output = torch.stack(stack, 1)
output = output.permute(0, 2, 1, 3)
output = output.permute(0, 3, 1, 2)
return output.contiguous()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'block_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](arg0_1, buf0, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
del arg0_1
return reinterpret_tensor(buf0, (4, 64, 1, 1), (64, 1, 64, 64), 0),
class psiNew(nn.Module):
def __init__(self, block_size):
super(psiNew, self).__init__()
self.block_size = block_size
self.block_size_sq = block_size * block_size
def inverse(self, input):
output = input.permute(0, 2, 3, 1)
batch_size, d_height, d_width, d_depth = output.size()
s_depth = int(d_depth / self.block_size_sq)
s_width = int(d_width * self.block_size)
s_height = int(d_height * self.block_size)
t_1 = output.contiguous().view(batch_size, d_height, d_width, self.
block_size_sq, s_depth)
spl = t_1.split(self.block_size, 3)
stack = [t_t.contiguous().view(batch_size, d_height, s_width,
s_depth) for t_t in spl]
output = torch.stack(stack, 0).transpose(0, 1).permute(0, 2, 1, 3, 4
).contiguous().view(batch_size, s_height, s_width, s_depth)
output = output.permute(0, 3, 1, 2)
return output.contiguous()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
LuckMonkeys/ATSPrivacy
|
psi
| false
| 8,481
|
[
"MIT"
] | 14
|
6b580942c6b98b6348d313f2bf90202ec19cefce
|
https://github.com/LuckMonkeys/ATSPrivacy/tree/6b580942c6b98b6348d313f2bf90202ec19cefce
|
Conv_Blocks
|
import torch
import torch.nn as nn
class Conv_Blocks(nn.Module):
def __init__(self, input_dim, output_dim, filter_size=3, batch_norm=
False, non_lin='tanh', dropout=0.0, first_block=False, last_block=
False, skip_connection=False):
super(Conv_Blocks, self).__init__()
self.skip_connection = skip_connection
self.last_block = last_block
self.first_block = first_block
self.Block = nn.Sequential()
self.Block.add_module('Conv_1', nn.Conv2d(input_dim, output_dim,
filter_size, 1, 1))
if batch_norm:
self.Block.add_module('BN_1', nn.BatchNorm2d(output_dim))
if non_lin == 'tanh':
self.Block.add_module('NonLin_1', nn.Tanh())
elif non_lin == 'relu':
self.Block.add_module('NonLin_1', nn.ReLU())
elif non_lin == 'leakyrelu':
self.Block.add_module('NonLin_1', nn.LeakyReLU())
else:
assert False, "non_lin = {} not valid: 'tanh', 'relu', 'leakyrelu'".format(
non_lin)
self.Block.add_module('Pool', nn.MaxPool2d(kernel_size=(2, 2),
stride=(2, 2), dilation=(1, 1), ceil_mode=False))
if dropout > 0:
self.Block.add_module('Drop', nn.Dropout2d(dropout))
def forward(self, x):
if self.skip_connection:
if not self.first_block:
x, skip_con_list = x
else:
skip_con_list = []
x = self.Block(x)
if self.skip_connection:
if not self.last_block:
skip_con_list.append(x)
x = [x, skip_con_list]
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_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
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 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x3, tmp3, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3 = 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))
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_tanh_0[grid(256)](buf1, primals_2, 256,
XBLOCK=128, 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)
triton_poi_fused_max_pool2d_with_indices_1[grid(64)](buf1, buf2,
buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
return buf2, primals_1, primals_3, buf1, buf3
class Conv_BlocksNew(nn.Module):
def __init__(self, input_dim, output_dim, filter_size=3, batch_norm=
False, non_lin='tanh', dropout=0.0, first_block=False, last_block=
False, skip_connection=False):
super(Conv_BlocksNew, self).__init__()
self.skip_connection = skip_connection
self.last_block = last_block
self.first_block = first_block
self.Block = nn.Sequential()
self.Block.add_module('Conv_1', nn.Conv2d(input_dim, output_dim,
filter_size, 1, 1))
if batch_norm:
self.Block.add_module('BN_1', nn.BatchNorm2d(output_dim))
if non_lin == 'tanh':
self.Block.add_module('NonLin_1', nn.Tanh())
elif non_lin == 'relu':
self.Block.add_module('NonLin_1', nn.ReLU())
elif non_lin == 'leakyrelu':
self.Block.add_module('NonLin_1', nn.LeakyReLU())
else:
assert False, "non_lin = {} not valid: 'tanh', 'relu', 'leakyrelu'".format(
non_lin)
self.Block.add_module('Pool', nn.MaxPool2d(kernel_size=(2, 2),
stride=(2, 2), dilation=(1, 1), ceil_mode=False))
if dropout > 0:
self.Block.add_module('Drop', nn.Dropout2d(dropout))
def forward(self, input_0):
primals_1 = self.Block.Conv_1.weight
primals_2 = self.Block.Conv_1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LuigiFilippoChiara/GoalGAN
|
Conv_Blocks
| false
| 8,482
|
[
"MIT"
] | 36
|
11ac7448af7ac8934e6eb47a06c51d92f04dec8c
|
https://github.com/LuigiFilippoChiara/GoalGAN/tree/11ac7448af7ac8934e6eb47a06c51d92f04dec8c
|
UpConv_Blocks
|
import torch
import torch.nn as nn
class UpConv_Blocks(nn.Module):
def __init__(self, input_dim, output_dim, filter=4, padding=1,
first_block=False, last_block=False, batch_norm=False, non_lin=
'relu', dropout=0, skip_connection=False):
super(UpConv_Blocks, self).__init__()
self.Block = nn.Sequential()
self.skip_connection = skip_connection
self.first_block = first_block
self.last_block = last_block
if self.skip_connection and not self.first_block:
input_dim *= 2
else:
pass
self.Block.add_module('UpConv', nn.ConvTranspose2d(input_dim,
output_dim, filter, 2, padding))
if not last_block:
if batch_norm:
self.Block.add_module('BN_up', nn.BatchNorm2d(output_dim))
if non_lin == 'tanh':
self.Block.add_module('NonLin_up', nn.Tanh())
elif non_lin == 'relu':
self.Block.add_module('NonLin_up', nn.ReLU())
elif non_lin == 'leakyrelu':
self.Block.add_module('NonLin_up', nn.LeakyReLU())
if dropout > 0:
self.Block.add_module('Drop_up', nn.Dropout2d(dropout))
def forward(self, x):
if self.skip_connection:
x, skip_con_list = x
if not self.first_block:
x = torch.cat((x, skip_con_list.pop(-1)), -3)
x = self.Block(x)
if self.skip_connection and not self.last_block:
x = [x, skip_con_list]
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_threshold_backward_0(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 64 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2,
2), padding=(1, 1), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 8, 8), (256, 64, 8, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_convolution_relu_threshold_backward_0[grid(1024)](buf1
, primals_2, buf2, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3, buf2
class UpConv_BlocksNew(nn.Module):
def __init__(self, input_dim, output_dim, filter=4, padding=1,
first_block=False, last_block=False, batch_norm=False, non_lin=
'relu', dropout=0, skip_connection=False):
super(UpConv_BlocksNew, self).__init__()
self.Block = nn.Sequential()
self.skip_connection = skip_connection
self.first_block = first_block
self.last_block = last_block
if self.skip_connection and not self.first_block:
input_dim *= 2
else:
pass
self.Block.add_module('UpConv', nn.ConvTranspose2d(input_dim,
output_dim, filter, 2, padding))
if not last_block:
if batch_norm:
self.Block.add_module('BN_up', nn.BatchNorm2d(output_dim))
if non_lin == 'tanh':
self.Block.add_module('NonLin_up', nn.Tanh())
elif non_lin == 'relu':
self.Block.add_module('NonLin_up', nn.ReLU())
elif non_lin == 'leakyrelu':
self.Block.add_module('NonLin_up', nn.LeakyReLU())
if dropout > 0:
self.Block.add_module('Drop_up', nn.Dropout2d(dropout))
def forward(self, input_0):
primals_1 = self.Block.UpConv.weight
primals_2 = self.Block.UpConv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
LuigiFilippoChiara/GoalGAN
|
UpConv_Blocks
| false
| 8,483
|
[
"MIT"
] | 36
|
11ac7448af7ac8934e6eb47a06c51d92f04dec8c
|
https://github.com/LuigiFilippoChiara/GoalGAN/tree/11ac7448af7ac8934e6eb47a06c51d92f04dec8c
|
ScaleDotProductAttention
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class ScaleDotProductAttention(nn.Module):
def __init__(self, k_dim, dropout=0.1):
super(ScaleDotProductAttention, self).__init__()
self.scale = 1.0 / k_dim ** 0.5
self.dropout = dropout
def forward(self, q, k, v, mask=None):
"""
:param q: (bz, q_len, q_dim)
:param k: (bz, k_len, k_dim)
:param v: (bz, v_len, v_dim)
k_len == v_len v_dim == q_dim
:param mask: (bz, k_len) 填充部分为0
:return: (bz, q_len, v_dim)
"""
att_score = torch.matmul(q, k.transpose(1, 2)).mul(self.scale)
if mask is not None:
att_mask = ~mask[:, None, :]
att_score = att_score.masked_fill(att_mask, -1000000000.0)
att_weights = F.softmax(att_score, dim=-1)
att_out = torch.matmul(att_weights, v)
return att_out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {'k_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused__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)
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_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
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_clone_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg1_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(buf0, (16, 4, 4), (16, 4, 1), 0), out
=buf1)
del arg1_1
buf2 = buf0
del buf0
triton_poi_fused__softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused__softmax_2[grid(256)](buf2, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(arg2_1, (16, 4, 4), (16, 4, 1), 0), out=buf4
)
del arg2_1
del buf3
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0),
class ScaleDotProductAttentionNew(nn.Module):
def __init__(self, k_dim, dropout=0.1):
super(ScaleDotProductAttentionNew, self).__init__()
self.scale = 1.0 / k_dim ** 0.5
self.dropout = dropout
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
LindgeW/BiaffineNER
|
ScaleDotProductAttention
| false
| 8,484
|
[
"Apache-2.0"
] | 13
|
0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
https://github.com/LindgeW/BiaffineNER/tree/0ae179e9ff731362f6c8ba6d0b24485ad45e8bbf
|
GRU
|
import torch
import torch.nn as nn
class GRU(nn.Module):
def __init__(self, outfea):
super(GRU, self).__init__()
self.ff = nn.Linear(2 * outfea, 2 * outfea)
self.zff = nn.Linear(2 * outfea, outfea)
self.outfea = outfea
def forward(self, x, xh):
r, u = torch.split(torch.sigmoid(self.ff(torch.cat([x, xh], -1))),
self.outfea, -1)
z = torch.tanh(self.zff(torch.cat([x, r * xh], -1)))
x = u * z + (1 - u) * xh
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'outfea': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
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_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 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.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 512
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 + (8 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.load(in_ptr2 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp9 * tmp10
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp6, tmp11, tmp12)
tmp14 = tl.where(tmp4, tmp5, tmp13)
tl.store(out_ptr0 + x2, tmp14, xmask)
@triton.jit
def triton_poi_fused_add_mul_rsub_tanh_3(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 + x0 + 8 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp6 = tl.load(in_ptr2 + x2, xmask)
tmp2 = libdevice.tanh(tmp1)
tmp3 = tmp0 * tmp2
tmp4 = 1.0
tmp5 = tmp4 - tmp0
tmp7 = tmp5 * tmp6
tmp8 = tmp3 + 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (8, 8), (8, 1))
assert_size_stride(primals_4, (8,), (1,))
assert_size_stride(primals_5, (4, 8), (8, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](primals_1, primals_2, buf0, 512,
XBLOCK=128, num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((64, 8), (8, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 8), (8, 1), 0),
reinterpret_tensor(primals_3, (8, 8), (1, 8), 0), out=buf1)
del primals_3
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 8), (128, 32, 8, 1), 0)
del buf1
triton_poi_fused_sigmoid_1[grid(512)](buf2, primals_4, 512, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.float32)
triton_poi_fused_cat_2[grid(512)](primals_1, buf2, primals_2, buf3,
512, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf3, (64, 8), (
8, 1), 0), reinterpret_tensor(primals_5, (8, 4), (1, 8), 0),
alpha=1, beta=1, out=buf4)
del primals_6
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_rsub_tanh_3[grid(256)](buf2, buf4,
primals_2, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
return buf5, primals_2, reinterpret_tensor(buf0, (64, 8), (8, 1), 0
), buf2, reinterpret_tensor(buf2, (4, 4, 4, 4), (128, 32, 8, 1), 4
), reinterpret_tensor(buf3, (64, 8), (8, 1), 0), buf4, primals_5
class GRUNew(nn.Module):
def __init__(self, outfea):
super(GRUNew, self).__init__()
self.ff = nn.Linear(2 * outfea, 2 * outfea)
self.zff = nn.Linear(2 * outfea, outfea)
self.outfea = outfea
def forward(self, input_0, input_1):
primals_3 = self.ff.weight
primals_4 = self.ff.bias
primals_5 = self.zff.weight
primals_6 = self.zff.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]
|
LMissher/STGNN
|
GRU
| false
| 8,485
|
[
"MIT"
] | 26
|
9c35d994738ad768ca4385273235bd30e994b746
|
https://github.com/LMissher/STGNN/tree/9c35d994738ad768ca4385273235bd30e994b746
|
VanillaGenerativeAdversarialLoss
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
class VanillaGenerativeAdversarialLoss(nn.Module):
"""
Loss for `Vanilla Generative Adversarial Network <https://arxiv.org/abs/1406.2661>`_
Args:
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs:
- prediction (tensor): unnormalized discriminator predictions
- real (bool): if the ground truth label is for real images or fake images. Default: true
.. warning::
Do not use sigmoid as the last layer of Discriminator.
"""
def __init__(self, reduction='mean'):
super(VanillaGenerativeAdversarialLoss, self).__init__()
self.bce_loss = nn.BCEWithLogitsLoss(reduction=reduction)
def forward(self, prediction, real=True):
if real:
label = torch.ones_like(prediction)
else:
label = torch.zeros_like(prediction)
return self.bce_loss(prediction, label)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_binary_cross_entropy_with_logits_0(in_out_ptr0,
in_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 0.0
tmp2 = tmp1 * tmp0
tmp3 = triton_helpers.minimum(tmp1, tmp0)
tmp4 = tl_math.abs(tmp0)
tmp5 = -tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = libdevice.log1p(tmp6)
tmp8 = tmp3 - tmp7
tmp9 = tmp2 - tmp8
tmp10 = tl.broadcast_to(tmp9, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp13 = 256.0
tmp14 = tmp12 / tmp13
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_binary_cross_entropy_with_logits_0[grid(1)](buf1,
arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
return buf1,
class VanillaGenerativeAdversarialLossNew(nn.Module):
"""
Loss for `Vanilla Generative Adversarial Network <https://arxiv.org/abs/1406.2661>`_
Args:
reduction (str, optional): Specifies the reduction to apply to the output:
``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
``'mean'``: the sum of the output will be divided by the number of
elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``
Inputs:
- prediction (tensor): unnormalized discriminator predictions
- real (bool): if the ground truth label is for real images or fake images. Default: true
.. warning::
Do not use sigmoid as the last layer of Discriminator.
"""
def __init__(self, reduction='mean'):
super(VanillaGenerativeAdversarialLossNew, self).__init__()
self.bce_loss = nn.BCEWithLogitsLoss(reduction=reduction)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Liuhong99/CST
|
VanillaGenerativeAdversarialLoss
| false
| 8,486
|
[
"MIT"
] | 20
|
f6653a4ee7968fa3ba875a182670636f648be783
|
https://github.com/Liuhong99/CST/tree/f6653a4ee7968fa3ba875a182670636f648be783
|
SAC
|
import torch
import torch.nn as nn
class SAC(nn.Module):
def __init__(self, input_channel, out_channel):
super(SAC, self).__init__()
self.conv_1 = nn.Conv3d(input_channel, out_channel, kernel_size=3,
stride=1, padding=1)
self.conv_3 = nn.Conv3d(input_channel, out_channel, kernel_size=3,
stride=1, padding=2, dilation=2)
self.conv_5 = nn.Conv3d(input_channel, out_channel, kernel_size=3,
stride=1, padding=3, dilation=3)
self.weights = nn.Parameter(torch.ones(3))
self.softmax = nn.Softmax(0)
def forward(self, inputs):
feat_1 = self.conv_1(inputs)
feat_3 = self.conv_3(inputs)
feat_5 = self.conv_5(inputs)
weights = self.softmax(self.weights)
feat = feat_1 * weights[0] + feat_3 * weights[1] + feat_5 * weights[2]
return feat
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_channel': 4, 'out_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
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_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
rnumel = 3
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, :]
rmask = rindex < rnumel
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, rmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp4, None)
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp10, None)
@triton.jit
def triton_poi_fused_add_convolution_mul_1(in_out_ptr0, in_out_ptr1,
in_out_ptr2, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_out_ptr2 + x2, xmask)
tmp7 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr3 + 0)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp11 = tl.load(in_ptr4 + 0)
tmp12 = tl.broadcast_to(tmp11, [XBLOCK])
tmp15 = tl.load(in_ptr5 + 0)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK])
tmp19 = tl.load(in_ptr3 + 1)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp26 = tl.load(in_ptr3 + 2)
tmp27 = tl.broadcast_to(tmp26, [XBLOCK])
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp8 = tmp6 + tmp7
tmp13 = tmp10 - tmp12
tmp14 = tl_math.exp(tmp13)
tmp17 = tmp14 / tmp16
tmp18 = tmp2 * tmp17
tmp21 = tmp20 - tmp12
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp22 / tmp16
tmp24 = tmp5 * tmp23
tmp25 = tmp18 + tmp24
tmp28 = tmp27 - tmp12
tmp29 = tl_math.exp(tmp28)
tmp30 = tmp29 / tmp16
tmp31 = tmp8 * tmp30
tmp32 = tmp25 + tmp31
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(in_out_ptr1 + x2, tmp5, xmask)
tl.store(in_out_ptr2 + x2, tmp8, xmask)
tl.store(out_ptr0 + x2, tmp32, 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, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (3,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(1, 1,
1), padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf2 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_4, stride=(1, 1,
1), padding=(2, 2, 2), dilation=(2, 2, 2), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf2, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf4 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_6, stride=(1, 1,
1), padding=(3, 3, 3), dilation=(3, 3, 3), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf4, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf6 = empty_strided_cuda((1,), (1,), torch.float32)
buf7 = empty_strided_cuda((1,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused__softmax_0[grid(1)](primals_8, buf6, buf7, 1, 3,
XBLOCK=1, num_warps=2, num_stages=1)
buf1 = buf0
del buf0
buf3 = buf2
del buf2
buf5 = buf4
del buf4
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_convolution_mul_1[grid(256)](buf1, buf3, buf5,
primals_2, primals_5, primals_7, primals_8, buf6, buf7, buf8,
256, XBLOCK=256, num_warps=4, num_stages=1)
del buf6
del buf7
del primals_2
del primals_5
del primals_7
return (buf8, primals_1, primals_4, primals_6, primals_8,
reinterpret_tensor(primals_3, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1),
0), buf1, buf3, buf5)
class SACNew(nn.Module):
def __init__(self, input_channel, out_channel):
super(SACNew, self).__init__()
self.conv_1 = nn.Conv3d(input_channel, out_channel, kernel_size=3,
stride=1, padding=1)
self.conv_3 = nn.Conv3d(input_channel, out_channel, kernel_size=3,
stride=1, padding=2, dilation=2)
self.conv_5 = nn.Conv3d(input_channel, out_channel, kernel_size=3,
stride=1, padding=3, dilation=3)
self.weights = nn.Parameter(torch.ones(3))
self.softmax = nn.Softmax(0)
def forward(self, input_0):
primals_8 = self.weights
primals_1 = self.conv_1.weight
primals_2 = self.conv_1.bias
primals_4 = self.conv_3.weight
primals_5 = self.conv_3.bias
primals_6 = self.conv_5.weight
primals_7 = self.conv_5.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
Luoxd1996/SCPM-Net
|
SAC
| false
| 8,487
|
[
"MIT"
] | 26
|
2039ea5253ec831dcae79c2f0caa6e5d2641a1f9
|
https://github.com/Luoxd1996/SCPM-Net/tree/2039ea5253ec831dcae79c2f0caa6e5d2641a1f9
|
GaussianKernel
|
import torch
import torch.nn as nn
from typing import Optional
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
class GaussianKernel(nn.Module):
"""Gaussian Kernel Matrix
Gaussian Kernel k is defined by
.. math::
k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)
where :math:`x_1, x_2 \\in R^d` are 1-d tensors.
Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`
.. math::
K(X)_{i,j} = k(x_i, x_j)
Also by default, during training this layer keeps running estimates of the
mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.
Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.
If :attr:`track_running_stats` is set to ``False``, this layer then does not
keep running estimates, and use a fixed :math:`\\sigma` instead.
Args:
sigma (float, optional): bandwidth :math:`\\sigma`. Default: None
track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.
Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``
alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``
Inputs:
- X (tensor): input group :math:`X`
Shape:
- Inputs: :math:`(minibatch, F)` where F means the dimension of input features.
- Outputs: :math:`(minibatch, minibatch)`
"""
def __init__(self, sigma: 'Optional[float]'=None, track_running_stats:
'Optional[bool]'=True, alpha: 'Optional[float]'=1.0):
super(GaussianKernel, self).__init__()
assert track_running_stats or sigma is not None
self.sigma_square = torch.tensor(sigma * sigma
) if sigma is not None else None
self.track_running_stats = track_running_stats
self.alpha = alpha
def forward(self, X: 'torch.Tensor') ->torch.Tensor:
l2_distance_square = ((X.unsqueeze(0) - X.unsqueeze(1)) ** 2).sum(2)
if self.track_running_stats:
self.sigma_square = self.alpha * torch.mean(l2_distance_square.
detach())
return torch.exp(-l2_distance_square / (2 * self.sigma_square))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from typing import Optional
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_div_exp_mean_mul_neg_pow_sub_sum_0(in_out_ptr0,
in_ptr0, out_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16 % 4
r2 = rindex // 64
r3 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None, eviction_policy='evict_last'
)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tl.broadcast_to(tmp18, [RBLOCK])
tmp21 = triton_helpers.promote_to_tensor(tl.sum(tmp19, 0))
tmp22 = 256.0
tmp23 = tmp21 / tmp22
tmp24 = 1.0
tmp25 = tmp23 * tmp24
tmp26 = -tmp18
tmp27 = 2.0
tmp28 = tmp25 * tmp27
tmp29 = tmp26 / tmp28
tmp30 = tl_math.exp(tmp29)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp25, None)
tl.store(out_ptr1 + tl.broadcast_to(r3, [RBLOCK]), tmp30, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_div_exp_mean_mul_neg_pow_sub_sum_0[grid(1)](buf2,
arg0_1, buf3, 1, 256, num_warps=2, num_stages=1)
del arg0_1
return buf3, buf2
class GaussianKernelNew(nn.Module):
"""Gaussian Kernel Matrix
Gaussian Kernel k is defined by
.. math::
k(x_1, x_2) = \\exp \\left( - \\dfrac{\\| x_1 - x_2 \\|^2}{2\\sigma^2} \\right)
where :math:`x_1, x_2 \\in R^d` are 1-d tensors.
Gaussian Kernel Matrix K is defined on input group :math:`X=(x_1, x_2, ..., x_m),`
.. math::
K(X)_{i,j} = k(x_i, x_j)
Also by default, during training this layer keeps running estimates of the
mean of L2 distances, which are then used to set hyperparameter :math:`\\sigma`.
Mathematically, the estimation is :math:`\\sigma^2 = \\dfrac{\\alpha}{n^2}\\sum_{i,j} \\| x_i - x_j \\|^2`.
If :attr:`track_running_stats` is set to ``False``, this layer then does not
keep running estimates, and use a fixed :math:`\\sigma` instead.
Args:
sigma (float, optional): bandwidth :math:`\\sigma`. Default: None
track_running_stats (bool, optional): If ``True``, this module tracks the running mean of :math:`\\sigma^2`.
Otherwise, it won't track such statistics and always uses fix :math:`\\sigma^2`. Default: ``True``
alpha (float, optional): :math:`\\alpha` which decides the magnitude of :math:`\\sigma^2` when track_running_stats is set to ``True``
Inputs:
- X (tensor): input group :math:`X`
Shape:
- Inputs: :math:`(minibatch, F)` where F means the dimension of input features.
- Outputs: :math:`(minibatch, minibatch)`
"""
def __init__(self, sigma: 'Optional[float]'=None, track_running_stats:
'Optional[bool]'=True, alpha: 'Optional[float]'=1.0):
super(GaussianKernelNew, self).__init__()
assert track_running_stats or sigma is not None
self.sigma_square = torch.tensor(sigma * sigma
) if sigma is not None else None
self.track_running_stats = track_running_stats
self.alpha = alpha
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
Liuhong99/CST
|
GaussianKernel
| false
| 8,488
|
[
"MIT"
] | 20
|
f6653a4ee7968fa3ba875a182670636f648be783
|
https://github.com/Liuhong99/CST/tree/f6653a4ee7968fa3ba875a182670636f648be783
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.