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
|
|---|---|---|---|---|---|---|---|---|---|---|
Attention
|
import torch
from torch import nn
import torch.nn.utils
class Attention(nn.Module):
def __init__(self, hidden_dim):
super(Attention, self).__init__()
self.hidden_dim = hidden_dim
self.ff = nn.Linear(in_features=hidden_dim, out_features=1)
self.softmax = nn.Softmax(dim=-1)
def forward(self, contexts, context_masks=None):
"""
:param contexts: (batch_size, seq_len, n_hid)
:param context_masks: (batch_size, seq_len)
:return: (batch_size, n_hid), (batch_size, seq_len)
"""
out = self.ff(contexts)
out = out.view(contexts.size(0), contexts.size(1))
if context_masks is not None:
masked_out = out.masked_fill(context_masks, float('-inf'))
else:
masked_out = out
attn_weights = self.softmax(masked_out)
out = attn_weights.unsqueeze(1).bmm(contexts)
out = out.squeeze(1)
return out, attn_weights
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
import torch.nn.utils
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (16,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_1
del primals_2
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](buf1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4), (4, 1), 0)
del buf1
triton_poi_fused__softmax_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 1, 4), (4, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf3, (4, 1, 4), (4, 4, 1), 0
), primals_3, out=buf4)
return reinterpret_tensor(buf4, (4, 4), (4, 1), 0), buf3, primals_3, buf3
class AttentionNew(nn.Module):
def __init__(self, hidden_dim):
super(AttentionNew, self).__init__()
self.hidden_dim = hidden_dim
self.ff = nn.Linear(in_features=hidden_dim, out_features=1)
self.softmax = nn.Softmax(dim=-1)
def forward(self, input_0):
primals_1 = self.ff.weight
primals_2 = self.ff.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
bstee615/ReVeal
|
Attention
| false
| 14,982
|
[
"MIT"
] | 63
|
fc22d0d54a3a23d4e0bc45a249b7eea22749685e
|
https://github.com/bstee615/ReVeal/tree/fc22d0d54a3a23d4e0bc45a249b7eea22749685e
|
TriangularSylvester
|
import torch
from torch import nn
class TriangularSylvester(nn.Module):
"""
Sylvester normalizing flow with Q=P or Q=I.
"""
def __init__(self, z_size):
super(TriangularSylvester, self).__init__()
self.z_size = z_size
self.h = nn.Tanh()
def der_h(self, x):
return self.der_tanh(x)
def der_tanh(self, x):
return 1 - self.h(x) ** 2
def forward(self, zk, r1, r2, b, permute_z=None, sum_ldj=True):
"""
All flow parameters are amortized. conditions on diagonals of R1 and R2 need to be satisfied
outside of this function.
Computes the following transformation:
z' = z + QR1 h( R2Q^T z + b)
or actually
z'^T = z^T + h(z^T Q R2^T + b^T)R1^T Q^T
with Q = P a permutation matrix (equal to identity matrix if permute_z=None)
:param zk: shape: (batch_size, z_size)
:param r1: shape: (batch_size, num_ortho_vecs, num_ortho_vecs).
:param r2: shape: (batch_size, num_ortho_vecs, num_ortho_vecs).
:param b: shape: (batch_size, 1, self.z_size)
:return: z, log_det_j
"""
zk = zk.unsqueeze(1)
diag_r1 = torch.diagonal(r1, 0, -1, -2)
diag_r2 = torch.diagonal(r2, 0, -1, -2)
if permute_z is not None:
z_per = zk[:, :, permute_z]
else:
z_per = zk
r2qzb = z_per @ r2.transpose(2, 1) + b
z = self.h(r2qzb) @ r1.transpose(2, 1)
if permute_z is not None:
z = z[:, :, permute_z]
z += zk
z = z.squeeze(1)
diag_j = diag_r1 * diag_r2
diag_j = self.der_h(r2qzb).squeeze(1) * diag_j
diag_j += 1.0
log_diag_j = (diag_j.abs() + 1e-08).log()
if sum_ldj:
log_det_j = log_diag_j.sum(-1)
else:
log_det_j = log_diag_j
return z, log_det_j
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'z_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, 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_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_add_tanh_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x5 = xindex
x0 = xindex % 64
x2 = xindex // 256
tmp0 = tl.load(in_out_ptr0 + x5, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x5, tmp2, xmask)
@triton.jit
def triton_poi_fused_abs_add_log_mul_pow_rsub_sum_tanh_4(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x4 = xindex % 64
x0 = xindex % 16
tmp0 = tl.load(in_ptr0 + 4 * x3, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x4, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr2 + 16 * x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr3 + 16 * x0, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (1 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr1 + (1 + 4 * x4), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr2 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr3 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp31 = tl.load(in_ptr0 + (2 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp32 = tl.load(in_ptr1 + (2 + 4 * x4), xmask, eviction_policy='evict_last'
)
tmp37 = tl.load(in_ptr2 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp38 = tl.load(in_ptr3 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp46 = tl.load(in_ptr0 + (3 + 4 * x3), xmask, eviction_policy='evict_last'
)
tmp47 = tl.load(in_ptr1 + (3 + 4 * x4), xmask, eviction_policy='evict_last'
)
tmp52 = tl.load(in_ptr2 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp53 = tl.load(in_ptr3 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tmp4 = tmp3 * tmp3
tmp5 = 1.0
tmp6 = tmp5 - tmp4
tmp9 = tmp7 * tmp8
tmp10 = tmp6 * tmp9
tmp11 = tmp10 + tmp5
tmp12 = tl_math.abs(tmp11)
tmp13 = 1e-08
tmp14 = tmp12 + tmp13
tmp15 = tl_math.log(tmp14)
tmp18 = tmp16 + tmp17
tmp19 = libdevice.tanh(tmp18)
tmp20 = tmp19 * tmp19
tmp21 = tmp5 - tmp20
tmp24 = tmp22 * tmp23
tmp25 = tmp21 * tmp24
tmp26 = tmp25 + tmp5
tmp27 = tl_math.abs(tmp26)
tmp28 = tmp27 + tmp13
tmp29 = tl_math.log(tmp28)
tmp30 = tmp15 + tmp29
tmp33 = tmp31 + tmp32
tmp34 = libdevice.tanh(tmp33)
tmp35 = tmp34 * tmp34
tmp36 = tmp5 - tmp35
tmp39 = tmp37 * tmp38
tmp40 = tmp36 * tmp39
tmp41 = tmp40 + tmp5
tmp42 = tl_math.abs(tmp41)
tmp43 = tmp42 + tmp13
tmp44 = tl_math.log(tmp43)
tmp45 = tmp30 + tmp44
tmp48 = tmp46 + tmp47
tmp49 = libdevice.tanh(tmp48)
tmp50 = tmp49 * tmp49
tmp51 = tmp5 - tmp50
tmp54 = tmp52 * tmp53
tmp55 = tmp51 * tmp54
tmp56 = tmp55 + tmp5
tmp57 = tl_math.abs(tmp56)
tmp58 = tmp57 + tmp13
tmp59 = tl_math.log(tmp58)
tmp60 = tmp45 + tmp59
tl.store(out_ptr0 + x3, tmp60, xmask)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
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)
buf1 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_poi_fused_clone_1[grid(1024)](arg2_1, buf1, 1024, XBLOCK=128,
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_add_tanh_2[grid(1024)](buf2, arg3_1, buf3, 1024,
XBLOCK=256, num_warps=4, num_stages=1)
buf4 = buf0
del buf0
triton_poi_fused_clone_1[grid(1024)](arg1_1, buf4, 1024, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((64, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (64, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (64, 4, 4), (16, 4, 1), 0), out=buf5)
del buf3
del buf4
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0
)
del buf5
buf7 = buf6
del buf6
triton_poi_fused_add_3[grid(1024)](buf7, arg0_1, 1024, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_abs_add_log_mul_pow_rsub_sum_tanh_4[grid(256)](buf2,
arg3_1, arg1_1, arg2_1, buf8, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del arg1_1
del arg2_1
del arg3_1
del buf2
return buf7, buf8
class TriangularSylvesterNew(nn.Module):
"""
Sylvester normalizing flow with Q=P or Q=I.
"""
def __init__(self, z_size):
super(TriangularSylvesterNew, self).__init__()
self.z_size = z_size
self.h = nn.Tanh()
def der_h(self, x):
return self.der_tanh(x)
def der_tanh(self, x):
return 1 - self.h(x) ** 2
def forward(self, input_0, input_1, input_2, input_3):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0], output[1]
|
boldsort/NeuralDX7
|
TriangularSylvester
| false
| 14,983
|
[
"MIT"
] | 119
|
327844cea18a6dfe35e0dc8f5de0832343487366
|
https://github.com/boldsort/NeuralDX7/tree/327844cea18a6dfe35e0dc8f5de0832343487366
|
MSE
|
import torch
import torch.nn as nn
import torch.utils.checkpoint
class MSE(nn.Module):
def __init__(self):
super(MSE, self).__init__()
def forward(self, pred, real):
diffs = torch.add(real, -pred)
n = torch.numel(diffs.data)
mse = torch.sum(diffs.pow(2)) / n
return mse
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.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_neg_pow_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = -tmp1
tmp3 = tmp0 + tmp2
tmp4 = tmp3 * tmp3
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = 0.00390625
tmp9 = tmp7 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_neg_pow_sum_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 MSENew(nn.Module):
def __init__(self):
super(MSENew, 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]
|
byamao1/MMSA
|
MSE
| false
| 14,984
|
[
"MIT"
] | 198
|
1a894d042144c9ac75b3465d38871ce8c2987251
|
https://github.com/byamao1/MMSA/tree/1a894d042144c9ac75b3465d38871ce8c2987251
|
LRN
|
import torch
import torch.nn as nn
class LRN(nn.Module):
def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=True
):
super(LRN, self).__init__()
self.ACROSS_CHANNELS = ACROSS_CHANNELS
if ACROSS_CHANNELS:
self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1),
stride=1, padding=(int((local_size - 1.0) / 2), 0, 0))
else:
self.average = nn.AvgPool2d(kernel_size=local_size, stride=1,
padding=int((local_size - 1.0) / 2))
self.alpha = alpha
self.beta = beta
def forward(self, x):
if self.ACROSS_CHANNELS:
div = x.pow(2).unsqueeze(1)
div = self.average(div).squeeze(1)
div = div.mul(self.alpha).add(1.0).pow(self.beta)
else:
div = x.pow(2)
div = self.average(div)
div = div.mul(self.alpha).add(1.0).pow(self.beta)
x = x.div(div)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mul_pow_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0 * tmp0
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 + tmp2
tmp6 = 0.75
tmp7 = libdevice.pow(tmp5, tmp6)
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mul_pow_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class LRNNew(nn.Module):
def __init__(self, local_size=1, alpha=1.0, beta=0.75, ACROSS_CHANNELS=True
):
super(LRNNew, self).__init__()
self.ACROSS_CHANNELS = ACROSS_CHANNELS
if ACROSS_CHANNELS:
self.average = nn.AvgPool3d(kernel_size=(local_size, 1, 1),
stride=1, padding=(int((local_size - 1.0) / 2), 0, 0))
else:
self.average = nn.AvgPool2d(kernel_size=local_size, stride=1,
padding=int((local_size - 1.0) / 2))
self.alpha = alpha
self.beta = beta
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bruinxiong/BNM
|
LRN
| false
| 14,985
|
[
"MIT"
] | 252
|
71d4b8c9beca00e77fcbc62a12b69bb093736a82
|
https://github.com/bruinxiong/BNM/tree/71d4b8c9beca00e77fcbc62a12b69bb093736a82
|
SIMSE
|
import torch
import torch.nn as nn
import torch.utils.checkpoint
class SIMSE(nn.Module):
def __init__(self):
super(SIMSE, self).__init__()
def forward(self, pred, real):
diffs = torch.add(real, -pred)
n = torch.numel(diffs.data)
simse = torch.sum(diffs).pow(2) / n ** 2
return simse
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.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_div_neg_pow_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = -tmp1
tmp3 = tmp0 + tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = tmp6 * tmp6
tmp8 = 1.52587890625e-05
tmp9 = tmp7 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_neg_pow_sum_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 SIMSENew(nn.Module):
def __init__(self):
super(SIMSENew, 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]
|
byamao1/MMSA
|
SIMSE
| false
| 14,986
|
[
"MIT"
] | 198
|
1a894d042144c9ac75b3465d38871ce8c2987251
|
https://github.com/byamao1/MMSA/tree/1a894d042144c9ac75b3465d38871ce8c2987251
|
ActorCriticMLP
|
import torch
from torch import Tensor
from torch import nn
from typing import Tuple
from torch.nn import functional as F
class ActorCriticMLP(nn.Module):
"""MLP network with heads for actor and critic."""
def __init__(self, input_shape: 'Tuple[int]', n_actions: 'int',
hidden_size: 'int'=128):
"""
Args:
input_shape: observation shape of the environment
n_actions: number of discrete actions available in the environment
hidden_size: size of hidden layers
"""
super().__init__()
self.fc1 = nn.Linear(input_shape[0], hidden_size)
self.actor_head = nn.Linear(hidden_size, n_actions)
self.critic_head = nn.Linear(hidden_size, 1)
def forward(self, x) ->Tuple[Tensor, Tensor]:
"""Forward pass through network. Calculates the action logits and the value.
Args:
x: input to network
Returns:
action log probs (logits), value
"""
x = F.relu(self.fc1(x.float()))
a = F.log_softmax(self.actor_head(x), dim=-1)
c = self.critic_head(x)
return a, c
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_shape': [4, 4], 'n_actions': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
from typing import Tuple
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
@triton.jit
def triton_poi_fused__log_softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (128, 4), (4, 1))
assert_size_stride(primals_3, (128,), (1,))
assert_size_stride(primals_4, (4, 128), (128, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 128), (128, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 128), (128, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 128), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 128), (2048, 512, 128, 1), 0)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 128), (2048, 512, 128, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(8192)](buf1,
primals_3, buf7, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_4, (128, 4), (1, 128),
0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=
256, num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused__log_softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del buf3
buf6 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 128),
(128, 1), 0), reinterpret_tensor(primals_6, (128, 1), (1, 128),
0), alpha=1, beta=1, out=buf6)
del primals_7
return buf4, reinterpret_tensor(buf6, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 128), (128, 1), 0
), buf4, primals_6, primals_4, buf7
class ActorCriticMLPNew(nn.Module):
"""MLP network with heads for actor and critic."""
def __init__(self, input_shape: 'Tuple[int]', n_actions: 'int',
hidden_size: 'int'=128):
"""
Args:
input_shape: observation shape of the environment
n_actions: number of discrete actions available in the environment
hidden_size: size of hidden layers
"""
super().__init__()
self.fc1 = nn.Linear(input_shape[0], hidden_size)
self.actor_head = nn.Linear(hidden_size, n_actions)
self.critic_head = nn.Linear(hidden_size, 1)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.actor_head.weight
primals_5 = self.actor_head.bias
primals_6 = self.critic_head.weight
primals_7 = self.critic_head.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
bzrry/lightning-bolts
|
ActorCriticMLP
| false
| 14,987
|
[
"Apache-2.0"
] | 822
|
bd392ad858039290c72c20cc3f10df39384e90b9
|
https://github.com/bzrry/lightning-bolts/tree/bd392ad858039290c72c20cc3f10df39384e90b9
|
Mlp
|
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return 0.5 * x * (1 + F.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class Mlp(nn.Module):
""" MLP as used in Vision Transformer, MLP-Mixer and related networks
"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
drop_probs = drop, drop
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.drop1 = nn.Dropout(drop_probs[0])
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop1(x)
x = self.fc2(x)
x = self.drop2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
from torch import nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_mul_pow_sqrt_tanh_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp8 * tmp7
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x0, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_pow_sqrt_tanh_0[grid(256)](buf0, buf1, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf1, (64, 4), (4, 1), 0), primals_4
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return 0.5 * x * (1 + F.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class MlpNew(nn.Module):
""" MLP as used in Vision Transformer, MLP-Mixer and related networks
"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
drop_probs = drop, drop
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.drop1 = nn.Dropout(drop_probs[0])
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop2 = nn.Dropout(drop_probs[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_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
bubbliiiing/classification-pytorch
|
Mlp
| false
| 14,988
|
[
"MIT"
] | 88
|
ee62c05bd3094c3fab48bada5a57cb2ed8b61c11
|
https://github.com/bubbliiiing/classification-pytorch/tree/ee62c05bd3094c3fab48bada5a57cb2ed8b61c11
|
PatchEmbed
|
import torch
from torch import nn
class PatchEmbed(nn.Module):
def __init__(self, input_shape=[224, 224], patch_size=16, in_chans=3,
num_features=768, norm_layer=None, flatten=True):
super().__init__()
self.num_patches = input_shape[0] // patch_size * (input_shape[1] //
patch_size)
self.flatten = flatten
self.proj = nn.Conv2d(in_chans, num_features, kernel_size=
patch_size, stride=patch_size)
self.norm = norm_layer(num_features) if norm_layer else nn.Identity()
def forward(self, x):
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2)
x = self.norm(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 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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 2304
xnumel = 256
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 256 * y3), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 768 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 12
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_convolution_2(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 768
y1 = yindex // 768
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 768 * x2 + 12288 * y1), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 16 * y3), tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (768, 3, 16, 16), (768, 256, 16, 1))
assert_size_stride(primals_2, (768,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((768, 3, 16, 16), (768, 1, 48, 3), torch.
float32)
get_raw_stream(0)
triton_poi_fused_0[grid(2304, 256)](primals_1, buf0, 2304, 256,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch
.float32)
triton_poi_fused_1[grid(12, 4096)](primals_3, buf1, 12, 4096,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(buf1, buf0, stride=(16, 16),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 768, 4, 4), (12288, 1, 3072, 768))
buf3 = empty_strided_cuda((4, 768, 4, 4), (12288, 16, 4, 1), torch.
float32)
triton_poi_fused_convolution_2[grid(3072, 16)](buf2, primals_2,
buf3, 3072, 16, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del buf2
del primals_2
return reinterpret_tensor(buf3, (4, 16, 768), (12288, 1, 16), 0
), buf0, buf1
class PatchEmbedNew(nn.Module):
def __init__(self, input_shape=[224, 224], patch_size=16, in_chans=3,
num_features=768, norm_layer=None, flatten=True):
super().__init__()
self.num_patches = input_shape[0] // patch_size * (input_shape[1] //
patch_size)
self.flatten = flatten
self.proj = nn.Conv2d(in_chans, num_features, kernel_size=
patch_size, stride=patch_size)
self.norm = norm_layer(num_features) if norm_layer else nn.Identity()
def forward(self, input_0):
primals_1 = self.proj.weight
primals_2 = self.proj.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
bubbliiiing/classification-pytorch
|
PatchEmbed
| false
| 14,989
|
[
"MIT"
] | 88
|
ee62c05bd3094c3fab48bada5a57cb2ed8b61c11
|
https://github.com/bubbliiiing/classification-pytorch/tree/ee62c05bd3094c3fab48bada5a57cb2ed8b61c11
|
QRNNLayer
|
import torch
import torch.nn as nn
from torch.optim import *
class ForgetMult(torch.nn.Module):
"""ForgetMult computes a simple recurrent equation:
h_t = f_t * x_t + (1 - f_t) * h_{t-1}
This equation is equivalent to dynamic weighted averaging.
Inputs: X, hidden
- X (seq_len, batch, input_size): tensor containing the features of the input sequence.
- F (seq_len, batch, input_size): tensor containing the forget gate values, assumed in range [0, 1].
- hidden_init (batch, input_size): tensor containing the initial hidden state for the recurrence (h_{t-1}).
"""
def __init__(self):
super(ForgetMult, self).__init__()
def forward(self, f, x, hidden_init=None):
result = []
forgets = f.split(1, dim=0)
prev_h = hidden_init
for i, h in enumerate((f * x).split(1, dim=0)):
if prev_h is not None:
h = h + (1 - forgets[i]) * prev_h
h = h.view(h.size()[1:])
result.append(h)
prev_h = h
return torch.stack(result)
class QRNNLayer(nn.Module):
"""Applies a single layer Quasi-Recurrent Neural Network (QRNN) to an input sequence.
Args:
input_size: The number of expected features in the input x.
hidden_size: The number of features in the hidden state h. If not specified, the input size is used.
save_prev_x: Whether to store previous inputs for use in future convolutional windows (i.e. for a continuing sequence such as in language modeling). If true, you must call reset to remove cached previous values of x. Default: False.
window: Defines the size of the convolutional window (how many previous tokens to look when computing the QRNN values). Supports 1 and 2. Default: 1.
zoneout: Whether to apply zoneout (i.e. failing to update elements in the hidden state) to the hidden state updates. Default: 0.
output_gate: If True, performs QRNN-fo (applying an output gate to the output). If False, performs QRNN-f. Default: True.
Inputs: X, hidden
- X (seq_len, batch, input_size): tensor containing the features of the input sequence.
- hidden (batch, hidden_size): tensor containing the initial hidden state for the QRNN.
Outputs: output, h_n
- output (seq_len, batch, hidden_size): tensor containing the output of the QRNN for each timestep.
- h_n (1, batch, hidden_size): tensor containing the hidden state for t=seq_len
"""
def __init__(self, input_size, hidden_size=None, save_prev_x=False,
zoneout=0, window=1, output_gate=True):
super(QRNNLayer, self).__init__()
assert window in [1, 2
], 'This QRNN implementation currently only handles convolutional window of size 1 or size 2'
self.window = window
self.input_size = input_size
self.hidden_size = hidden_size if hidden_size else input_size
self.zoneout = zoneout
self.save_prev_x = save_prev_x
self.prevX = None
self.output_gate = output_gate
self.linear = nn.Linear(self.window * self.input_size, 3 * self.
hidden_size if self.output_gate else 2 * self.hidden_size)
def reset(self):
self.prevX = None
def forward(self, X, hidden=None):
seq_len, batch_size, _ = X.size()
source = None
if self.window == 1:
source = X
elif self.window == 2:
Xm1 = []
Xm1.append(self.prevX if self.prevX is not None else X[:1, :, :
] * 0)
if len(X) > 1:
Xm1.append(X[:-1, :, :])
Xm1 = torch.cat(Xm1, 0)
source = torch.cat([X, Xm1], 2)
Y = self.linear(source)
if self.output_gate:
Y = Y.view(seq_len, batch_size, 3 * self.hidden_size)
Z, F, O = Y.chunk(3, dim=2)
else:
Y = Y.view(seq_len, batch_size, 2 * self.hidden_size)
Z, F = Y.chunk(2, dim=2)
Z = torch.tanh(Z)
F = torch.sigmoid(F)
if self.zoneout:
if self.training:
mask = F.new_empty(F.size(), requires_grad=False).bernoulli_(
1 - self.zoneout)
F = F * mask
else:
F *= 1 - self.zoneout
C = ForgetMult()(F, Z, hidden)
if self.output_gate:
H = torch.sigmoid(O) * C
else:
H = C
if self.window > 1 and self.save_prev_x:
self.prevX = X[-1:, :, :].detach()
return H, C[-1:, :, :]
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.optim import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_sigmoid_tanh_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 12 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (4 + x0 + 12 * x1), xmask)
tmp5 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tmp6 = tmp4 + tmp5
tmp7 = tl.sigmoid(tmp6)
tmp8 = tmp7 * tmp3
tl.store(out_ptr0 + x2, tmp3, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
tl.store(out_ptr2 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_mul_rsub_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, out_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + (16 + x0), xmask)
tmp3 = tl.load(in_ptr1 + (16 + x0), xmask)
tmp4 = tl.load(in_ptr1 + x0, xmask)
tmp7 = tl.load(in_ptr0 + (32 + x0), xmask)
tmp9 = tl.load(in_ptr1 + (32 + x0), xmask)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp5 = tmp2 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp1 - tmp7
tmp10 = tmp8 * tmp6
tmp11 = tmp9 + tmp10
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp6, xmask)
tl.store(out_ptr2 + x0, tmp8, xmask)
tl.store(out_ptr3 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused_rsub_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + (48 + x0), xmask)
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_sigmoid_stack_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, in_ptr5, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp29 = tl.load(in_ptr4 + (8 + x0 + 12 * x1), xmask)
tmp30 = tl.load(in_ptr5 + (8 + x0), xmask, eviction_policy='evict_last')
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (x0 + 4 * (-4 + x1)), tmp9 & xmask, other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 12, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr2 + (x0 + 4 * (-8 + x1)), tmp14 & xmask, other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 16, tl.int64)
tmp19 = tl.load(in_ptr0 + (48 + x0 + 4 * (-12 + x1)), tmp16 & xmask,
other=0.0)
tmp20 = tl.load(in_ptr3 + (x0 + 4 * (-12 + x1)), tmp16 & xmask, other=0.0)
tmp21 = tl.load(in_ptr2 + (x0 + 4 * (-12 + x1)), tmp16 & xmask, other=0.0)
tmp22 = tmp20 * tmp21
tmp23 = tmp19 + tmp22
tmp24 = tl.full(tmp23.shape, 0.0, tmp23.dtype)
tmp25 = tl.where(tmp16, tmp23, tmp24)
tmp26 = tl.where(tmp14, tmp15, tmp25)
tmp27 = tl.where(tmp9, tmp10, tmp26)
tmp28 = tl.where(tmp4, tmp5, tmp27)
tmp31 = tmp29 + tmp30
tmp32 = tl.sigmoid(tmp31)
tmp33 = tmp32 * tmp28
tl.store(out_ptr0 + x2, tmp28, xmask)
tl.store(out_ptr1 + x2, tmp32, xmask)
tl.store(out_ptr2 + x2, tmp33, 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, (12, 4), (4, 1))
assert_size_stride(primals_3, (12,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 12), (12, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 12), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_tanh_0[grid(64)](buf0, primals_3, buf1,
buf2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
buf6 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
buf7 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_mul_rsub_1[grid(16)](buf2, buf3, buf4, buf5,
buf6, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf8 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_rsub_2[grid(16)](buf2, buf8, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_mul_sigmoid_stack_3[grid(64)](buf3, buf5, buf7,
buf8, buf0, primals_3, buf9, buf10, buf11, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf0
del primals_3
return buf11, reinterpret_tensor(buf9, (1, 4, 4), (16, 4, 1), 48
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf1, buf2, reinterpret_tensor(buf3, (4, 4), (4, 1), 0
), buf4, reinterpret_tensor(buf5, (4, 4), (4, 1), 0
), buf6, reinterpret_tensor(buf7, (4, 4), (4, 1), 0), buf8, buf9, buf10
class ForgetMult(torch.nn.Module):
"""ForgetMult computes a simple recurrent equation:
h_t = f_t * x_t + (1 - f_t) * h_{t-1}
This equation is equivalent to dynamic weighted averaging.
Inputs: X, hidden
- X (seq_len, batch, input_size): tensor containing the features of the input sequence.
- F (seq_len, batch, input_size): tensor containing the forget gate values, assumed in range [0, 1].
- hidden_init (batch, input_size): tensor containing the initial hidden state for the recurrence (h_{t-1}).
"""
def __init__(self):
super(ForgetMult, self).__init__()
def forward(self, f, x, hidden_init=None):
result = []
forgets = f.split(1, dim=0)
prev_h = hidden_init
for i, h in enumerate((f * x).split(1, dim=0)):
if prev_h is not None:
h = h + (1 - forgets[i]) * prev_h
h = h.view(h.size()[1:])
result.append(h)
prev_h = h
return torch.stack(result)
class QRNNLayerNew(nn.Module):
"""Applies a single layer Quasi-Recurrent Neural Network (QRNN) to an input sequence.
Args:
input_size: The number of expected features in the input x.
hidden_size: The number of features in the hidden state h. If not specified, the input size is used.
save_prev_x: Whether to store previous inputs for use in future convolutional windows (i.e. for a continuing sequence such as in language modeling). If true, you must call reset to remove cached previous values of x. Default: False.
window: Defines the size of the convolutional window (how many previous tokens to look when computing the QRNN values). Supports 1 and 2. Default: 1.
zoneout: Whether to apply zoneout (i.e. failing to update elements in the hidden state) to the hidden state updates. Default: 0.
output_gate: If True, performs QRNN-fo (applying an output gate to the output). If False, performs QRNN-f. Default: True.
Inputs: X, hidden
- X (seq_len, batch, input_size): tensor containing the features of the input sequence.
- hidden (batch, hidden_size): tensor containing the initial hidden state for the QRNN.
Outputs: output, h_n
- output (seq_len, batch, hidden_size): tensor containing the output of the QRNN for each timestep.
- h_n (1, batch, hidden_size): tensor containing the hidden state for t=seq_len
"""
def __init__(self, input_size, hidden_size=None, save_prev_x=False,
zoneout=0, window=1, output_gate=True):
super(QRNNLayerNew, self).__init__()
assert window in [1, 2
], 'This QRNN implementation currently only handles convolutional window of size 1 or size 2'
self.window = window
self.input_size = input_size
self.hidden_size = hidden_size if hidden_size else input_size
self.zoneout = zoneout
self.save_prev_x = save_prev_x
self.prevX = None
self.output_gate = output_gate
self.linear = nn.Linear(self.window * self.input_size, 3 * self.
hidden_size if self.output_gate else 2 * self.hidden_size)
def reset(self):
self.prevX = None
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], output[1]
|
boshining/NeuronBlocks
|
QRNNLayer
| false
| 14,990
|
[
"MIT"
] | 1,257
|
74fbb8658fb3f1cffea5c9bc84b2a1da59c20dd9
|
https://github.com/boshining/NeuronBlocks/tree/74fbb8658fb3f1cffea5c9bc84b2a1da59c20dd9
|
DiffLoss
|
import torch
import torch.nn as nn
import torch.utils.checkpoint
class DiffLoss(nn.Module):
def __init__(self):
super(DiffLoss, self).__init__()
def forward(self, input1, input2):
batch_size = input1.size(0)
input1 = input1.view(batch_size, -1)
input2 = input2.view(batch_size, -1)
input1_mean = torch.mean(input1, dim=0, keepdims=True)
input2_mean = torch.mean(input2, dim=0, keepdims=True)
input1 = input1 - input1_mean
input2 = input2 - input2_mean
input1_l2_norm = torch.norm(input1, p=2, dim=1, keepdim=True).detach()
input1_l2 = input1.div(input1_l2_norm.expand_as(input1) + 1e-06)
input2_l2_norm = torch.norm(input2, p=2, dim=1, keepdim=True).detach()
input2_l2 = input2.div(input2_l2_norm.expand_as(input2) + 1e-06)
diff_loss = torch.mean(input1_l2.t().mm(input2_l2).pow(2))
return diff_loss
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.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_linalg_vector_norm_mean_sub_0(in_ptr0,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + r1, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (64 + r1), None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (128 + r1), None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (192 + r1), None, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tmp11 = tmp10 * tmp10
tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
tmp14 = tl.where(xmask, tmp12, 0)
tmp15 = tl.sum(tmp14, 1)[:, None]
tmp16 = libdevice.sqrt(tmp15)
tmp17 = 1e-06
tmp18 = tmp16 + tmp17
tmp19 = tmp10 / tmp18
tl.store(out_ptr2 + (r1 + 64 * x0), tmp19, xmask)
@triton.jit
def triton_red_fused_mean_pow_1(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rbase = tl.arange(0, RBLOCK)[None, :]
_tmp3 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, rmask, eviction_policy='evict_first',
other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = _tmp3 + tmp2
_tmp3 = tl.where(rmask, tmp4, _tmp3)
tmp3 = tl.sum(_tmp3, 1)[:, None]
tmp5 = 4096.0
tmp6 = tmp3 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp6, 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)
buf4 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_linalg_vector_norm_mean_sub_0[grid(4)](arg0_1,
buf4, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
buf5 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_mean_sub_0[grid(4)](arg1_1,
buf5, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
buf6 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (64, 4), (1, 64), 0),
buf5, out=buf6)
del buf4
del buf5
buf7 = empty_strided_cuda((), (), torch.float32)
buf8 = buf7
del buf7
triton_red_fused_mean_pow_1[grid(1)](buf8, buf6, 1, 4096, XBLOCK=1,
RBLOCK=2048, num_warps=16, num_stages=1)
del buf6
return buf8,
class DiffLossNew(nn.Module):
def __init__(self):
super(DiffLossNew, 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]
|
byamao1/MMSA
|
DiffLoss
| false
| 14,991
|
[
"MIT"
] | 198
|
1a894d042144c9ac75b3465d38871ce8c2987251
|
https://github.com/byamao1/MMSA/tree/1a894d042144c9ac75b3465d38871ce8c2987251
|
MultiheadAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import torch.utils.checkpoint
from torch.nn import Parameter
class MultiheadAttention(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(self, embed_dim, num_heads, attn_dropout=0.0, bias=True,
add_bias_kv=False, add_zero_attn=False):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.attn_dropout = attn_dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
self.scaling = self.head_dim ** -0.5
self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim))
self.register_parameter('in_proj_bias', None)
if bias:
self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim))
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.in_proj_weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
nn.init.xavier_normal_(self.bias_k)
if self.bias_v is not None:
nn.init.xavier_normal_(self.bias_v)
def forward(self, query, key, value, attn_mask=None):
"""Input shape: Time x Batch x Channel
Self-attention can be implemented by passing in the same arguments for
query, key and value. Timesteps can be masked by supplying a T x T mask in the
`attn_mask` argument. Padding elements can be excluded from
the key by passing a binary ByteTensor (`key_padding_mask`) with shape:
batch x src_len, where padding elements are indicated by 1s.
"""
qkv_same = query.data_ptr() == key.data_ptr() == value.data_ptr()
kv_same = key.data_ptr() == value.data_ptr()
tgt_len, bsz, embed_dim = query.size()
assert embed_dim == self.embed_dim
assert list(query.size()) == [tgt_len, bsz, embed_dim]
assert key.size() == value.size()
if qkv_same:
q, k, v = self.in_proj_qkv(query)
elif kv_same:
q = self.in_proj_q(query)
if key is None:
assert value is None
k = v = None
else:
k, v = self.in_proj_kv(key)
else:
q = self.in_proj_q(query)
k = self.in_proj_k(key)
v = self.in_proj_v(value)
q *= self.scaling
if self.bias_k is not None:
assert self.bias_v is not None
k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
if attn_mask is not None:
attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(
attn_mask.size(0), 1)], dim=1)
q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
if k is not None:
k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
if v is not None:
v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim
).transpose(0, 1)
src_len = k.size(1)
if self.add_zero_attn:
src_len += 1
k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])],
dim=1)
v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])],
dim=1)
if attn_mask is not None:
attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(
attn_mask.size(0), 1)], dim=1)
attn_weights = torch.bmm(q, k.transpose(1, 2))
assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len,
src_len]
if attn_mask is not None:
try:
attn_weights += attn_mask.unsqueeze(0)
except:
None
None
assert False
attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(
attn_weights)
attn_weights = F.dropout(attn_weights, p=self.attn_dropout,
training=self.training)
attn = torch.bmm(attn_weights, v)
assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.
head_dim]
attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
attn = self.out_proj(attn)
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights.sum(dim=1) / self.num_heads
return attn, attn_weights
def in_proj_qkv(self, query):
return self._in_proj(query).chunk(3, dim=-1)
def in_proj_kv(self, key):
return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
def in_proj_q(self, query, **kwargs):
return self._in_proj(query, end=self.embed_dim, **kwargs)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=0, end=None, **kwargs):
weight = kwargs.get('weight', self.in_proj_weight)
bias = kwargs.get('bias', self.in_proj_bias)
weight = weight[start:end, :]
if bias is not None:
bias = bias[start:end]
return F.linear(input, weight, bias)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4,
4, 4, 4])]
def get_init_inputs():
return [[], {'embed_dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import torch.utils.checkpoint
from torch.nn import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused__softmax_1(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 64
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]
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]
tmp11 = tmp6 / tmp10
tl.store(out_ptr2 + (r1 + 16 * x0), tmp11, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 4
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (x1 + 16 * y0), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_div_sum_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x1 = xindex // 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 256 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (128 + x0 + 256 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (192 + x0 + 256 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (12,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 4),
reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 16), alpha=1,
beta=1, out=buf1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_5, (4,), (1,), 8),
reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 32), alpha=1,
beta=1, out=buf2)
del primals_4
buf3 = reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_mul_0[grid(64)](buf3, primals_5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((16, 4, 16), (64, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (1, 16, 0),
0), reinterpret_tensor(buf1, (16, 1, 16), (1, 1, 16), 0), out=buf4)
buf7 = empty_strided_cuda((16, 4, 16), (64, 16, 1), torch.float32)
triton_per_fused__softmax_1[grid(64)](buf4, buf7, 64, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del buf4
buf8 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf7, reinterpret_tensor(buf2, (16, 16, 1), (1,
16, 1), 0), out=buf8)
buf9 = empty_strided_cuda((4, 16, 1), (16, 1, 1), torch.float32)
triton_poi_fused_clone_2[grid(4, 16)](buf8, buf9, 4, 16, XBLOCK=16,
YBLOCK=4, num_warps=1, num_stages=1)
buf10 = reinterpret_tensor(buf8, (16, 4), (4, 1), 0)
del buf8
extern_kernels.addmm(primals_7, reinterpret_tensor(buf9, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf10)
del primals_7
buf11 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_div_sum_3[grid(256)](buf7, buf11, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0
), buf11, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf9, (16, 4), (4, 1), 0
), primals_6, reinterpret_tensor(buf2, (16, 1, 16), (1, 1, 16), 0
), reinterpret_tensor(buf3, (16, 1, 4), (1, 1, 16), 0
), reinterpret_tensor(buf1, (16, 16, 1), (1, 16, 1), 0)
class MultiheadAttentionNew(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(self, embed_dim, num_heads, attn_dropout=0.0, bias=True,
add_bias_kv=False, add_zero_attn=False):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.attn_dropout = attn_dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
self.scaling = self.head_dim ** -0.5
self.in_proj_weight = Parameter(torch.Tensor(3 * embed_dim, embed_dim))
self.register_parameter('in_proj_bias', None)
if bias:
self.in_proj_bias = Parameter(torch.Tensor(3 * embed_dim))
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.in_proj_weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.in_proj_bias is not None:
nn.init.constant_(self.in_proj_bias, 0.0)
nn.init.constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
nn.init.xavier_normal_(self.bias_k)
if self.bias_v is not None:
nn.init.xavier_normal_(self.bias_v)
def in_proj_qkv(self, query):
return self._in_proj(query).chunk(3, dim=-1)
def in_proj_kv(self, key):
return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
def in_proj_q(self, query, **kwargs):
return self._in_proj(query, end=self.embed_dim, **kwargs)
def in_proj_k(self, key):
return self._in_proj(key, start=self.embed_dim, end=2 * self.embed_dim)
def in_proj_v(self, value):
return self._in_proj(value, start=2 * self.embed_dim)
def _in_proj(self, input, start=0, end=None, **kwargs):
weight = kwargs.get('weight', self.in_proj_weight)
bias = kwargs.get('bias', self.in_proj_bias)
weight = weight[start:end, :]
if bias is not None:
bias = bias[start:end]
return F.linear(input, weight, bias)
def forward(self, input_0, input_1, input_2):
primals_4 = self.in_proj_weight
primals_5 = self.in_proj_bias
primals_6 = self.out_proj.weight
primals_7 = self.out_proj.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
byamao1/MMSA
|
MultiheadAttention
| false
| 14,992
|
[
"MIT"
] | 198
|
1a894d042144c9ac75b3465d38871ce8c2987251
|
https://github.com/byamao1/MMSA/tree/1a894d042144c9ac75b3465d38871ce8c2987251
|
Discriminator
|
import torch
import numpy as np
from torch import nn
from torch.nn import functional as F
class Discriminator(nn.Module):
def __init__(self, img_shape, hidden_dim=1024):
super().__init__()
in_dim = int(np.prod(img_shape))
self.fc1 = nn.Linear(in_dim, hidden_dim)
self.fc2 = nn.Linear(self.fc1.out_features, self.fc1.out_features // 2)
self.fc3 = nn.Linear(self.fc2.out_features, self.fc2.out_features // 2)
self.fc4 = nn.Linear(self.fc3.out_features, 1)
def forward(self, img):
x = img.view(img.size(0), -1)
x = F.leaky_relu(self.fc1(x), 0.2)
x = F.dropout(x, 0.3)
x = F.leaky_relu(self.fc2(x), 0.2)
x = F.dropout(x, 0.3)
x = F.leaky_relu(self.fc3(x), 0.2)
x = F.dropout(x, 0.3)
return torch.sigmoid(self.fc4(x))
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'img_shape': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import numpy as np
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 1024
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, None)
tl.store(out_ptr1 + x2, tmp7, None)
@triton.jit
def triton_poi_fused_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, None)
tl.store(out_ptr1 + x2, tmp7, None)
@triton.jit
def triton_poi_fused_leaky_relu_2(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 256
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
@triton.jit
def triton_poi_fused_sigmoid_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (1024, 4), (4, 1))
assert_size_stride(primals_3, (1024,), (1,))
assert_size_stride(primals_4, (512, 1024), (1024, 1))
assert_size_stride(primals_5, (512,), (1,))
assert_size_stride(primals_6, (256, 512), (512, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (1, 256), (256, 1))
assert_size_stride(primals_9, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1024), (1024, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 1024
), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 1024), (1024, 1), torch.bool)
buf2 = empty_strided_cuda((4, 1024), (1024, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(4096)](buf0, primals_3, buf1,
buf2, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_3
buf3 = torch.ops.aten.native_dropout.default(buf2, 0.3, True)
del buf2
buf4 = buf3[0]
buf5 = buf3[1]
del buf3
buf6 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_4, (1024, 512),
(1, 1024), 0), out=buf6)
buf7 = empty_strided_cuda((4, 512), (512, 1), torch.bool)
buf8 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
triton_poi_fused_leaky_relu_1[grid(2048)](buf6, primals_5, buf7,
buf8, 2048, XBLOCK=128, num_warps=4, num_stages=1)
del buf6
del primals_5
buf9 = torch.ops.aten.native_dropout.default(buf8, 0.3, True)
del buf8
buf10 = buf9[0]
buf11 = buf9[1]
del buf9
buf12 = empty_strided_cuda((4, 256), (256, 1), torch.float32)
extern_kernels.mm(buf10, reinterpret_tensor(primals_6, (512, 256),
(1, 512), 0), out=buf12)
buf13 = empty_strided_cuda((4, 256), (256, 1), torch.bool)
buf14 = empty_strided_cuda((4, 256), (256, 1), torch.float32)
triton_poi_fused_leaky_relu_2[grid(1024)](buf12, primals_7, buf13,
buf14, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del buf12
del primals_7
buf15 = torch.ops.aten.native_dropout.default(buf14, 0.3, True)
del buf14
buf16 = buf15[0]
buf17 = buf15[1]
del buf15
buf18 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf16, reinterpret_tensor(primals_8, (256, 1), (1,
256), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_sigmoid_3[grid(4)](buf19, primals_9, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_9
return (buf19, primals_1, buf1, buf4, buf5, buf7, buf10, buf11, buf13,
buf16, buf17, buf19, primals_8, primals_6, primals_4)
class DiscriminatorNew(nn.Module):
def __init__(self, img_shape, hidden_dim=1024):
super().__init__()
in_dim = int(np.prod(img_shape))
self.fc1 = nn.Linear(in_dim, hidden_dim)
self.fc2 = nn.Linear(self.fc1.out_features, self.fc1.out_features // 2)
self.fc3 = nn.Linear(self.fc2.out_features, self.fc2.out_features // 2)
self.fc4 = nn.Linear(self.fc3.out_features, 1)
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_8 = self.fc4.weight
primals_9 = self.fc4.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
bzrry/lightning-bolts
|
Discriminator
| false
| 14,993
|
[
"Apache-2.0"
] | 822
|
bd392ad858039290c72c20cc3f10df39384e90b9
|
https://github.com/bzrry/lightning-bolts/tree/bd392ad858039290c72c20cc3f10df39384e90b9
|
SchedulerTestNet
|
import torch
from torch.nn import functional as F
class SchedulerTestNet(torch.nn.Module):
"""adapted from: https://github.com/pytorch/pytorch/blob/master/test/test_optim.py."""
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(1, 1, 1)
self.conv2 = torch.nn.Conv2d(1, 1, 1)
def forward(self, x):
return self.conv2(F.relu(self.conv1(x)))
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.full([1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tl.store(in_out_ptr0 + x0, tmp5, None)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, None)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (1, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (1, 1, 1, 1), (1, 1, 1, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(16384)](buf1, primals_2,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 1, 64, 64), (4096, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(16384)](buf3, primals_5, 16384,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1
class SchedulerTestNetNew(torch.nn.Module):
"""adapted from: https://github.com/pytorch/pytorch/blob/master/test/test_optim.py."""
def __init__(self):
super().__init__()
self.conv1 = torch.nn.Conv2d(1, 1, 1)
self.conv2 = torch.nn.Conv2d(1, 1, 1)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
bzrry/lightning-bolts
|
SchedulerTestNet
| false
| 14,994
|
[
"Apache-2.0"
] | 822
|
bd392ad858039290c72c20cc3f10df39384e90b9
|
https://github.com/bzrry/lightning-bolts/tree/bd392ad858039290c72c20cc3f10df39384e90b9
|
SELoss
|
import torch
from torch import Tensor
from torch import nn
class SELoss(nn.MSELoss):
def __init__(self):
super().__init__(reduction='none')
def forward(self, inputs: 'Tensor', target: 'Tensor') ->Tensor:
return super().forward(inputs, target).sum(1)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mse_loss_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp4 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp10 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp14 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tl.store(out_ptr0 + x2, tmp18, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mse_loss_sum_0[grid(64)](arg1_1, arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class SELossNew(nn.MSELoss):
def __init__(self):
super().__init__(reduction='none')
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
bzrry/lightning-bolts
|
SELoss
| false
| 14,995
|
[
"Apache-2.0"
] | 822
|
bd392ad858039290c72c20cc3f10df39384e90b9
|
https://github.com/bzrry/lightning-bolts/tree/bd392ad858039290c72c20cc3f10df39384e90b9
|
Discriminator
|
import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, n_in, n_out):
super(Discriminator, self).__init__()
self.f_k = nn.Bilinear(n_in, n_out, 1)
self.sigm = nn.Sigmoid()
for m in self.modules():
self.weights_init(m)
def weights_init(self, m):
if isinstance(m, nn.Bilinear):
torch.nn.init.xavier_uniform_(m.weight.data)
if m.bias is not None:
m.bias.data.fill_(0.0)
def forward(self, S, node, s_bias=None):
S = S.expand_as(node)
score = torch.squeeze(self.f_k(node, S), 1)
if s_bias is not None:
score += s_bias
return self.sigm(score)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_in': 4, 'n_out': 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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_sigmoid_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten._trilinear.default(reinterpret_tensor(
primals_2, (64, 4), (4, 1), 0), primals_3, reinterpret_tensor(
primals_1, (64, 4), (4, 1), 0), [1, 3], [0], [1, 2], [2, 3])
del primals_3
buf1 = buf0
del buf0
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
get_raw_stream(0)
triton_poi_fused_add_sigmoid_0[grid(64)](buf2, primals_4, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_4
return buf2, reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), buf2
class DiscriminatorNew(nn.Module):
def __init__(self, n_in, n_out):
super(DiscriminatorNew, self).__init__()
self.f_k = nn.Bilinear(n_in, n_out, 1)
self.sigm = nn.Sigmoid()
for m in self.modules():
self.weights_init(m)
def weights_init(self, m):
if isinstance(m, nn.Bilinear):
torch.nn.init.xavier_uniform_(m.weight.data)
if m.bias is not None:
m.bias.data.fill_(0.0)
def forward(self, input_0, input_1):
primals_3 = self.f_k.weight
primals_4 = self.f_k.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
caojiangxia/BiGI
|
Discriminator
| false
| 14,996
|
[
"MIT"
] | 57
|
ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
https://github.com/caojiangxia/BiGI/tree/ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
GCN
|
from torch.nn import Module
import math
import torch
import torch.nn as nn
from torch.nn.modules.module import Module
class GraphConvolution(Module):
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(torch.FloatTensor(in_features, out_features)
)
if bias:
self.bias = nn.Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GCN(nn.Module):
def __init__(self, nfeat, nhid, dropout, alpha):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.dropout = dropout
self.leakyrelu = nn.LeakyReLU(alpha)
def forward(self, x, adj):
x = self.leakyrelu(self.gc1(x, adj))
return x
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'nfeat': 4, 'nhid': 4, 'dropout': 0.5, 'alpha': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.nn import Module
import math
import torch.nn as nn
from torch.nn.modules.module import Module
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 4.0
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), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_2, primals_1, out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_3, buf0, out=buf1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_leaky_relu_0[grid(16)](buf1, primals_4, buf2,
buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf1
del primals_4
return buf3, buf2, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0
), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0)
class GraphConvolution(Module):
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = nn.Parameter(torch.FloatTensor(in_features, out_features)
)
if bias:
self.bias = nn.Parameter(torch.FloatTensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GCNNew(nn.Module):
def __init__(self, nfeat, nhid, dropout, alpha):
super(GCNNew, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.dropout = dropout
self.leakyrelu = nn.LeakyReLU(alpha)
def forward(self, input_0, input_1):
primals_1 = self.gc1.weight
primals_4 = self.gc1.bias
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
caojiangxia/BiGI
|
GCN
| false
| 14,997
|
[
"MIT"
] | 57
|
ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
https://github.com/caojiangxia/BiGI/tree/ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
Block
|
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False):
if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.
device)
random_tensor.floor_()
output = x.div(keep_prob) * random_tensor
return output
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return 0.5 * x * (1 + F.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class DropPath(nn.Module):
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training)
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0,
proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
self.scale = (dim // num_heads) ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads
).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Mlp(nn.Module):
""" MLP as used in Vision Transformer, MLP-Mixer and related networks
"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
drop_probs = drop, drop
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.drop1 = nn.Dropout(drop_probs[0])
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop1(x)
x = self.fc2(x)
x = self.drop2(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, drop=
0.0, attn_drop=0.0, drop_path=0.0, act_layer=GELU, norm_layer=nn.
LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias,
attn_drop=attn_drop, proj_drop=drop)
self.norm2 = norm_layer(dim)
self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio
), act_layer=act_layer, drop=drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'num_heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import numpy as np
from torch import nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (4 + y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tmp14 * tmp1
tmp16 = tl_math.exp(tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused__softmax_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (8 + y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_8(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + 1)
tmp9 = tl.broadcast_to(tmp8, [XBLOCK])
tmp13 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr2 + 2)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK])
tmp20 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr2 + 3)
tmp23 = tl.broadcast_to(tmp22, [XBLOCK])
tmp4 = tmp1 + tmp3
tmp5 = tmp0 + tmp4
tmp10 = tmp7 + tmp9
tmp11 = tmp6 + tmp10
tmp12 = tmp5 + tmp11
tmp17 = tmp14 + tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp12 + tmp18
tmp24 = tmp21 + tmp23
tmp25 = tmp20 + tmp24
tmp26 = tmp19 + tmp25
tmp27 = 4.0
tmp28 = tmp26 / tmp27
tmp29 = tmp5 - tmp28
tmp30 = tmp29 * tmp29
tmp31 = tmp11 - tmp28
tmp32 = tmp31 * tmp31
tmp33 = tmp30 + tmp32
tmp34 = tmp18 - tmp28
tmp35 = tmp34 * tmp34
tmp36 = tmp33 + tmp35
tmp37 = tmp25 - tmp28
tmp38 = tmp37 * tmp37
tmp39 = tmp36 + tmp38
tmp40 = tmp39 / tmp27
tl.store(out_ptr0 + x0, tmp28, xmask)
tl.store(out_ptr1 + x0, tmp40, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_9(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp6 = tmp4 - tmp5
tmp8 = 1e-05
tmp9 = tmp7 + tmp8
tmp10 = libdevice.rsqrt(tmp9)
tmp11 = tmp6 * tmp10
tmp13 = tmp11 * tmp12
tmp15 = tmp13 + tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
@triton.jit
def triton_poi_fused_add_mul_pow_sqrt_tanh_10(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp8 * tmp7
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused_add_11(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_out_ptr0 + x2, xmask)
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp7 = tmp5 + tmp6
tmp8 = tmp4 + tmp7
tl.store(in_out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (12, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (16, 4), (4, 1))
assert_size_stride(primals_10, (16,), (1,))
assert_size_stride(primals_11, (4, 16), (16, 1))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(16)](primals_3, buf0,
buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((16, 12), (12, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 12), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_2[grid(16, 4)](buf3, buf4, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(16, 4)](buf3, buf5, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf5, (16, 1, 4), (4, 0, 1), 0), out=buf6)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(256)](buf6, buf7, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf6
triton_poi_fused__softmax_5[grid(256)](buf7, buf8, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_6[grid(16, 4)](buf3, buf9, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf3
buf10 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (16, 4, 1), (4, 1, 0), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_7[grid(16, 4)](buf10, buf11, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (16, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf11, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), out=buf12)
buf13 = buf1
del buf1
buf14 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_8[grid(16)](primals_3, buf12,
primals_6, buf13, buf14, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_9[grid(64)](primals_3, buf12,
primals_6, buf13, buf14, primals_7, primals_8, buf15, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf13
del buf14
del primals_8
buf16 = reinterpret_tensor(buf7, (16, 16), (16, 1), 0)
del buf7
extern_kernels.addmm(primals_10, reinterpret_tensor(buf15, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_9, (4, 16), (1, 4), 0),
alpha=1, beta=1, out=buf16)
del primals_10
buf17 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_add_mul_pow_sqrt_tanh_10[grid(256)](buf16, buf17,
256, XBLOCK=256, num_warps=4, num_stages=1)
buf18 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf17, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_11, (16, 4), (1, 16), 0), out=buf18)
buf19 = reinterpret_tensor(buf18, (4, 4, 4), (16, 4, 1), 0)
del buf18
triton_poi_fused_add_11[grid(64)](buf19, primals_3, buf12,
primals_6, primals_12, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_12
return buf19, primals_3, primals_6, primals_7, reinterpret_tensor(buf2,
(16, 4), (4, 1), 0), buf8, reinterpret_tensor(buf11, (16, 4), (4, 1), 0
), buf12, reinterpret_tensor(buf15, (16, 4), (4, 1), 0
), buf16, reinterpret_tensor(buf17, (16, 16), (16, 1), 0
), primals_11, primals_9, primals_5, reinterpret_tensor(buf9, (16,
1, 4), (4, 1, 1), 0), reinterpret_tensor(buf4, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf5, (16, 4, 1), (4, 1, 4), 0), primals_4
def drop_path(x, drop_prob: 'float'=0.0, training: 'bool'=False):
if drop_prob == 0.0 or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1)
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.
device)
random_tensor.floor_()
output = x.div(keep_prob) * random_tensor
return output
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return 0.5 * x * (1 + F.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class DropPath(nn.Module):
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training)
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0.0,
proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
self.scale = (dim // num_heads) ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads
).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2]
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Mlp(nn.Module):
""" MLP as used in Vision Transformer, MLP-Mixer and related networks
"""
def __init__(self, in_features, hidden_features=None, out_features=None,
act_layer=GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
drop_probs = drop, drop
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.drop1 = nn.Dropout(drop_probs[0])
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop1(x)
x = self.fc2(x)
x = self.drop2(x)
return x
class BlockNew(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, drop=
0.0, attn_drop=0.0, drop_path=0.0, act_layer=GELU, norm_layer=nn.
LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias,
attn_drop=attn_drop, proj_drop=drop)
self.norm2 = norm_layer(dim)
self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio
), act_layer=act_layer, drop=drop)
self.drop_path = DropPath(drop_path
) if drop_path > 0.0 else nn.Identity()
def forward(self, input_0):
primals_1 = self.norm1.weight
primals_2 = self.norm1.bias
primals_4 = self.attn.qkv.weight
primals_5 = self.attn.proj.weight
primals_6 = self.attn.proj.bias
primals_7 = self.norm2.weight
primals_8 = self.norm2.bias
primals_9 = self.mlp.fc1.weight
primals_10 = self.mlp.fc1.bias
primals_11 = self.mlp.fc2.weight
primals_12 = self.mlp.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
bubbliiiing/classification-pytorch
|
Block
| false
| 14,998
|
[
"MIT"
] | 88
|
ee62c05bd3094c3fab48bada5a57cb2ed8b61c11
|
https://github.com/bubbliiiing/classification-pytorch/tree/ee62c05bd3094c3fab48bada5a57cb2ed8b61c11
|
Ln_distance
|
import torch
from torch import nn
import torch.utils.data
class Ln_distance(nn.Module):
"""If dims is None Compute across all dimensions except first"""
def __init__(self, n, dim=None):
super(Ln_distance, self).__init__()
self.n = n
self.dim = dim
def forward(self, x, y):
d = x - y
if self.dim is None:
self.dim = list(range(1, len(d.shape)))
return torch.abs(d).pow(self.n).sum(dim=self.dim).pow(1.0 / float(
self.n))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n': 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, math as tl_math
from torch import nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_abs_pow_sub_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tmp3 * tmp3
tmp5 = tmp4 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = 0.25
tmp11 = libdevice.pow(tmp9, tmp10)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp11, 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,), (1,), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_abs_pow_sub_sum_0[grid(4)](buf1, arg0_1, arg1_1, 4,
64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class Ln_distanceNew(nn.Module):
"""If dims is None Compute across all dimensions except first"""
def __init__(self, n, dim=None):
super(Ln_distanceNew, self).__init__()
self.n = n
self.dim = dim
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
carla-recourse/CARLA
|
Ln_distance
| false
| 15,000
|
[
"MIT"
] | 140
|
e9bb3152598a94e700c38d7377825054959dcf48
|
https://github.com/carla-recourse/CARLA/tree/e9bb3152598a94e700c38d7377825054959dcf48
|
CombinedTargetMSELoss
|
import torch
import torch.nn as nn
class CombinedTargetMSELoss(nn.Module):
"""MSE loss for combined target.
CombinedTarget: The combination of classification target
(response map) and regression target (offset map).
Paper ref: Huang et al. The Devil is in the Details: Delving into
Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
Args:
use_target_weight (bool): Option to use weighted MSE loss.
Different joint types may have different target weights.
loss_weight (float): Weight of the loss. Default: 1.0.
"""
def __init__(self, use_target_weight, loss_weight=1.0):
super().__init__()
self.criterion = nn.MSELoss(reduction='mean')
self.use_target_weight = use_target_weight
self.loss_weight = loss_weight
def forward(self, output, target, target_weight):
batch_size = output.size(0)
num_channels = output.size(1)
heatmaps_pred = output.reshape((batch_size, num_channels, -1)).split(
1, 1)
heatmaps_gt = target.reshape((batch_size, num_channels, -1)).split(1, 1
)
loss = 0.0
num_joints = num_channels // 3
for idx in range(num_joints):
heatmap_pred = heatmaps_pred[idx * 3].squeeze()
heatmap_gt = heatmaps_gt[idx * 3].squeeze()
offset_x_pred = heatmaps_pred[idx * 3 + 1].squeeze()
offset_x_gt = heatmaps_gt[idx * 3 + 1].squeeze()
offset_y_pred = heatmaps_pred[idx * 3 + 2].squeeze()
offset_y_gt = heatmaps_gt[idx * 3 + 2].squeeze()
if self.use_target_weight:
heatmap_pred = heatmap_pred * target_weight[:, idx]
heatmap_gt = heatmap_gt * target_weight[:, idx]
loss += 0.5 * self.criterion(heatmap_pred, heatmap_gt)
loss += 0.5 * self.criterion(heatmap_gt * offset_x_pred,
heatmap_gt * offset_x_gt)
loss += 0.5 * self.criterion(heatmap_gt * offset_y_pred,
heatmap_gt * offset_y_gt)
return loss / num_joints * self.loss_weight
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'use_target_weight': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mse_loss_mul_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 - tmp4
tmp6 = tmp5 * tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp11 = tmp4 * tmp10
tmp13 = tmp4 * tmp12
tmp14 = tmp11 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.sum(tmp16, 1)[:, None]
tmp20 = tmp4 * tmp19
tmp22 = tmp4 * tmp21
tmp23 = tmp20 - tmp22
tmp24 = tmp23 * tmp23
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp27 = tl.sum(tmp25, 1)[:, None]
tmp28 = 4.0
tmp29 = tmp9 / tmp28
tmp30 = 0.5
tmp31 = tmp29 * tmp30
tmp32 = 0.0
tmp33 = tmp31 + tmp32
tmp34 = tmp18 / tmp28
tmp35 = tmp34 * tmp30
tmp36 = tmp33 + tmp35
tmp37 = tmp27 / tmp28
tmp38 = tmp37 * tmp30
tmp39 = tmp36 + tmp38
tmp40 = 1.0
tmp41 = tmp39 * tmp40
tmp42 = tmp41 * tmp40
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp42, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mse_loss_mul_0[grid(1)](buf3, arg0_1,
arg2_1, arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf3,
class CombinedTargetMSELossNew(nn.Module):
"""MSE loss for combined target.
CombinedTarget: The combination of classification target
(response map) and regression target (offset map).
Paper ref: Huang et al. The Devil is in the Details: Delving into
Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
Args:
use_target_weight (bool): Option to use weighted MSE loss.
Different joint types may have different target weights.
loss_weight (float): Weight of the loss. Default: 1.0.
"""
def __init__(self, use_target_weight, loss_weight=1.0):
super().__init__()
self.criterion = nn.MSELoss(reduction='mean')
self.use_target_weight = use_target_weight
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]
|
carolchenyx/mmpose
|
CombinedTargetMSELoss
| false
| 15,001
|
[
"Apache-2.0"
] | 367
|
cd74bf1d0b13954188cc678415fd0ef98a74b46b
|
https://github.com/carolchenyx/mmpose/tree/cd74bf1d0b13954188cc678415fd0ef98a74b46b
|
Square
|
import torch
import torch.nn as nn
class Square(nn.Module):
def __init__(self):
super(Square, self).__init__()
def forward(self, x):
return torch.mul(x, 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_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 = tmp0 * tmp0
tl.store(out_ptr0 + x0, tmp1, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class SquareNew(nn.Module):
def __init__(self):
super(SquareNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
carlzhangweiwen/gazelle_mpc
|
Square
| false
| 15,002
|
[
"MIT"
] | 50
|
45818ccf6375100a8fe2680f44f37d713380aa5c
|
https://github.com/carlzhangweiwen/gazelle_mpc/tree/45818ccf6375100a8fe2680f44f37d713380aa5c
|
Attention
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, opt):
super(Attention, self).__init__()
self.lin_u = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.lin_v = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.opt = opt
def forward(self, user, item, UV_adj, VU_adj):
user = self.lin_u(user)
item = self.lin_v(item)
query = user
key = item
value = torch.mm(query, key.transpose(0, 1))
value = UV_adj.to_dense() * value
value /= math.sqrt(self.opt['hidden_dim'])
value = F.softmax(value, dim=1)
learn_user = torch.matmul(value, key) + user
query = item
key = user
value = torch.mm(query, key.transpose(0, 1))
value = VU_adj.to_dense() * value
value /= math.sqrt(self.opt['hidden_dim'])
value = F.softmax(value, dim=1)
learn_item = torch.matmul(value, key) + item
return learn_user, learn_item
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4]),
torch.rand([4, 4])]
def get_init_inputs():
return [[], {'opt': _mock_config(hidden_dim=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_mul_0(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')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp7 = tmp5 * tmp6
tmp8 = tmp7 * tmp3
tmp9 = triton_helpers.maximum(tmp4, tmp8)
tmp12 = tmp10 * tmp11
tmp13 = tmp12 * tmp3
tmp14 = triton_helpers.maximum(tmp9, tmp13)
tmp17 = tmp15 * tmp16
tmp18 = tmp17 * tmp3
tmp19 = triton_helpers.maximum(tmp14, tmp18)
tmp20 = tmp4 - tmp19
tmp21 = 0.5
tmp22 = tmp20 * tmp21
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp8 - tmp19
tmp25 = tmp24 * tmp21
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp23 + tmp26
tmp28 = tmp13 - tmp19
tmp29 = tmp28 * tmp21
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp27 + tmp30
tmp32 = tmp18 - tmp19
tmp33 = tmp32 * tmp21
tmp34 = tl_math.exp(tmp33)
tmp35 = tmp31 + tmp34
tl.store(out_ptr0 + x0, tmp19, xmask)
tl.store(out_ptr1 + x0, tmp35, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_1(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
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp6 = tmp4 - tmp5
tmp7 = 0.5
tmp8 = tmp6 * tmp7
tmp9 = tl_math.exp(tmp8)
tmp11 = tmp9 / tmp10
tl.store(in_out_ptr0 + x2, tmp11, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, primals_3, 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, 1), torch.float32)
extern_kernels.addmm(primals_5, primals_6, reinterpret_tensor(
primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(buf1, (4, 4), (1, 4), 0),
out=buf2)
buf3 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf4 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_mul_0[grid(4)](primals_7, buf2, buf3,
buf4, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf5 = buf2
del buf2
triton_poi_fused__softmax_mul_1[grid(16)](buf5, primals_7, buf3,
buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf0, buf5, buf1, alpha=1, beta=1, out=buf6)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(buf0, (4, 4), (1, 4), 0),
out=buf7)
buf8 = buf4
del buf4
buf9 = buf3
del buf3
triton_poi_fused__softmax_mul_0[grid(4)](primals_8, buf7, buf8,
buf9, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf10 = buf7
del buf7
triton_poi_fused__softmax_mul_1[grid(16)](buf10, primals_8, buf8,
buf9, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf8
del buf9
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, buf10, buf0, alpha=1, beta=1, out=buf11)
return (buf6, buf11, primals_3, primals_6, primals_7, primals_8, buf0,
buf1, buf5, buf10)
class AttentionNew(nn.Module):
def __init__(self, opt):
super(AttentionNew, self).__init__()
self.lin_u = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.lin_v = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.opt = opt
def forward(self, input_0, input_1, input_2, input_3):
primals_1 = self.lin_u.weight
primals_2 = self.lin_u.bias
primals_3 = self.lin_v.weight
primals_5 = self.lin_v.bias
primals_4 = input_0
primals_6 = input_1
primals_7 = input_2
primals_8 = input_3
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0], output[1]
|
caojiangxia/BiGI
|
Attention
| false
| 15,003
|
[
"MIT"
] | 57
|
ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
https://github.com/caojiangxia/BiGI/tree/ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
SplitChannels
|
import torch
class SplitChannels(torch.nn.Module):
def __init__(self, split_location):
super(SplitChannels, self).__init__()
self.split_location = split_location
def forward(self, x):
a, b = x[:, :self.split_location], x[:, self.split_location:]
a, b = a.clone(), b.clone()
del x
return a, b
def inverse(self, x, y):
return torch.cat([x, y], dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'split_location': 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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tl.store(out_ptr0 + x0, tmp0, xmask)
def call(args):
arg0_1, = 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(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 0, 4, 4), (0, 16, 4, 1), torch.float32)
return buf0, buf1
class SplitChannelsNew(torch.nn.Module):
def __init__(self, split_location):
super(SplitChannelsNew, self).__init__()
self.split_location = split_location
def inverse(self, x, y):
return torch.cat([x, y], dim=1)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1]
|
cetmann/iunets
|
SplitChannels
| false
| 15,004
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
SoftTargetCrossEntropy
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed
class SoftTargetCrossEntropy(nn.Module):
def forward(self, x, target):
loss = torch.sum(-target * F.log_softmax(x, dim=-1), dim=-1)
return loss.mean()
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_mean_mul_neg_sum_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp1 = -tmp0
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 = tmp2 - tmp13
tmp15 = tmp1 * tmp14
tmp17 = -tmp16
tmp18 = tmp4 - tmp13
tmp19 = tmp17 * tmp18
tmp20 = tmp15 + tmp19
tmp22 = -tmp21
tmp23 = tmp7 - tmp13
tmp24 = tmp22 * tmp23
tmp25 = tmp20 + tmp24
tmp27 = -tmp26
tmp28 = tmp10 - tmp13
tmp29 = tmp27 * tmp28
tmp30 = tmp25 + tmp29
tmp31 = tl.broadcast_to(tmp30, [XBLOCK, RBLOCK])
tmp33 = tl.sum(tmp31, 1)[:, None]
tmp34 = 64.0
tmp35 = tmp33 / tmp34
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp35, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused__log_softmax_mean_mul_neg_sum_1[grid(1)](buf3,
arg0_1, buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf3,
class SoftTargetCrossEntropyNew(nn.Module):
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
ccjlovewsy/relabel_imagenet
|
SoftTargetCrossEntropy
| false
| 15,005
|
[
"Apache-2.0"
] | 344
|
6cd84dffe4ce8005395970b2938b3196d0958351
|
https://github.com/ccjlovewsy/relabel_imagenet/tree/6cd84dffe4ce8005395970b2938b3196d0958351
|
SmoothCrossEntropyLoss
|
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _WeightedLoss
class SmoothCrossEntropyLoss(_WeightedLoss):
def __init__(self, weight=None, reduction='mean', smoothing=0.0):
super().__init__(weight=weight, reduction=reduction)
self.smoothing = smoothing
self.weight = weight
self.reduction = reduction
@staticmethod
def _smooth_one_hot(targets: 'torch.Tensor', n_classes: 'int',
smoothing=0.0):
assert 0 <= smoothing < 1
with torch.no_grad():
targets = torch.empty(size=(targets.size(0), n_classes), device
=targets.device).fill_(smoothing / (n_classes - 1)).scatter_(
1, targets.data.unsqueeze(1), 1.0 - smoothing)
return targets
def forward(self, inputs, targets):
targets = SmoothCrossEntropyLoss._smooth_one_hot(targets, inputs.
size(-1), self.smoothing)
lsm = F.log_softmax(inputs, -1)
if self.weight is not None:
lsm = lsm * self.weight.unsqueeze(0)
loss = -(targets * lsm).sum(-1)
if self.reduction == 'sum':
loss = loss.sum()
elif self.reduction == 'mean':
loss = loss.mean()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.ones([4], dtype=torch.int64)]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch.nn.modules.loss import _WeightedLoss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_mean_mul_neg_scatter_sum_1(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 4
r2 = rindex
tmp0 = tl.load(in_ptr0 + r0, None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + 4 * r2, None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (1 + 4 * r2), None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + (2 + 4 * r2), None, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr1 + (3 + 4 * r2), None, eviction_policy='evict_last')
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp7 = tl_math.exp(tmp6)
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp12 = tl_math.exp(tmp11)
tmp13 = tmp10 + tmp12
tmp15 = tl_math.exp(tmp14)
tmp16 = tmp13 + tmp15
tmp17 = tl_math.log(tmp16)
tmp18 = tmp6 - tmp17
tmp19 = tmp5 * tmp18
tmp20 = tl.full([1, 1], 1, tl.int64)
tmp21 = tmp0 == tmp20
tmp22 = tl.where(tmp21, tmp3, tmp4)
tmp23 = tmp8 - tmp17
tmp24 = tmp22 * tmp23
tmp25 = tmp19 + tmp24
tmp26 = tl.full([1, 1], 2, tl.int64)
tmp27 = tmp0 == tmp26
tmp28 = tl.where(tmp27, tmp3, tmp4)
tmp29 = tmp11 - tmp17
tmp30 = tmp28 * tmp29
tmp31 = tmp25 + tmp30
tmp32 = tl.full([1, 1], 3, tl.int64)
tmp33 = tmp0 == tmp32
tmp34 = tl.where(tmp33, tmp3, tmp4)
tmp35 = tmp14 - tmp17
tmp36 = tmp34 * tmp35
tmp37 = tmp31 + tmp36
tmp38 = -tmp37
tmp39 = tl.broadcast_to(tmp38, [XBLOCK, RBLOCK])
tmp41 = tl.sum(tmp39, 1)[:, None]
tmp42 = 64.0
tmp43 = tmp41 / tmp42
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp43, 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,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused__log_softmax_mean_mul_neg_scatter_sum_1[grid(1)](buf3,
arg1_1, buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg1_1
del buf0
return buf3,
class SmoothCrossEntropyLossNew(_WeightedLoss):
def __init__(self, weight=None, reduction='mean', smoothing=0.0):
super().__init__(weight=weight, reduction=reduction)
self.smoothing = smoothing
self.weight = weight
self.reduction = reduction
@staticmethod
def _smooth_one_hot(targets: 'torch.Tensor', n_classes: 'int',
smoothing=0.0):
assert 0 <= smoothing < 1
with torch.no_grad():
targets = torch.empty(size=(targets.size(0), n_classes), device
=targets.device).fill_(smoothing / (n_classes - 1)).scatter_(
1, targets.data.unsqueeze(1), 1.0 - smoothing)
return targets
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
cclauss/archai
|
SmoothCrossEntropyLoss
| false
| 15,006
|
[
"MIT"
] | 344
|
a5fb8f937f7f1319e3204120803b2a045e9f768b
|
https://github.com/cclauss/archai/tree/a5fb8f937f7f1319e3204120803b2a045e9f768b
|
GAT
|
from _paritybench_helpers import _mock_config
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, opt):
super(Attention, self).__init__()
self.lin_u = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.lin_v = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.opt = opt
def forward(self, user, item, UV_adj, VU_adj):
user = self.lin_u(user)
item = self.lin_v(item)
query = user
key = item
value = torch.mm(query, key.transpose(0, 1))
value = UV_adj.to_dense() * value
value /= math.sqrt(self.opt['hidden_dim'])
value = F.softmax(value, dim=1)
learn_user = torch.matmul(value, key) + user
query = item
key = user
value = torch.mm(query, key.transpose(0, 1))
value = VU_adj.to_dense() * value
value /= math.sqrt(self.opt['hidden_dim'])
value = F.softmax(value, dim=1)
learn_item = torch.matmul(value, key) + item
return learn_user, learn_item
class GAT(nn.Module):
def __init__(self, opt):
super(GAT, self).__init__()
self.att = Attention(opt)
self.dropout = opt['dropout']
self.leakyrelu = nn.LeakyReLU(opt['leakey'])
def forward(self, ufea, vfea, UV_adj, VU_adj, adj=None):
learn_user = ufea
learn_item = vfea
learn_user = F.dropout(learn_user, self.dropout, training=self.training
)
learn_item = F.dropout(learn_item, self.dropout, training=self.training
)
learn_user, learn_item = self.att(learn_user, learn_item, UV_adj,
VU_adj)
return learn_user, learn_item
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4]),
torch.rand([4, 4])]
def get_init_inputs():
return [[], {'opt': _mock_config(hidden_dim=4, dropout=0.5, leakey=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_mul_0(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')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp7 = tmp5 * tmp6
tmp8 = tmp7 * tmp3
tmp9 = triton_helpers.maximum(tmp4, tmp8)
tmp12 = tmp10 * tmp11
tmp13 = tmp12 * tmp3
tmp14 = triton_helpers.maximum(tmp9, tmp13)
tmp17 = tmp15 * tmp16
tmp18 = tmp17 * tmp3
tmp19 = triton_helpers.maximum(tmp14, tmp18)
tmp20 = tmp4 - tmp19
tmp21 = 0.5
tmp22 = tmp20 * tmp21
tmp23 = tl_math.exp(tmp22)
tmp24 = tmp8 - tmp19
tmp25 = tmp24 * tmp21
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp23 + tmp26
tmp28 = tmp13 - tmp19
tmp29 = tmp28 * tmp21
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp27 + tmp30
tmp32 = tmp18 - tmp19
tmp33 = tmp32 * tmp21
tmp34 = tl_math.exp(tmp33)
tmp35 = tmp31 + tmp34
tl.store(out_ptr0 + x0, tmp19, xmask)
tl.store(out_ptr1 + x0, tmp35, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_1(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
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp6 = tmp4 - tmp5
tmp7 = 0.5
tmp8 = tmp6 * tmp7
tmp9 = tl_math.exp(tmp8)
tmp11 = tmp9 / tmp10
tl.store(in_out_ptr0 + x2, tmp11, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 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, 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.addmm(primals_4, primals_1, reinterpret_tensor(
primals_3, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf0)
del primals_3
del primals_4
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, primals_2, reinterpret_tensor(
primals_5, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_5
del primals_6
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(buf1, (4, 4), (1, 4), 0),
out=buf2)
buf3 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf4 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_mul_0[grid(4)](primals_7, buf2, buf3,
buf4, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf5 = buf2
del buf2
triton_poi_fused__softmax_mul_1[grid(16)](buf5, primals_7, buf3,
buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf0, buf5, buf1, alpha=1, beta=1, out=buf6)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(buf0, (4, 4), (1, 4), 0),
out=buf7)
buf8 = buf4
del buf4
buf9 = buf3
del buf3
triton_poi_fused__softmax_mul_0[grid(4)](primals_8, buf7, buf8,
buf9, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf10 = buf7
del buf7
triton_poi_fused__softmax_mul_1[grid(16)](buf10, primals_8, buf8,
buf9, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf8
del buf9
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, buf10, buf0, alpha=1, beta=1, out=buf11)
return (buf6, buf11, primals_1, primals_2, primals_7, primals_8, buf0,
buf1, buf5, buf10)
class Attention(nn.Module):
def __init__(self, opt):
super(Attention, self).__init__()
self.lin_u = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.lin_v = nn.Linear(opt['hidden_dim'], opt['hidden_dim'])
self.opt = opt
def forward(self, user, item, UV_adj, VU_adj):
user = self.lin_u(user)
item = self.lin_v(item)
query = user
key = item
value = torch.mm(query, key.transpose(0, 1))
value = UV_adj.to_dense() * value
value /= math.sqrt(self.opt['hidden_dim'])
value = F.softmax(value, dim=1)
learn_user = torch.matmul(value, key) + user
query = item
key = user
value = torch.mm(query, key.transpose(0, 1))
value = VU_adj.to_dense() * value
value /= math.sqrt(self.opt['hidden_dim'])
value = F.softmax(value, dim=1)
learn_item = torch.matmul(value, key) + item
return learn_user, learn_item
class GATNew(nn.Module):
def __init__(self, opt):
super(GATNew, self).__init__()
self.att = Attention(opt)
self.dropout = opt['dropout']
self.leakyrelu = nn.LeakyReLU(opt['leakey'])
def forward(self, input_0, input_1, input_2, input_3):
primals_1 = self.att.lin_u.weight
primals_4 = self.att.lin_u.bias
primals_2 = self.att.lin_v.weight
primals_6 = self.att.lin_v.bias
primals_3 = input_0
primals_5 = input_1
primals_7 = input_2
primals_8 = input_3
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0], output[1]
|
caojiangxia/BiGI
|
GAT
| false
| 15,007
|
[
"MIT"
] | 57
|
ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
https://github.com/caojiangxia/BiGI/tree/ed54c20523a5b3f295b90a9c08f7c54e8258d04a
|
LinfDistance
|
import torch
from torch import nn
import torch.autograd
class LinfDistance(nn.Module):
def forward(self, img1, img2):
return (img1 - img2).reshape(img1.shape[0], -1).abs().max(dim=1)[0]
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
from torch import 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_per_fused_abs_max_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, float('-inf'))
tmp7 = triton_helpers.max2(tmp6, 1)[:, None]
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_abs_max_0[grid(4)](arg0_1, arg1_1, buf0, 4, 64,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class LinfDistanceNew(nn.Module):
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
cassidylaidlaw/perceptual-advex
|
LinfDistance
| false
| 15,008
|
[
"MIT"
] | 45
|
d39136eb5b5e950442456ddade6b4f4fba3dd8f6
|
https://github.com/cassidylaidlaw/perceptual-advex/tree/d39136eb5b5e950442456ddade6b4f4fba3dd8f6
|
ImageNetNormalizer
|
import torch
from torch import nn
import torch.autograd
class ImageNetNormalizer(nn.Module):
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
super().__init__()
self.mean = mean
self.std = std
def forward(self, x):
mean = torch.tensor(self.mean, device=x.device)
std = torch.tensor(self.std, device=x.device)
return (x - mean[None, :, None, None]) / std[None, :, None, None]
def get_inputs():
return [torch.rand([4, 3, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
import torch.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_div_sub_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
x3 = xindex
x1 = xindex // 16 % 3
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = x1
tmp2 = tl.full([1], 1, tl.int64)
tmp3 = tmp1 < tmp2
tmp4 = tl.full([1], 2, tl.int64)
tmp5 = tmp1 < tmp4
tmp6 = 0.4560000002384186
tmp7 = 0.4059999883174896
tmp8 = tl.where(tmp5, tmp6, tmp7)
tmp9 = 0.48500001430511475
tmp10 = tl.where(tmp3, tmp9, tmp8)
tmp11 = tmp0 - tmp10
tmp12 = 0.2240000069141388
tmp13 = 0.22499999403953552
tmp14 = tl.where(tmp5, tmp12, tmp13)
tmp15 = 0.2290000021457672
tmp16 = tl.where(tmp3, tmp15, tmp14)
tmp17 = tmp11 / tmp16
tl.store(out_ptr0 + x3, tmp17, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 3, 4, 4), (48, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 3, 4, 4), (48, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_sub_0[grid(192)](arg0_1, buf0, 192, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ImageNetNormalizerNew(nn.Module):
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
super().__init__()
self.mean = mean
self.std = std
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
cassidylaidlaw/perceptual-advex
|
ImageNetNormalizer
| false
| 15,009
|
[
"MIT"
] | 45
|
d39136eb5b5e950442456ddade6b4f4fba3dd8f6
|
https://github.com/cassidylaidlaw/perceptual-advex/tree/d39136eb5b5e950442456ddade6b4f4fba3dd8f6
|
L2Distance
|
import torch
from torch import nn
import torch.autograd
class L2Distance(nn.Module):
def forward(self, img1, img2):
return (img1 - img2).reshape(img1.shape[0], -1).norm(dim=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import 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_per_fused_linalg_vector_norm_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = libdevice.sqrt(tmp7)
tl.debug_barrier()
tl.store(in_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,), (1,), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_linalg_vector_norm_0[grid(4)](buf1, arg0_1, arg1_1,
4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class L2DistanceNew(nn.Module):
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
cassidylaidlaw/perceptual-advex
|
L2Distance
| false
| 15,010
|
[
"MIT"
] | 45
|
d39136eb5b5e950442456ddade6b4f4fba3dd8f6
|
https://github.com/cassidylaidlaw/perceptual-advex/tree/d39136eb5b5e950442456ddade6b4f4fba3dd8f6
|
GaussianConv2d
|
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.data
from torch.nn.parameter import Parameter
class GaussianConv2d(nn.Module):
def __init__(self, in_channels, out_channels, ksize=5):
"""Applies 2-D Gaussian Blur.
Args:
in_channels: An integer indicates input channel dimension.
out_channels: An integer indicates output channel dimension.
ksize: An integer indicates Gaussian kernel size.
"""
super(GaussianConv2d, self).__init__()
weight = (np.arange(ksize, dtype=np.float32) - ksize // 2) ** 2
weight = np.sqrt(weight[None, :] + weight[:, None])
weight = np.reshape(weight, (1, 1, ksize, ksize)) / weight.sum()
self.weight = Parameter(torch.Tensor(weight).expand(out_channels, -
1, -1, -1))
self._in_channels = in_channels
self._out_channels = out_channels
def forward(self, x):
with torch.no_grad():
return F.conv2d(x, self.weight, groups=self._in_channels)
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
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
import numpy as np
import torch.nn as nn
import torch.utils.data
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 4 * x2 + 16384 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 3600
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 + 14400 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 3600 * y3), tmp0, xmask & ymask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 1, 5, 5), (25, 25, 5, 1))
assert_size_stride(arg1_1, (4, 4, 64, 64), (16384, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 64, 64), (16384, 1, 256, 4), torch
.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4096)](arg1_1, buf0, 16,
4096, XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del arg1_1
buf1 = extern_kernels.convolution(buf0, arg0_1, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf1, (4, 4, 60, 60), (14400, 1, 240, 4))
del arg0_1
del buf0
buf2 = empty_strided_cuda((4, 4, 60, 60), (14400, 3600, 60, 1),
torch.float32)
triton_poi_fused_convolution_1[grid(16, 3600)](buf1, buf2, 16, 3600,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del buf1
return buf2,
class GaussianConv2dNew(nn.Module):
def __init__(self, in_channels, out_channels, ksize=5):
"""Applies 2-D Gaussian Blur.
Args:
in_channels: An integer indicates input channel dimension.
out_channels: An integer indicates output channel dimension.
ksize: An integer indicates Gaussian kernel size.
"""
super(GaussianConv2dNew, self).__init__()
weight = (np.arange(ksize, dtype=np.float32) - ksize // 2) ** 2
weight = np.sqrt(weight[None, :] + weight[:, None])
weight = np.reshape(weight, (1, 1, ksize, ksize)) / weight.sum()
self.weight = Parameter(torch.Tensor(weight).expand(out_channels, -
1, -1, -1))
self._in_channels = in_channels
self._out_channels = out_channels
def forward(self, input_0):
arg0_1 = self.weight
arg1_1 = input_0
output = call([arg0_1, arg1_1])
return output[0]
|
cenkbircanoglu/SPML
|
GaussianConv2d
| false
| 15,011
|
[
"MIT"
] | 68
|
f09e4c30ecf2030d42ac70b2c35e7fdeee9bf468
|
https://github.com/cenkbircanoglu/SPML/tree/f09e4c30ecf2030d42ac70b2c35e7fdeee9bf468
|
ContrastiveLoss
|
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import *
from torch.distributions import *
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
class ContrastiveLoss(nn.Module):
"""
Contrastive loss
Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise
"""
def __init__(self, margin):
super(ContrastiveLoss, self).__init__()
self.margin = margin
self.eps = 1e-09
def forward(self, output1, output2, target, size_average=True):
distances = (output2 - output1).pow(2).sum(1)
losses = 0.5 * (target.float() * distances + (1 + -1 * target).
float() * F.relu(self.margin - (distances + self.eps).sqrt()).
pow(2))
return losses.mean() if size_average else losses.sum()
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 [[], {'margin': 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
from torch import nn
from torch.utils.data import *
from torch.distributions import *
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_pow_sub_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp4 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp10 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp14 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tl.store(out_ptr0 + x2, tmp18, xmask)
@triton.jit
def triton_per_fused_add_mean_mul_pow_relu_rsub_sqrt_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r2 = rindex
r0 = rindex % 64
tmp0 = tl.load(in_ptr0 + r2, None)
tmp1 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = -1.0
tmp4 = tmp0 * tmp3
tmp5 = 1.0
tmp6 = tmp4 + tmp5
tmp7 = 1e-09
tmp8 = tmp1 + tmp7
tmp9 = libdevice.sqrt(tmp8)
tmp10 = 4.0
tmp11 = tmp10 - tmp9
tmp12 = tl.full([1], 0, tl.int32)
tmp13 = triton_helpers.maximum(tmp12, tmp11)
tmp14 = tmp13 * tmp13
tmp15 = tmp6 * tmp14
tmp16 = tmp2 + tmp15
tmp17 = 0.5
tmp18 = tmp16 * tmp17
tmp19 = tl.broadcast_to(tmp18, [RBLOCK])
tmp21 = triton_helpers.promote_to_tensor(tl.sum(tmp19, 0))
tmp22 = 256.0
tmp23 = tmp21 / tmp22
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp23, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_pow_sub_sum_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((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_add_mean_mul_pow_relu_rsub_sqrt_1[grid(1)](buf2,
arg2_1, buf0, 1, 256, num_warps=2, num_stages=1)
del arg2_1
del buf0
return buf2,
class ContrastiveLossNew(nn.Module):
"""
Contrastive loss
Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise
"""
def __init__(self, margin):
super(ContrastiveLossNew, self).__init__()
self.margin = margin
self.eps = 1e-09
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]
|
cgsas/LOB
|
ContrastiveLoss
| false
| 15,012
|
[
"MIT"
] | 97
|
4175912194c2a066b2d7df038a376484b57ed76c
|
https://github.com/cgsas/LOB/tree/4175912194c2a066b2d7df038a376484b57ed76c
|
CombinedTargetMSELoss
|
import torch
import torch.nn as nn
class CombinedTargetMSELoss(nn.Module):
"""MSE loss for combined target.
CombinedTarget: The combination of classification target
(response map) and regression target (offset map).
Paper ref: Huang et al. The Devil is in the Details: Delving into
Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
Args:
use_target_weight (bool): Option to use weighted MSE loss.
Different joint types may have different target weights.
"""
def __init__(self, use_target_weight):
super().__init__()
self.criterion = nn.MSELoss(reduction='mean')
self.use_target_weight = use_target_weight
def forward(self, output, target, target_weight):
batch_size = output.size(0)
num_channels = output.size(1)
heatmaps_pred = output.reshape((batch_size, num_channels, -1)).split(
1, 1)
heatmaps_gt = target.reshape((batch_size, num_channels, -1)).split(1, 1
)
loss = 0.0
num_joints = num_channels // 3
for idx in range(num_joints):
heatmap_pred = heatmaps_pred[idx * 3].squeeze()
heatmap_gt = heatmaps_gt[idx * 3].squeeze()
offset_x_pred = heatmaps_pred[idx * 3 + 1].squeeze()
offset_x_gt = heatmaps_gt[idx * 3 + 1].squeeze()
offset_y_pred = heatmaps_pred[idx * 3 + 2].squeeze()
offset_y_gt = heatmaps_gt[idx * 3 + 2].squeeze()
if self.use_target_weight:
heatmap_pred = heatmap_pred.mul(target_weight[:, idx])
heatmap_gt = heatmap_gt.mul(target_weight[:, idx])
loss += 0.5 * self.criterion(heatmap_pred, heatmap_gt)
loss += 0.5 * self.criterion(heatmap_gt * offset_x_pred,
heatmap_gt * offset_x_gt)
loss += 0.5 * self.criterion(heatmap_gt * offset_y_pred,
heatmap_gt * offset_y_gt)
return loss / num_joints
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'use_target_weight': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mse_loss_mul_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp5 = tmp2 - tmp4
tmp6 = tmp5 * tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp11 = tmp4 * tmp10
tmp13 = tmp4 * tmp12
tmp14 = tmp11 - tmp13
tmp15 = tmp14 * tmp14
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.sum(tmp16, 1)[:, None]
tmp20 = tmp4 * tmp19
tmp22 = tmp4 * tmp21
tmp23 = tmp20 - tmp22
tmp24 = tmp23 * tmp23
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp27 = tl.sum(tmp25, 1)[:, None]
tmp28 = 4.0
tmp29 = tmp9 / tmp28
tmp30 = 0.5
tmp31 = tmp29 * tmp30
tmp32 = 0.0
tmp33 = tmp31 + tmp32
tmp34 = tmp18 / tmp28
tmp35 = tmp34 * tmp30
tmp36 = tmp33 + tmp35
tmp37 = tmp27 / tmp28
tmp38 = tmp37 * tmp30
tmp39 = tmp36 + tmp38
tmp40 = 1.0
tmp41 = tmp39 * tmp40
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp41, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf3 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mse_loss_mul_0[grid(1)](buf3, arg0_1,
arg2_1, arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
return buf3,
class CombinedTargetMSELossNew(nn.Module):
"""MSE loss for combined target.
CombinedTarget: The combination of classification target
(response map) and regression target (offset map).
Paper ref: Huang et al. The Devil is in the Details: Delving into
Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
Args:
use_target_weight (bool): Option to use weighted MSE loss.
Different joint types may have different target weights.
"""
def __init__(self, use_target_weight):
super().__init__()
self.criterion = nn.MSELoss(reduction='mean')
self.use_target_weight = use_target_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]
|
chaowentao/mmpose
|
CombinedTargetMSELoss
| false
| 15,013
|
[
"Apache-2.0"
] | 367
|
b528c60ef4fab56d35d1ed7e187023794639be26
|
https://github.com/chaowentao/mmpose/tree/b528c60ef4fab56d35d1ed7e187023794639be26
|
MoEHead
|
import math
import torch
from torch.nn import functional as F
from torch.autograd import Variable
from torch import nn
def softmax(x):
if x.dim() == 3:
return F.softmax(x.transpose(0, 2)).transpose(0, 2)
return F.softmax(x)
def gumbel_softmax(input, beta=0.5, tau=1.0):
noise = input.data.new(*input.size()).uniform_()
noise.add_(TINY).log_().neg_().add_(TINY).log_().neg_()
return softmax((input + beta * Variable(noise)) / tau)
def matmul(x, y):
if x.dim() == y.dim():
return x @ y
if x.dim() == y.dim() - 1:
return (x.unsqueeze(-2) @ y).squeeze(-2)
return (x @ y.unsqueeze(-1)).squeeze(-1)
def mask(targets, out, input_mask=None, return_mask=False):
if input_mask is None:
input_mask = targets != 1
out_mask = input_mask.unsqueeze(-1).expand_as(out)
if return_mask:
return targets[input_mask], out[out_mask].view(-1, out.size(-1)
), the_mask
return targets[input_mask], out[out_mask].view(-1, out.size(-1))
class Linear(nn.Linear):
def forward(self, x):
size = x.size()
return super().forward(x.contiguous().view(-1, size[-1])).view(*
size[:-1], -1)
class Attention(nn.Module):
def __init__(self, d_key, drop_ratio, causal, diag=False, window=-1,
noisy=False):
super().__init__()
self.scale = math.sqrt(d_key)
self.dropout = nn.Dropout(drop_ratio)
self.causal = causal
self.diag = diag
self.window = window
self.noisy = noisy
def forward(self, query, key, value=None, mask=None, feedback=None,
beta=0, tau=1, weights=None):
dot_products = matmul(query, key.transpose(1, 2))
if weights is not None:
dot_products = dot_products + weights
if query.dim() == 3 and self.causal and query.size(1) == key.size(1):
tri = key.data.new(key.size(1), key.size(1)).fill_(1).triu(1) * INF
dot_products.data.sub_(tri.unsqueeze(0))
if self.window > 0:
window_mask = key.data.new(key.size(1), key.size(1)).fill_(1)
window_mask = (window_mask.triu(self.window + 1) + window_mask.
tril(-self.window - 1)) * INF
dot_products.data.sub_(window_mask.unsqueeze(0))
if self.diag:
inds = torch.arange(0, key.size(1)).long().view(1, 1, -1)
if key.is_cuda:
inds = inds
dot_products.data.scatter_(1, inds.expand(dot_products.size(0),
1, inds.size(-1)), -INF)
if mask is not None:
if dot_products.dim() == 2:
dot_products.data -= (1 - mask) * INF
else:
dot_products.data -= (1 - mask[:, None, :]) * INF
if value is None:
return dot_products
logits = dot_products / self.scale
if not self.noisy:
probs = softmax(logits)
else:
probs = gumbel_softmax(logits, beta=beta, tau=tau)
if feedback is not None:
feedback.append(probs.contiguous())
return matmul(self.dropout(probs), value)
class MoEHead(nn.Module):
def __init__(self, d_key, d_value, n_heads, drop_ratio, causal=False,
diag=False, window=-1, noisy=False, use_wo=True):
super().__init__()
self.attention = Attention(d_key, drop_ratio, causal=causal, diag=
diag, window=window, noisy=noisy)
self.wq = Linear(d_key, d_key, bias=use_wo)
self.wk = Linear(d_key, d_key, bias=use_wo)
self.wv = Linear(d_value, d_value, bias=use_wo)
self.wo = Linear(d_value, d_key, bias=use_wo)
self.gate = Linear(d_value // n_heads, 1)
self.use_wo = use_wo
self.n_heads = n_heads
def forward(self, query, key, inputs, mask=None, feedback=None, weights
=None, beta=0, tau=1):
query, key, value = self.wq(query), self.wk(key), self.wv(inputs)
B, Tq, D = query.size()
_, Tk, _ = key.size()
N = self.n_heads
probs = []
query, key, value = (x.contiguous().view(B, -1, N, D // N).
transpose(2, 1).contiguous().view(B * N, -1, D // N) for x in (
query, key, value))
if mask is not None:
mask = mask[:, None, :].expand(B, N, Tk).contiguous().view(B *
N, -1)
probs = self.attention(query, key, None, mask, probs, beta, tau,
weights)
mix = matmul(self.attention.dropout(probs), value).contiguous().view(B,
N, -1, D // N).transpose(2, 1).contiguous()
mix = softmax(self.gate(mix))
probs = (probs.contiguous().view(B, N, Tq, Tk).transpose(2, 1) * mix
).sum(-2)
outputs = matmul(probs, inputs)
return self.wo(outputs)
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_key': 4, 'd_value': 4, 'n_heads': 4, 'drop_ratio': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
from torch.nn import functional as F
from torch.autograd import Variable
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, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, 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__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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_sum_4(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x4 = xindex // 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask)
tmp1 = tl.load(in_ptr1 + 4 * x4, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (1 + 4 * x4), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask)
tmp8 = tl.load(in_ptr1 + (2 + 4 * x4), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x4), 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 + x5, tmp14, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (1, 1), (1, 1))
assert_size_stride(primals_11, (1,), (1,))
assert_size_stride(primals_12, (4, 4), (4, 1))
assert_size_stride(primals_13, (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_4, (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_7, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf2)
del primals_8
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_3, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_6, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, 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 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(16, 4)](buf2, primals_9, buf6, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_9
buf7 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf5, reinterpret_tensor(buf6, (16, 4, 1), (4, 1,
0), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_1[grid(16, 4)](buf7, buf8, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf10 = reinterpret_tensor(buf7, (64, 1), (1, 1), 0)
del buf7
extern_kernels.addmm(primals_11, reinterpret_tensor(buf8, (64, 1),
(1, 0), 0), primals_10, alpha=1, beta=1, out=buf10)
del primals_11
buf11 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_2[grid(64)](buf10, buf11, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_3[grid(64)](buf11, buf12, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf13 = reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0)
del buf11
triton_poi_fused__softmax_mul_sum_4[grid(64)](buf5, buf12, buf13,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf14 = reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0)
del buf12
extern_kernels.bmm(buf13, primals_7, out=buf14)
buf15 = reinterpret_tensor(buf13, (16, 4), (4, 1), 0)
del buf13
extern_kernels.addmm(primals_13, reinterpret_tensor(buf14, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_12, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf15)
del primals_13
return reinterpret_tensor(buf15, (4, 4, 4), (16, 4, 1), 0
), primals_7, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_4, (16, 4), (4, 1), 0
), buf5, reinterpret_tensor(buf8, (64, 1), (1, 1), 0
), buf10, reinterpret_tensor(buf14, (16, 4), (4, 1), 0
), primals_12, primals_10, reinterpret_tensor(buf6, (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 softmax(x):
if x.dim() == 3:
return F.softmax(x.transpose(0, 2)).transpose(0, 2)
return F.softmax(x)
def gumbel_softmax(input, beta=0.5, tau=1.0):
noise = input.data.new(*input.size()).uniform_()
noise.add_(TINY).log_().neg_().add_(TINY).log_().neg_()
return softmax((input + beta * Variable(noise)) / tau)
def matmul(x, y):
if x.dim() == y.dim():
return x @ y
if x.dim() == y.dim() - 1:
return (x.unsqueeze(-2) @ y).squeeze(-2)
return (x @ y.unsqueeze(-1)).squeeze(-1)
def mask(targets, out, input_mask=None, return_mask=False):
if input_mask is None:
input_mask = targets != 1
out_mask = input_mask.unsqueeze(-1).expand_as(out)
if return_mask:
return targets[input_mask], out[out_mask].view(-1, out.size(-1)
), the_mask
return targets[input_mask], out[out_mask].view(-1, out.size(-1))
class Linear(nn.Linear):
def forward(self, x):
size = x.size()
return super().forward(x.contiguous().view(-1, size[-1])).view(*
size[:-1], -1)
class Attention(nn.Module):
def __init__(self, d_key, drop_ratio, causal, diag=False, window=-1,
noisy=False):
super().__init__()
self.scale = math.sqrt(d_key)
self.dropout = nn.Dropout(drop_ratio)
self.causal = causal
self.diag = diag
self.window = window
self.noisy = noisy
def forward(self, query, key, value=None, mask=None, feedback=None,
beta=0, tau=1, weights=None):
dot_products = matmul(query, key.transpose(1, 2))
if weights is not None:
dot_products = dot_products + weights
if query.dim() == 3 and self.causal and query.size(1) == key.size(1):
tri = key.data.new(key.size(1), key.size(1)).fill_(1).triu(1) * INF
dot_products.data.sub_(tri.unsqueeze(0))
if self.window > 0:
window_mask = key.data.new(key.size(1), key.size(1)).fill_(1)
window_mask = (window_mask.triu(self.window + 1) + window_mask.
tril(-self.window - 1)) * INF
dot_products.data.sub_(window_mask.unsqueeze(0))
if self.diag:
inds = torch.arange(0, key.size(1)).long().view(1, 1, -1)
if key.is_cuda:
inds = inds
dot_products.data.scatter_(1, inds.expand(dot_products.size(0),
1, inds.size(-1)), -INF)
if mask is not None:
if dot_products.dim() == 2:
dot_products.data -= (1 - mask) * INF
else:
dot_products.data -= (1 - mask[:, None, :]) * INF
if value is None:
return dot_products
logits = dot_products / self.scale
if not self.noisy:
probs = softmax(logits)
else:
probs = gumbel_softmax(logits, beta=beta, tau=tau)
if feedback is not None:
feedback.append(probs.contiguous())
return matmul(self.dropout(probs), value)
class MoEHeadNew(nn.Module):
def __init__(self, d_key, d_value, n_heads, drop_ratio, causal=False,
diag=False, window=-1, noisy=False, use_wo=True):
super().__init__()
self.attention = Attention(d_key, drop_ratio, causal=causal, diag=
diag, window=window, noisy=noisy)
self.wq = Linear(d_key, d_key, bias=use_wo)
self.wk = Linear(d_key, d_key, bias=use_wo)
self.wv = Linear(d_value, d_value, bias=use_wo)
self.wo = Linear(d_value, d_key, bias=use_wo)
self.gate = Linear(d_value // n_heads, 1)
self.use_wo = use_wo
self.n_heads = n_heads
def forward(self, input_0, input_1, input_2):
primals_2 = self.wq.weight
primals_3 = self.wq.bias
primals_5 = self.wk.weight
primals_6 = self.wk.bias
primals_8 = self.wv.weight
primals_9 = self.wv.bias
primals_12 = self.wo.weight
primals_13 = self.wo.bias
primals_10 = self.gate.weight
primals_11 = self.gate.bias
primals_1 = input_0
primals_4 = input_1
primals_7 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
cclauss/nonauto-nmt
|
MoEHead
| false
| 15,014
|
[
"BSD-3-Clause"
] | 262
|
efcbe4f2329b140ac3ce06abb6409457cebc8e49
|
https://github.com/cclauss/nonauto-nmt/tree/efcbe4f2329b140ac3ce06abb6409457cebc8e49
|
InvertibleChannelMixing1D
|
from torch.autograd import Function
import torch
from torch import nn
from warnings import warn
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalChannelMixing(nn.Module):
"""Base class for all orthogonal channel mixing layers.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(OrthogonalChannelMixing, self).__init__()
self.in_channels = in_channels
self.weight = nn.Parameter(torch.zeros((in_channels, in_channels)),
requires_grad=learnable)
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self.kwargs = kwargs
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel_matrix_transposed(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return torch.transpose(self.kernel_matrix, -1, -2)
class InvertibleChannelMixing1D(OrthogonalChannelMixing):
"""Orthogonal (and hence invertible) channel mixing layer for 1D data.
This layer linearly combines the input channels to each output channel.
Here, the number of output channels is the same as the number of input
channels, and the matrix specifying the connectivity between the channels
is orthogonal.
:param in_channels:
The number of input (and output) channels.
:param method:
The chosen method for parametrizing the orthogonal matrix which
determines the orthogonal channel mixing. Either ``"exp"``, ``"cayley"``
or ``"householder"``.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(InvertibleChannelMixing1D, self).__init__(in_channels=
in_channels, method=method, learnable=learnable, **kwargs)
self.kwargs = kwargs
@property
def kernel(self):
return self.kernel_matrix.view(self.in_channels, self.in_channels, 1)
def forward(self, x):
return nn.functional.conv1d(x, self.kernel)
def inverse(self, x):
return nn.functional.conv_transpose1d(x, self.kernel)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
from torch import nn
from warnings import warn
assert_size_stride = torch._C._dynamo.guards.assert_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_eye_sub_0(in_ptr0, 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
y0 = yindex
x1 = xindex
tmp6 = tl.load(in_ptr0 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tmp0 = y0
tmp1 = x1
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x1 + 4 * y0), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp10, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(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)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(4, 4)](primals_1, buf0, buf5, 4,
4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 1), 0)
del buf0
triton_poi_fused_convolution_1[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK
=4, YBLOCK=4, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1,
4, 4), (16, 4, 1), 0), buf8, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf9, (1, 4, 4), (16, 4, 1))
del buf8
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
buf11 = buf10
del buf10
return reinterpret_tensor(buf9, (4, 4), (4, 1), 0
), buf5, reinterpret_tensor(buf7, (4, 4, 1), (1, 4, 4), 0
), reinterpret_tensor(primals_2, (1, 4, 4), (16, 4, 1), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalChannelMixing(nn.Module):
"""Base class for all orthogonal channel mixing layers.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(OrthogonalChannelMixing, self).__init__()
self.in_channels = in_channels
self.weight = nn.Parameter(torch.zeros((in_channels, in_channels)),
requires_grad=learnable)
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self.kwargs = kwargs
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel_matrix_transposed(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return torch.transpose(self.kernel_matrix, -1, -2)
class InvertibleChannelMixing1DNew(OrthogonalChannelMixing):
"""Orthogonal (and hence invertible) channel mixing layer for 1D data.
This layer linearly combines the input channels to each output channel.
Here, the number of output channels is the same as the number of input
channels, and the matrix specifying the connectivity between the channels
is orthogonal.
:param in_channels:
The number of input (and output) channels.
:param method:
The chosen method for parametrizing the orthogonal matrix which
determines the orthogonal channel mixing. Either ``"exp"``, ``"cayley"``
or ``"householder"``.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(InvertibleChannelMixing1DNew, self).__init__(in_channels=
in_channels, method=method, learnable=learnable, **kwargs)
self.kwargs = kwargs
@property
def kernel(self):
return self.kernel_matrix.view(self.in_channels, self.in_channels, 1)
def inverse(self, x):
return nn.functional.conv_transpose1d(x, self.kernel)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleChannelMixing1D
| false
| 15,015
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
InvertibleChannelMixing3D
|
from torch.autograd import Function
import torch
from torch import nn
from warnings import warn
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalChannelMixing(nn.Module):
"""Base class for all orthogonal channel mixing layers.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(OrthogonalChannelMixing, self).__init__()
self.in_channels = in_channels
self.weight = nn.Parameter(torch.zeros((in_channels, in_channels)),
requires_grad=learnable)
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self.kwargs = kwargs
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel_matrix_transposed(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return torch.transpose(self.kernel_matrix, -1, -2)
class InvertibleChannelMixing3D(OrthogonalChannelMixing):
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(InvertibleChannelMixing3D, self).__init__(in_channels=
in_channels, method=method, learnable=learnable, **kwargs)
self.kwargs = kwargs
@property
def kernel(self):
return self.kernel_matrix.view(self.in_channels, self.in_channels,
1, 1, 1)
def forward(self, x):
return nn.functional.conv3d(x, self.kernel)
def inverse(self, x):
return nn.functional.conv_transpose3d(x, self.kernel)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
from torch import nn
from warnings import warn
assert_size_stride = torch._C._dynamo.guards.assert_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_eye_sub_0(in_ptr0, 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
y0 = yindex
x1 = xindex
tmp6 = tl.load(in_ptr0 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tmp0 = y0
tmp1 = x1
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x1 + 4 * y0), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp10, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(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)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 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)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(4, 4)](primals_1, buf0, buf5, 4,
4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = reinterpret_tensor(buf0, (4, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0)
del buf0
triton_poi_fused_convolution_1[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK
=4, YBLOCK=4, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), buf8, stride=(1, 1, 1),
padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf9, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
del buf8
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
buf11 = buf10
del buf10
return reinterpret_tensor(buf9, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf5, reinterpret_tensor(buf7, (4, 4, 1, 1, 1), (1, 4, 4, 4, 4), 0
), reinterpret_tensor(primals_2, (1, 4, 4, 4, 4), (256, 64, 16, 4,
1), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalChannelMixing(nn.Module):
"""Base class for all orthogonal channel mixing layers.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(OrthogonalChannelMixing, self).__init__()
self.in_channels = in_channels
self.weight = nn.Parameter(torch.zeros((in_channels, in_channels)),
requires_grad=learnable)
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self.kwargs = kwargs
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel_matrix_transposed(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return torch.transpose(self.kernel_matrix, -1, -2)
class InvertibleChannelMixing3DNew(OrthogonalChannelMixing):
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(InvertibleChannelMixing3DNew, self).__init__(in_channels=
in_channels, method=method, learnable=learnable, **kwargs)
self.kwargs = kwargs
@property
def kernel(self):
return self.kernel_matrix.view(self.in_channels, self.in_channels,
1, 1, 1)
def inverse(self, x):
return nn.functional.conv_transpose3d(x, self.kernel)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleChannelMixing3D
| false
| 15,016
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
InvertibleChannelMixing2D
|
from torch.autograd import Function
import torch
from torch import nn
from warnings import warn
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalChannelMixing(nn.Module):
"""Base class for all orthogonal channel mixing layers.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(OrthogonalChannelMixing, self).__init__()
self.in_channels = in_channels
self.weight = nn.Parameter(torch.zeros((in_channels, in_channels)),
requires_grad=learnable)
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self.kwargs = kwargs
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel_matrix_transposed(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return torch.transpose(self.kernel_matrix, -1, -2)
class InvertibleChannelMixing2D(OrthogonalChannelMixing):
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(InvertibleChannelMixing2D, self).__init__(in_channels=
in_channels, method=method, learnable=learnable, **kwargs)
self.kwargs = kwargs
@property
def kernel(self):
return self.kernel_matrix.view(self.in_channels, self.in_channels, 1, 1
)
def forward(self, x):
return nn.functional.conv2d(x, self.kernel)
def inverse(self, x):
return nn.functional.conv_transpose2d(x, self.kernel)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
from torch import nn
from warnings import warn
assert_size_stride = torch._C._dynamo.guards.assert_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_eye_sub_0(in_ptr0, 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
y0 = yindex
x1 = xindex
tmp6 = tl.load(in_ptr0 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tmp0 = y0
tmp1 = x1
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x1 + 4 * y0), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp10, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(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)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 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)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(4, 4)](primals_1, buf0, buf5, 4,
4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
triton_poi_fused_convolution_1[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK
=4, YBLOCK=4, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(primals_2, buf8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 4, 4), (64, 16, 4, 1))
del buf8
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
buf11 = buf10
del buf10
return buf9, primals_2, buf5, reinterpret_tensor(buf7, (4, 4, 1, 1), (1,
4, 4, 4), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalChannelMixing(nn.Module):
"""Base class for all orthogonal channel mixing layers.
"""
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(OrthogonalChannelMixing, self).__init__()
self.in_channels = in_channels
self.weight = nn.Parameter(torch.zeros((in_channels, in_channels)),
requires_grad=learnable)
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self.kwargs = kwargs
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel_matrix_transposed(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return torch.transpose(self.kernel_matrix, -1, -2)
class InvertibleChannelMixing2DNew(OrthogonalChannelMixing):
def __init__(self, in_channels: 'int', method: 'str'='cayley',
learnable: 'bool'=True, **kwargs):
super(InvertibleChannelMixing2DNew, self).__init__(in_channels=
in_channels, method=method, learnable=learnable, **kwargs)
self.kwargs = kwargs
@property
def kernel(self):
return self.kernel_matrix.view(self.in_channels, self.in_channels, 1, 1
)
def inverse(self, x):
return nn.functional.conv_transpose2d(x, self.kernel)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleChannelMixing2D
| false
| 15,017
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
homo_Gauss_mloglike
|
import torch
import numpy as np
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
import torch.nn as nn
import torch.optim
from torch.distributions import Normal
class homo_Gauss_mloglike(nn.Module):
def __init__(self, Ndims=1, sig=None):
super(homo_Gauss_mloglike, self).__init__()
if sig is None:
self.log_std = nn.Parameter(torch.zeros(Ndims))
else:
self.log_std = nn.Parameter(torch.ones(Ndims) * np.log(sig),
requires_grad=False)
def forward(self, mu, y, model_std=None):
sig = self.log_std.exp().clamp(min=0.0001)
if model_std is not None:
sig = (sig ** 2 + model_std ** 2) ** 0.5
dist = Normal(mu, sig)
return -dist.log_prob(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
from torch._inductor.runtime.triton_helpers import math as tl_math
import numpy as np
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
import torch.nn as nn
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_log_mul_neg_pow_sub_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp5 = tl.load(in_ptr2 + 0)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK])
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = -tmp3
tmp7 = tl_math.exp(tmp6)
tmp8 = 0.0001
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tmp9 * tmp9
tmp11 = 2.0
tmp12 = tmp10 * tmp11
tmp13 = tmp4 / tmp12
tmp14 = tl_math.log(tmp9)
tmp15 = tmp13 - tmp14
tmp16 = 0.9189385332046727
tmp17 = tmp15 - tmp16
tmp18 = -tmp17
tmp19 = tmp13 / tmp12
tl.store(out_ptr0 + x0, tmp18, xmask)
tl.store(out_ptr1 + x0, tmp19, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (1,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (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)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_log_mul_neg_pow_sub_0[grid(256)](primals_3,
primals_2, primals_1, buf0, buf1, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_2
del primals_3
return buf0, primals_1, buf1
class homo_Gauss_mloglikeNew(nn.Module):
def __init__(self, Ndims=1, sig=None):
super(homo_Gauss_mloglikeNew, self).__init__()
if sig is None:
self.log_std = nn.Parameter(torch.zeros(Ndims))
else:
self.log_std = nn.Parameter(torch.ones(Ndims) * np.log(sig),
requires_grad=False)
def forward(self, input_0, input_1):
primals_1 = self.log_std
primals_2 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
chelsealuisa/DUN
|
homo_Gauss_mloglike
| false
| 15,018
|
[
"MIT"
] | 58
|
1ccd9bc49b91b13089350f003a25bdb11003d843
|
https://github.com/chelsealuisa/DUN/tree/1ccd9bc49b91b13089350f003a25bdb11003d843
|
ContrastiveLoss
|
import torch
import torchvision.transforms.functional as F
import torch.nn.functional as F
import torch.nn as nn
class ContrastiveLoss(nn.Module):
"""
Contrastive loss function.
Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
"""
def __init__(self, margin=2.0):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, output1, output2, label):
euclidean_distance = F.pairwise_distance(output1, output2)
loss_contrastive = torch.mean(label * torch.pow(euclidean_distance,
2) + (1 - label) * torch.pow(torch.clamp(self.margin -
euclidean_distance, min=0.0), 2))
return loss_contrastive
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_norm_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = 1e-06
tmp4 = tmp2 + tmp3
tmp5 = tmp4 * tmp4
tmp8 = tmp6 - tmp7
tmp9 = tmp8 + tmp3
tmp10 = tmp9 * tmp9
tmp11 = tmp5 + tmp10
tmp14 = tmp12 - tmp13
tmp15 = tmp14 + tmp3
tmp16 = tmp15 * tmp15
tmp17 = tmp11 + tmp16
tmp20 = tmp18 - tmp19
tmp21 = tmp20 + tmp3
tmp22 = tmp21 * tmp21
tmp23 = tmp17 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tl.store(out_ptr0 + x0, tmp24, xmask)
@triton.jit
def triton_per_fused_add_clamp_mean_mul_pow_rsub_1(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r2 = rindex
r0 = rindex % 64
tmp0 = tl.load(in_ptr0 + r2, None)
tmp1 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp3 = tmp0 * tmp2
tmp4 = 1.0
tmp5 = tmp4 - tmp0
tmp6 = 2.0
tmp7 = tmp6 - tmp1
tmp8 = 0.0
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tmp9 * tmp9
tmp11 = tmp5 * tmp10
tmp12 = tmp3 + tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 256.0
tmp17 = tmp15 / tmp16
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp17, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_norm_sub_0[grid(64)](arg1_1, arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_add_clamp_mean_mul_pow_rsub_1[grid(1)](buf2,
arg2_1, buf0, 1, 256, num_warps=2, num_stages=1)
del arg2_1
del buf0
return buf2,
class ContrastiveLossNew(nn.Module):
"""
Contrastive loss function.
Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
"""
def __init__(self, margin=2.0):
super(ContrastiveLossNew, self).__init__()
self.margin = margin
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]
|
chenyanghungry/person-reid-lib
|
ContrastiveLoss
| false
| 15,019
|
[
"MIT"
] | 81
|
783e66c9bfedf582e2cf935b9f5be960b543ac3c
|
https://github.com/chenyanghungry/person-reid-lib/tree/783e66c9bfedf582e2cf935b9f5be960b543ac3c
|
MLP
|
import torch
from torch import nn
import torch.utils.data
class MLP(nn.Module):
def __init__(self, input_size, output_size, hidden_size=None, dropout=0.1):
super().__init__()
if hidden_size is None:
hidden_size = input_size * 4
self.w_1 = nn.Linear(input_size * 2, hidden_size)
self.w_2 = nn.Linear(hidden_size, output_size)
self.dropout = nn.Dropout(dropout)
def forward(self, x1, x2):
x = torch.cat([x1, x2], -1)
return self.w_2(self.dropout(torch.nn.functional.relu(self.w_1(x))))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 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._inductor.runtime import triton_helpers
from torch import nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (16, 8), (8, 1))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (4, 16), (16, 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=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 8), (8, 1), 0),
reinterpret_tensor(primals_3, (8, 16), (1, 8), 0), out=buf1)
del primals_3
buf2 = reinterpret_tensor(buf1, (4, 4, 4, 16), (256, 64, 16, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 4, 16), (256, 64, 16, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(1024)](buf2,
primals_4, buf4, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf2, (64, 16),
(16, 1), 0), reinterpret_tensor(primals_5, (16, 4), (1, 16), 0),
alpha=1, beta=1, out=buf3)
del primals_6
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 8), (8, 1), 0), reinterpret_tensor(
buf2, (64, 16), (16, 1), 0), primals_5, buf4
class MLPNew(nn.Module):
def __init__(self, input_size, output_size, hidden_size=None, dropout=0.1):
super().__init__()
if hidden_size is None:
hidden_size = input_size * 4
self.w_1 = nn.Linear(input_size * 2, hidden_size)
self.w_2 = nn.Linear(hidden_size, output_size)
self.dropout = nn.Dropout(dropout)
def forward(self, input_0, input_1):
primals_3 = self.w_1.weight
primals_4 = self.w_1.bias
primals_5 = self.w_2.weight
primals_6 = self.w_2.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]
|
chenyangh/tensor2struct-public
|
MLP
| false
| 15,020
|
[
"MIT"
] | 69
|
d3257cba6d76d3c658a58a78f687d986bdc755cf
|
https://github.com/chenyangh/tensor2struct-public/tree/d3257cba6d76d3c658a58a78f687d986bdc755cf
|
InvertibleDownsampling2D
|
from torch.autograd import Function
import torch
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_2_t
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleDownsampling2D(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_2_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_pair(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels * channel_multiplier
super(InvertibleDownsampling2D, self).__init__(*args,
low_channel_number=self.in_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def forward(self, x):
return F.conv2d(x, self.kernel, stride=self.stride, groups=self.
low_channel_number)
def inverse(self, x):
return F.conv_transpose2d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_2_t
from torch.nn.modules.utils import _pair
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_eye_sub_0(in_ptr0, out_ptr0, out_ptr1, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
y0 = yindex % 4
x2 = xindex
y3 = yindex
y1 = yindex // 4
tmp6 = tl.load(in_ptr0 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp0 = y0
tmp1 = x2
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x2 + 4 * y3), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x2 + 4 * y3), tmp10, xmask & ymask)
@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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(16, 4)](primals_1, buf0, buf5,
16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = buf0
del buf0
triton_poi_fused_clone_1[grid(16, 4)](buf7, buf8, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(primals_2, reinterpret_tensor(
buf8, (16, 1, 2, 2), (4, 0, 2, 1), 0), stride=(2, 2), padding=(
0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf9, (4, 16, 2, 2), (64, 4, 2, 1))
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
del buf7
buf11 = buf10
del buf10
return buf9, primals_2, buf5, reinterpret_tensor(buf8, (16, 1, 2, 2), (
4, 4, 2, 1), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleDownsampling2DNew(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_2_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_pair(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels * channel_multiplier
super(InvertibleDownsampling2DNew, self).__init__(*args,
low_channel_number=self.in_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def inverse(self, x):
return F.conv_transpose2d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleDownsampling2D
| false
| 15,021
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
EncoderLayer
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch.nn import functional as F
from torch.autograd import Variable
from torch import nn
def softmax(x):
if x.dim() == 3:
return F.softmax(x.transpose(0, 2)).transpose(0, 2)
return F.softmax(x)
def gumbel_softmax(input, beta=0.5, tau=1.0):
noise = input.data.new(*input.size()).uniform_()
noise.add_(TINY).log_().neg_().add_(TINY).log_().neg_()
return softmax((input + beta * Variable(noise)) / tau)
def matmul(x, y):
if x.dim() == y.dim():
return x @ y
if x.dim() == y.dim() - 1:
return (x.unsqueeze(-2) @ y).squeeze(-2)
return (x @ y.unsqueeze(-1)).squeeze(-1)
def mask(targets, out, input_mask=None, return_mask=False):
if input_mask is None:
input_mask = targets != 1
out_mask = input_mask.unsqueeze(-1).expand_as(out)
if return_mask:
return targets[input_mask], out[out_mask].view(-1, out.size(-1)
), the_mask
return targets[input_mask], out[out_mask].view(-1, out.size(-1))
class Linear(nn.Linear):
def forward(self, x):
size = x.size()
return super().forward(x.contiguous().view(-1, size[-1])).view(*
size[:-1], -1)
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-06):
super().__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.gamma * (x - mean) / (std + self.eps) + self.beta
class ResidualBlock(nn.Module):
def __init__(self, layer, d_model, drop_ratio, pos=0):
super().__init__()
self.layer = layer
self.dropout = nn.Dropout(drop_ratio)
self.layernorm = LayerNorm(d_model)
self.pos = pos
def forward(self, *x):
return self.layernorm(x[self.pos] + self.dropout(self.layer(*x)))
class Attention(nn.Module):
def __init__(self, d_key, drop_ratio, causal, diag=False, window=-1,
noisy=False):
super().__init__()
self.scale = math.sqrt(d_key)
self.dropout = nn.Dropout(drop_ratio)
self.causal = causal
self.diag = diag
self.window = window
self.noisy = noisy
def forward(self, query, key, value=None, mask=None, feedback=None,
beta=0, tau=1, weights=None):
dot_products = matmul(query, key.transpose(1, 2))
if weights is not None:
dot_products = dot_products + weights
if query.dim() == 3 and self.causal and query.size(1) == key.size(1):
tri = key.data.new(key.size(1), key.size(1)).fill_(1).triu(1) * INF
dot_products.data.sub_(tri.unsqueeze(0))
if self.window > 0:
window_mask = key.data.new(key.size(1), key.size(1)).fill_(1)
window_mask = (window_mask.triu(self.window + 1) + window_mask.
tril(-self.window - 1)) * INF
dot_products.data.sub_(window_mask.unsqueeze(0))
if self.diag:
inds = torch.arange(0, key.size(1)).long().view(1, 1, -1)
if key.is_cuda:
inds = inds
dot_products.data.scatter_(1, inds.expand(dot_products.size(0),
1, inds.size(-1)), -INF)
if mask is not None:
if dot_products.dim() == 2:
dot_products.data -= (1 - mask) * INF
else:
dot_products.data -= (1 - mask[:, None, :]) * INF
if value is None:
return dot_products
logits = dot_products / self.scale
if not self.noisy:
probs = softmax(logits)
else:
probs = gumbel_softmax(logits, beta=beta, tau=tau)
if feedback is not None:
feedback.append(probs.contiguous())
return matmul(self.dropout(probs), value)
class MultiHead2(nn.Module):
def __init__(self, d_key, d_value, n_heads, drop_ratio, causal=False,
diag=False, window=-1, noisy=False, use_wo=True):
super().__init__()
self.attention = Attention(d_key, drop_ratio, causal=causal, diag=
diag, window=window, noisy=noisy)
self.wq = Linear(d_key, d_key, bias=use_wo)
self.wk = Linear(d_key, d_key, bias=use_wo)
self.wv = Linear(d_value, d_value, bias=use_wo)
if use_wo:
self.wo = Linear(d_value, d_key, bias=use_wo)
self.use_wo = use_wo
self.n_heads = n_heads
def forward(self, query, key, value, mask=None, feedback=None, weights=
None, beta=0, tau=1):
query, key, value = self.wq(query), self.wk(key), self.wv(value)
B, Tq, D = query.size()
_, Tk, _ = key.size()
N = self.n_heads
probs = []
query, key, value = (x.contiguous().view(B, -1, N, D // N).
transpose(2, 1).contiguous().view(B * N, -1, D // N) for x in (
query, key, value))
if mask is not None:
mask = mask[:, None, :].expand(B, N, Tk).contiguous().view(B *
N, -1)
outputs = self.attention(query, key, value, mask, probs, beta, tau,
weights)
outputs = outputs.contiguous().view(B, N, -1, D // N).transpose(2, 1
).contiguous().view(B, -1, D)
if feedback is not None:
feedback.append(probs[0].view(B, N, Tq, Tk))
if self.use_wo:
return self.wo(outputs)
return outputs
class FeedForward(nn.Module):
def __init__(self, d_model, d_hidden):
super().__init__()
self.linear1 = Linear(d_model, d_hidden)
self.linear2 = Linear(d_hidden, d_model)
def forward(self, x):
return self.linear2(F.relu(self.linear1(x)))
class EncoderLayer(nn.Module):
def __init__(self, args):
super().__init__()
self.selfattn = ResidualBlock(MultiHead2(args.d_model, args.d_model,
args.n_heads, args.drop_ratio, use_wo=args.use_wo), args.
d_model, args.drop_ratio)
self.feedforward = ResidualBlock(FeedForward(args.d_model, args.
d_hidden), args.d_model, args.drop_ratio)
def forward(self, x, mask=None):
return self.feedforward(self.selfattn(x, x, x, mask))
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'args': _mock_config(d_model=4, n_heads=4, drop_ratio=0.5,
use_wo=4, d_hidden=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
from torch.nn import functional as F
from torch.autograd import Variable
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, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_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 = 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 + x2, tmp15, xmask)
@triton.jit
def triton_poi_fused__softmax_2(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
tmp0 = tl.load(in_ptr0 + (y1 + 4 * x2 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (4 * x2 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x2 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x2 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x2 + 16 * y0), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + (y0 + 16 * x2 + 64 * y1), tmp8, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_add_mean_std_4(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = 3.0
tmp29 = tmp27 / tmp28
tl.store(in_out_ptr0 + x0, tmp29, xmask)
tl.store(out_ptr0 + x0, tmp16, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_5(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x2, xmask)
tmp4 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 - tmp4
tmp6 = tmp0 * tmp5
tmp8 = libdevice.sqrt(tmp7)
tmp9 = 1e-06
tmp10 = tmp8 + tmp9
tmp11 = tmp6 / tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_6(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_7(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_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_add_div_mean_mul_std_sub_8(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 4.0
tmp10 = tmp8 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp0 * tmp11
tmp13 = tmp2 - tmp10
tmp14 = tmp13 * tmp13
tmp15 = tmp3 - tmp10
tmp16 = tmp15 * tmp15
tmp17 = tmp14 + tmp16
tmp18 = tmp5 - tmp10
tmp19 = tmp18 * tmp18
tmp20 = tmp17 + tmp19
tmp21 = tmp7 - tmp10
tmp22 = tmp21 * tmp21
tmp23 = tmp20 + tmp22
tmp24 = 3.0
tmp25 = tmp23 / tmp24
tmp26 = libdevice.sqrt(tmp25)
tmp27 = 1e-06
tmp28 = tmp26 + tmp27
tmp29 = tmp12 / tmp28
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x2, tmp31, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (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,), (1,))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4, 4), (4, 1))
assert_size_stride(primals_13, (4,), (1,))
assert_size_stride(primals_14, (4, 4), (4, 1))
assert_size_stride(primals_15, (4,), (1,))
assert_size_stride(primals_16, (4,), (1,))
assert_size_stride(primals_17, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_3, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf0
triton_poi_fused_clone_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 16), (1, 4, 16), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (4, 4, 16), (64, 16, 1), 0)
del buf5
triton_poi_fused__softmax_2[grid(64, 4)](buf6, buf7, 64, 4, XBLOCK=
4, YBLOCK=32, 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(16, 4)](buf2, primals_7, buf8, 16, 4,
XBLOCK=2, YBLOCK=16, 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(reinterpret_tensor(buf7, (16, 4, 4), (1, 16, 64),
0), 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_9, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_9
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf13 = buf12
del buf12
buf14 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_mean_std_4[grid(16)](buf13, primals_1, buf11,
buf14, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_5[grid(64)](primals_10,
primals_1, buf11, buf14, buf13, primals_11, buf15, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del buf13
del buf14
del primals_11
buf16 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf15, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_12, (4, 4), (1, 4), 0), out=buf16)
buf17 = reinterpret_tensor(buf16, (4, 4, 4), (16, 4, 1), 0)
del buf16
buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_6[grid(64)](buf17,
primals_13, buf21, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_13
buf18 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf17, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_14, (4, 4), (1, 4), 0), out=buf18)
buf19 = reinterpret_tensor(buf18, (4, 4, 4), (16, 4, 1), 0)
del buf18
triton_poi_fused_add_7[grid(64)](buf19, buf15, primals_15, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_15
buf20 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_8[grid(64)](primals_16,
buf19, primals_17, buf20, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_17
return buf20, primals_1, primals_10, primals_16, buf7, reinterpret_tensor(
buf10, (16, 4), (4, 1), 0), buf11, reinterpret_tensor(buf15, (16, 4
), (4, 1), 0), reinterpret_tensor(buf17, (16, 4), (4, 1), 0
), buf19, primals_14, buf21, primals_12, 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 softmax(x):
if x.dim() == 3:
return F.softmax(x.transpose(0, 2)).transpose(0, 2)
return F.softmax(x)
def gumbel_softmax(input, beta=0.5, tau=1.0):
noise = input.data.new(*input.size()).uniform_()
noise.add_(TINY).log_().neg_().add_(TINY).log_().neg_()
return softmax((input + beta * Variable(noise)) / tau)
def matmul(x, y):
if x.dim() == y.dim():
return x @ y
if x.dim() == y.dim() - 1:
return (x.unsqueeze(-2) @ y).squeeze(-2)
return (x @ y.unsqueeze(-1)).squeeze(-1)
def mask(targets, out, input_mask=None, return_mask=False):
if input_mask is None:
input_mask = targets != 1
out_mask = input_mask.unsqueeze(-1).expand_as(out)
if return_mask:
return targets[input_mask], out[out_mask].view(-1, out.size(-1)
), the_mask
return targets[input_mask], out[out_mask].view(-1, out.size(-1))
class Linear(nn.Linear):
def forward(self, x):
size = x.size()
return super().forward(x.contiguous().view(-1, size[-1])).view(*
size[:-1], -1)
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-06):
super().__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.gamma * (x - mean) / (std + self.eps) + self.beta
class ResidualBlock(nn.Module):
def __init__(self, layer, d_model, drop_ratio, pos=0):
super().__init__()
self.layer = layer
self.dropout = nn.Dropout(drop_ratio)
self.layernorm = LayerNorm(d_model)
self.pos = pos
def forward(self, *x):
return self.layernorm(x[self.pos] + self.dropout(self.layer(*x)))
class Attention(nn.Module):
def __init__(self, d_key, drop_ratio, causal, diag=False, window=-1,
noisy=False):
super().__init__()
self.scale = math.sqrt(d_key)
self.dropout = nn.Dropout(drop_ratio)
self.causal = causal
self.diag = diag
self.window = window
self.noisy = noisy
def forward(self, query, key, value=None, mask=None, feedback=None,
beta=0, tau=1, weights=None):
dot_products = matmul(query, key.transpose(1, 2))
if weights is not None:
dot_products = dot_products + weights
if query.dim() == 3 and self.causal and query.size(1) == key.size(1):
tri = key.data.new(key.size(1), key.size(1)).fill_(1).triu(1) * INF
dot_products.data.sub_(tri.unsqueeze(0))
if self.window > 0:
window_mask = key.data.new(key.size(1), key.size(1)).fill_(1)
window_mask = (window_mask.triu(self.window + 1) + window_mask.
tril(-self.window - 1)) * INF
dot_products.data.sub_(window_mask.unsqueeze(0))
if self.diag:
inds = torch.arange(0, key.size(1)).long().view(1, 1, -1)
if key.is_cuda:
inds = inds
dot_products.data.scatter_(1, inds.expand(dot_products.size(0),
1, inds.size(-1)), -INF)
if mask is not None:
if dot_products.dim() == 2:
dot_products.data -= (1 - mask) * INF
else:
dot_products.data -= (1 - mask[:, None, :]) * INF
if value is None:
return dot_products
logits = dot_products / self.scale
if not self.noisy:
probs = softmax(logits)
else:
probs = gumbel_softmax(logits, beta=beta, tau=tau)
if feedback is not None:
feedback.append(probs.contiguous())
return matmul(self.dropout(probs), value)
class MultiHead2(nn.Module):
def __init__(self, d_key, d_value, n_heads, drop_ratio, causal=False,
diag=False, window=-1, noisy=False, use_wo=True):
super().__init__()
self.attention = Attention(d_key, drop_ratio, causal=causal, diag=
diag, window=window, noisy=noisy)
self.wq = Linear(d_key, d_key, bias=use_wo)
self.wk = Linear(d_key, d_key, bias=use_wo)
self.wv = Linear(d_value, d_value, bias=use_wo)
if use_wo:
self.wo = Linear(d_value, d_key, bias=use_wo)
self.use_wo = use_wo
self.n_heads = n_heads
def forward(self, query, key, value, mask=None, feedback=None, weights=
None, beta=0, tau=1):
query, key, value = self.wq(query), self.wk(key), self.wv(value)
B, Tq, D = query.size()
_, Tk, _ = key.size()
N = self.n_heads
probs = []
query, key, value = (x.contiguous().view(B, -1, N, D // N).
transpose(2, 1).contiguous().view(B * N, -1, D // N) for x in (
query, key, value))
if mask is not None:
mask = mask[:, None, :].expand(B, N, Tk).contiguous().view(B *
N, -1)
outputs = self.attention(query, key, value, mask, probs, beta, tau,
weights)
outputs = outputs.contiguous().view(B, N, -1, D // N).transpose(2, 1
).contiguous().view(B, -1, D)
if feedback is not None:
feedback.append(probs[0].view(B, N, Tq, Tk))
if self.use_wo:
return self.wo(outputs)
return outputs
class FeedForward(nn.Module):
def __init__(self, d_model, d_hidden):
super().__init__()
self.linear1 = Linear(d_model, d_hidden)
self.linear2 = Linear(d_hidden, d_model)
def forward(self, x):
return self.linear2(F.relu(self.linear1(x)))
class EncoderLayerNew(nn.Module):
def __init__(self, args):
super().__init__()
self.selfattn = ResidualBlock(MultiHead2(args.d_model, args.d_model,
args.n_heads, args.drop_ratio, use_wo=args.use_wo), args.
d_model, args.drop_ratio)
self.feedforward = ResidualBlock(FeedForward(args.d_model, args.
d_hidden), args.d_model, args.drop_ratio)
def forward(self, input_0):
primals_2 = self.selfattn.layer.wq.weight
primals_3 = self.selfattn.layer.wq.bias
primals_4 = self.selfattn.layer.wk.weight
primals_5 = self.selfattn.layer.wk.bias
primals_6 = self.selfattn.layer.wv.weight
primals_7 = self.selfattn.layer.wv.bias
primals_8 = self.selfattn.layer.wo.weight
primals_9 = self.selfattn.layer.wo.bias
primals_10 = self.selfattn.layernorm.gamma
primals_11 = self.selfattn.layernorm.beta
primals_12 = self.feedforward.layer.linear1.weight
primals_13 = self.feedforward.layer.linear1.bias
primals_14 = self.feedforward.layer.linear2.weight
primals_15 = self.feedforward.layer.linear2.bias
primals_16 = self.feedforward.layernorm.gamma
primals_17 = self.feedforward.layernorm.beta
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])
return output[0]
|
cclauss/nonauto-nmt
|
EncoderLayer
| false
| 15,022
|
[
"BSD-3-Clause"
] | 262
|
efcbe4f2329b140ac3ce06abb6409457cebc8e49
|
https://github.com/cclauss/nonauto-nmt/tree/efcbe4f2329b140ac3ce06abb6409457cebc8e49
|
BatchHardTripletLoss
|
import torch
import torch.nn as nn
class BatchHardTripletLoss(nn.Module):
def __init__(self, margin=0):
super(BatchHardTripletLoss, self).__init__()
self.margin = margin
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
def forward(self, inputs, targets):
batch_size = inputs.size(0)
dist = torch.pow(inputs, 2).sum(dim=1, keepdim=True).expand(batch_size,
batch_size)
dist = dist + dist.t()
dist.addmm_(1, -2, inputs, inputs.t())
dist = dist.clamp(min=1e-12).sqrt()
mask = targets.expand(batch_size, batch_size).eq(targets.expand(
batch_size, batch_size).t())
dist_ap = dist[mask == 1]
dist_ap = dist_ap.view(batch_size, -1)
dist_an = dist[mask == 0]
dist_an = dist_an.view(batch_size, -1)
dist_ap, _ = torch.max(dist_ap, dim=1)
dist_an, _ = torch.min(dist_an, dim=1)
y = torch.ones(dist_an.size(), dtype=dist_an.dtype, device=dist_an.
device)
loss = self.ranking_loss(dist_an, dist_ap, y)
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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_add_clamp_sqrt_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
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_out_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')
tmp12 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr0 + (3 + 4 * x0), 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
tmp13 = tmp12 * tmp12
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp21 = tmp20 * tmp20
tmp22 = tmp19 + tmp21
tmp23 = tmp11 + tmp22
tmp24 = tmp0 + tmp23
tmp25 = 1e-12
tmp26 = triton_helpers.maximum(tmp24, tmp25)
tmp27 = libdevice.sqrt(tmp26)
tl.store(in_out_ptr0 + x2, tmp27, xmask)
@triton.jit
def triton_poi_fused_eq_1(in_ptr0, 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 + (x1 + 4 * y0), xmask & ymask)
tmp1 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tmp2 = tmp0 == tmp1
tmp3 = tmp2.to(tl.int64)
tmp4 = tl.full([1, 1], 1, tl.int64)
tmp5 = tmp3 == tmp4
tl.store(out_ptr0 + (x1 + 4 * y0), tmp2, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp5, xmask & ymask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
0), out=buf0)
buf1 = buf0
del buf0
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_add_clamp_sqrt_0[grid(16)](buf2, arg0_1, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_eq_1[grid(4, 4)](arg1_1, buf3, buf4, 4, 4, XBLOCK=
4, YBLOCK=4, num_warps=1, num_stages=1)
del arg1_1
return buf2, buf4, buf3
class BatchHardTripletLossNew(nn.Module):
def __init__(self, margin=0):
super(BatchHardTripletLossNew, self).__init__()
self.margin = margin
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
chenyanghungry/person-reid-lib
|
BatchHardTripletLoss
| false
| 15,023
|
[
"MIT"
] | 81
|
783e66c9bfedf582e2cf935b9f5be960b543ac3c
|
https://github.com/chenyanghungry/person-reid-lib/tree/783e66c9bfedf582e2cf935b9f5be960b543ac3c
|
SelfAttentive
|
import torch
import torch.nn as nn
class SelfAttentive(nn.Module):
def __init__(self, hidden_size, att_hops=1, att_unit=200, dropout=0.2):
super(SelfAttentive, self).__init__()
self.drop = nn.Dropout(dropout)
self.ws1 = nn.Linear(hidden_size, att_unit, bias=False)
self.ws2 = nn.Linear(att_unit, att_hops, bias=False)
self.tanh = nn.Tanh()
self.softmax = nn.Softmax()
self.attention_hops = att_hops
def forward(self, rnn_out, mask=None):
outp = rnn_out
size = outp.size()
compressed_embeddings = outp.reshape(-1, size[2])
hbar = self.tanh(self.ws1(self.drop(compressed_embeddings)))
alphas = self.ws2(hbar).view(size[0], size[1], -1)
alphas = torch.transpose(alphas, 1, 2).contiguous()
if mask is not None:
mask = mask.squeeze(2)
concatenated_mask = [mask for i in range(self.attention_hops)]
concatenated_mask = torch.cat(concatenated_mask, 1)
penalized_alphas = alphas + concatenated_mask
else:
penalized_alphas = alphas
alphas = self.softmax(penalized_alphas.view(-1, size[1]))
alphas = alphas.view(size[0], self.attention_hops, size[1])
return torch.bmm(alphas, outp), alphas
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 3200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
@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 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (200, 4), (4, 1))
assert_size_stride(primals_3, (1, 200), (200, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 200), (200, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 200), (1, 4), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(3200)](buf1, 3200, XBLOCK=128,
num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_3, (200, 1), (1,
200), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = reinterpret_tensor(buf2, (4, 4), (4, 1), 0)
del buf2
triton_poi_fused__softmax_2[grid(16)](buf3, buf4, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 1, 4), (4, 4, 1), 0)
del buf3
extern_kernels.bmm(reinterpret_tensor(buf4, (4, 1, 4), (4, 4, 1), 0
), primals_1, out=buf5)
return buf5, reinterpret_tensor(buf4, (4, 1, 4), (4, 4, 1), 0
), primals_1, buf1, buf4, primals_3
class SelfAttentiveNew(nn.Module):
def __init__(self, hidden_size, att_hops=1, att_unit=200, dropout=0.2):
super(SelfAttentiveNew, self).__init__()
self.drop = nn.Dropout(dropout)
self.ws1 = nn.Linear(hidden_size, att_unit, bias=False)
self.ws2 = nn.Linear(att_unit, att_hops, bias=False)
self.tanh = nn.Tanh()
self.softmax = nn.Softmax()
self.attention_hops = att_hops
def forward(self, input_0):
primals_2 = self.ws1.weight
primals_3 = self.ws2.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
chenyangh/SemEval2019-Task3
|
SelfAttentive
| false
| 15,024
|
[
"MIT"
] | 50
|
c6204797b4b6cc08cb4d2d88108405f959d63ee9
|
https://github.com/chenyangh/SemEval2019-Task3/tree/c6204797b4b6cc08cb4d2d88108405f959d63ee9
|
Attention
|
import torch
import torch.nn as nn
import torch.nn
class Attention(nn.Module):
def __init__(self, dim_i, dim_o):
"""
build the target-aware attention
input schema:
dim_i: the dimension of the input feature vector
dim_o: the dimension of the output feature vector
output schema:
return a aggregated vector from the context k, v of q
"""
super(Attention, self).__init__()
self.Q = nn.Linear(dim_i, dim_o)
self.K = nn.Linear(dim_i, dim_o)
self.V = nn.Linear(dim_i, dim_o)
def forward(self, hist_seq_emb, hist_seq_mask, cand_emb):
q, k, v = self.Q(cand_emb), self.K(hist_seq_emb), self.V(hist_seq_emb)
logits = torch.sum(q.unsqueeze(1) * k, dim=2)
logits = logits * hist_seq_mask + logits * (1 - hist_seq_mask
) * -2 ** 32.0
scores = torch.softmax(logits, dim=1)
output = torch.sum(scores.unsqueeze(2) * v, dim=1)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim_i': 4, 'dim_o': 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
assert_size_stride = torch._C._dynamo.guards.assert_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, 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
x1 = xindex // 16 % 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x3, tmp14, xmask)
@triton.jit
def triton_poi_fused__softmax_add_mul_rsub_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp10 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp17 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp18 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp25 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp26 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp1
tmp5 = tmp0 * tmp4
tmp6 = -4294967296.0
tmp7 = tmp5 * tmp6
tmp8 = tmp2 + tmp7
tmp11 = tmp9 * tmp10
tmp12 = tmp3 - tmp10
tmp13 = tmp9 * tmp12
tmp14 = tmp13 * tmp6
tmp15 = tmp11 + tmp14
tmp16 = triton_helpers.maximum(tmp8, tmp15)
tmp19 = tmp17 * tmp18
tmp20 = tmp3 - tmp18
tmp21 = tmp17 * tmp20
tmp22 = tmp21 * tmp6
tmp23 = tmp19 + tmp22
tmp24 = triton_helpers.maximum(tmp16, tmp23)
tmp27 = tmp25 * tmp26
tmp28 = tmp3 - tmp26
tmp29 = tmp25 * tmp28
tmp30 = tmp29 * tmp6
tmp31 = tmp27 + tmp30
tmp32 = triton_helpers.maximum(tmp24, tmp31)
tmp33 = tmp8 - tmp32
tmp34 = tl_math.exp(tmp33)
tmp35 = tmp15 - tmp32
tmp36 = tl_math.exp(tmp35)
tmp37 = tmp34 + tmp36
tmp38 = tmp23 - tmp32
tmp39 = tl_math.exp(tmp38)
tmp40 = tmp37 + tmp39
tmp41 = tmp31 - tmp32
tmp42 = tl_math.exp(tmp41)
tmp43 = tmp40 + tmp42
tl.store(out_ptr0 + x2, tmp32, xmask)
tl.store(out_ptr1 + x2, tmp43, xmask)
@triton.jit
def triton_poi_fused_mul_sum_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
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex % 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr3 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr4 + x3, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp17 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp26 = tl.load(in_ptr4 + (64 + x3), xmask, eviction_policy='evict_last')
tmp29 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp30 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp39 = tl.load(in_ptr4 + (128 + x3), xmask, eviction_policy='evict_last')
tmp42 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp43 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp52 = tl.load(in_ptr4 + (192 + x3), xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp3 - tmp1
tmp5 = tmp0 * tmp4
tmp6 = -4294967296.0
tmp7 = tmp5 * tmp6
tmp8 = tmp2 + tmp7
tmp10 = tmp8 - tmp9
tmp11 = tl_math.exp(tmp10)
tmp13 = tmp11 / tmp12
tmp15 = tmp13 * tmp14
tmp18 = tmp16 * tmp17
tmp19 = tmp3 - tmp17
tmp20 = tmp16 * tmp19
tmp21 = tmp20 * tmp6
tmp22 = tmp18 + tmp21
tmp23 = tmp22 - tmp9
tmp24 = tl_math.exp(tmp23)
tmp25 = tmp24 / tmp12
tmp27 = tmp25 * tmp26
tmp28 = tmp15 + tmp27
tmp31 = tmp29 * tmp30
tmp32 = tmp3 - tmp30
tmp33 = tmp29 * tmp32
tmp34 = tmp33 * tmp6
tmp35 = tmp31 + tmp34
tmp36 = tmp35 - tmp9
tmp37 = tl_math.exp(tmp36)
tmp38 = tmp37 / tmp12
tmp40 = tmp38 * tmp39
tmp41 = tmp28 + tmp40
tmp44 = tmp42 * tmp43
tmp45 = tmp3 - tmp43
tmp46 = tmp42 * tmp45
tmp47 = tmp46 * tmp6
tmp48 = tmp44 + tmp47
tmp49 = tmp48 - tmp9
tmp50 = tl_math.exp(tmp49)
tmp51 = tmp50 / tmp12
tmp53 = tmp51 * tmp52
tmp54 = tmp41 + tmp53
tl.store(out_ptr0 + x4, tmp54, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.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((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(primals_6, (64,
4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf2)
del primals_7
del primals_8
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sum_0[grid(256)](buf0, buf1, buf3, 256, XBLOCK
=128, num_warps=4, num_stages=1)
buf4 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
triton_poi_fused__softmax_add_mul_rsub_1[grid(64)](buf3, primals_9,
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_mul_sum_2[grid(256)](buf3, primals_9, buf4, buf5,
buf2, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
del buf4
del buf5
return buf6, primals_9, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), buf1, buf2
class AttentionNew(nn.Module):
def __init__(self, dim_i, dim_o):
"""
build the target-aware attention
input schema:
dim_i: the dimension of the input feature vector
dim_o: the dimension of the output feature vector
output schema:
return a aggregated vector from the context k, v of q
"""
super(AttentionNew, self).__init__()
self.Q = nn.Linear(dim_i, dim_o)
self.K = nn.Linear(dim_i, dim_o)
self.V = nn.Linear(dim_i, dim_o)
def forward(self, input_0, input_1, input_2):
primals_1 = self.Q.weight
primals_2 = self.Q.bias
primals_4 = self.K.weight
primals_5 = self.K.bias
primals_7 = self.V.weight
primals_8 = self.V.bias
primals_3 = input_0
primals_6 = input_1
primals_9 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
chencsgit/luoxi_models
|
Attention
| false
| 15,025
|
[
"Apache-2.0"
] | 58
|
ea9e69dfb81b29f41ed92c75faacf81114c69a2f
|
https://github.com/chencsgit/luoxi_models/tree/ea9e69dfb81b29f41ed92c75faacf81114c69a2f
|
PoseNormalize
|
import torch
import torch.nn as nn
class PoseNormalize(nn.Module):
@torch.no_grad()
def forward(self, x):
return x * 2 - 1
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
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_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 - tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class PoseNormalizeNew(nn.Module):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
chinitaberrio/DeepPrivacy
|
PoseNormalize
| false
| 15,026
|
[
"MIT"
] | 1,128
|
d50e1b5ae762b47ab5a8f54cb90e66465057bd25
|
https://github.com/chinitaberrio/DeepPrivacy/tree/d50e1b5ae762b47ab5a8f54cb90e66465057bd25
|
InvertibleDownsampling3D
|
from torch.autograd import Function
import torch
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_3_t
from torch.nn.modules.utils import _triple
import torch.nn.functional as F
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleDownsampling3D(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_3_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_triple(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels * channel_multiplier
super(InvertibleDownsampling3D, self).__init__(*args,
low_channel_number=self.in_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def forward(self, x):
return F.conv3d(x, self.kernel, stride=self.stride, groups=self.
low_channel_number)
def inverse(self, x):
return F.conv_transpose3d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_3_t
from torch.nn.modules.utils import _triple
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_eye_sub_0(in_ptr0, out_ptr0, out_ptr1, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 32
xnumel = 8
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
y0 = yindex % 8
x2 = xindex
y3 = yindex
y1 = yindex // 8
tmp6 = tl.load(in_ptr0 + (x2 + 8 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (y0 + 8 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp0 = y0
tmp1 = x2
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x2 + 8 * y3), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x2 + 8 * y3), tmp10, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 32
xnumel = 8
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 8
y1 = yindex // 8
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 8 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 8 * y3), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 8, 8), (64, 8, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 8), (64, 8, 1), torch.float32)
buf5 = empty_strided_cuda((4, 8, 8), (64, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(32, 8)](primals_1, buf0, buf5,
32, 8, XBLOCK=8, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = buf0
del buf0
triton_poi_fused_clone_1[grid(32, 8)](buf7, buf8, 32, 8, XBLOCK=8,
YBLOCK=32, num_warps=4, num_stages=1)
buf9 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), reinterpret_tensor(buf8,
(32, 1, 2, 2, 2), (8, 0, 4, 2, 1), 0), stride=(2, 2, 2),
padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=4, bias=None)
assert_size_stride(buf9, (1, 32, 2, 2, 2), (256, 8, 4, 2, 1))
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
del buf7
buf11 = buf10
del buf10
return reinterpret_tensor(buf9, (32, 2, 2, 2), (8, 4, 2, 1), 0
), buf5, reinterpret_tensor(buf8, (32, 1, 2, 2, 2), (8, 8, 4, 2, 1), 0
), reinterpret_tensor(primals_2, (1, 4, 4, 4, 4), (256, 64, 16, 4,
1), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleDownsampling3DNew(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_3_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_triple(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels * channel_multiplier
super(InvertibleDownsampling3DNew, self).__init__(*args,
low_channel_number=self.in_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def inverse(self, x):
return F.conv_transpose3d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleDownsampling3D
| false
| 15,027
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
ToyNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ToyNet(nn.Module):
def __init__(self):
super(ToyNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.conv3 = nn.Conv2d(16, 64, 3)
self.conv4 = nn.Conv2d(64, 256, 3)
self.fc0 = nn.Linear(256 * 11 * 11, 2048)
self.fc1 = nn.Linear(2048, 512)
self.fc2 = nn.Linear(512, 128)
self.fc3 = nn.Linear(128, 2)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = self.pool(F.relu(self.conv4(x)))
x = x.view(-1, 256 * 11 * 11)
x = F.relu(self.fc0(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def get_inputs():
return [torch.rand([4, 3, 216, 216])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 18
xnumel = 25
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 25 * y3), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 75 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 12
xnumel = 46656
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 46656 * y3), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 139968 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 96
xnumel = 25
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 % 6
y1 = yindex // 6
tmp0 = tl.load(in_ptr0 + (x2 + 25 * y3), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (y0 + 6 * x2 + 150 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 16
y1 = yindex // 16
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 16 * x2 + 144 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 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_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 1078656
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 6
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_6(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 269664
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x1 = xindex // 6 % 106
x2 = xindex // 636
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 12 * x1 + 2544 * x2), xmask)
tmp1 = tl.load(in_ptr0 + (6 + x0 + 12 * x1 + 2544 * x2), xmask)
tmp3 = tl.load(in_ptr0 + (1272 + x0 + 12 * x1 + 2544 * x2), xmask)
tmp5 = tl.load(in_ptr0 + (1278 + x0 + 12 * x1 + 2544 * x2), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_7(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 665856
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 16
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_8(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 166464
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16 % 51
x2 = xindex // 816
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 32 * x1 + 3264 * x2), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 32 * x1 + 3264 * x2), xmask)
tmp3 = tl.load(in_ptr0 + (1632 + x0 + 32 * x1 + 3264 * x2), xmask)
tmp5 = tl.load(in_ptr0 + (1648 + x0 + 32 * x1 + 3264 * x2), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_9(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 614656
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_10(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 % 24
x2 = xindex // 1536 % 24
x3 = xindex // 36864
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x1 + 6272 * x2 + 153664 * x3), None)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 128 * x1 + 6272 * x2 + 153664 * x3),
None)
tmp3 = tl.load(in_ptr0 + (3136 + x0 + 128 * x1 + 6272 * x2 + 153664 *
x3), None)
tmp5 = tl.load(in_ptr0 + (3200 + x0 + 128 * x1 + 6272 * x2 + 153664 *
x3), 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 + x4, tmp6, None)
tl.store(out_ptr1 + x4, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_11(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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_max_pool2d_with_indices_12(in_ptr0, out_ptr0, out_ptr1,
ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 484
xnumel = 256
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 11
y1 = yindex // 11
y5 = yindex
y4 = yindex // 121
y6 = yindex % 121
tmp0 = tl.load(in_ptr0 + (x2 + 512 * y0 + 11264 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (256 + x2 + 512 * y0 + 11264 * y1), xmask &
ymask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (5632 + x2 + 512 * y0 + 11264 * y1), xmask &
ymask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (5888 + x2 + 512 * y0 + 11264 * y1), xmask &
ymask, eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1, 1], 1, tl.int8)
tmp4 = tl.full([1, 1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1, 1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1, 1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + (x2 + 256 * y5), tmp15, xmask & ymask)
tl.store(out_ptr1 + (y6 + 121 * x2 + 30976 * y4), tmp16, xmask & ymask)
@triton.jit
def triton_poi_fused_relu_13(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 2048
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_relu_14(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_relu_15(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17) = args
args.clear()
assert_size_stride(primals_1, (6, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (6,), (1,))
assert_size_stride(primals_3, (4, 3, 216, 216), (139968, 46656, 216, 1))
assert_size_stride(primals_4, (16, 6, 5, 5), (150, 25, 5, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (64, 16, 3, 3), (144, 9, 3, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (256, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_9, (256,), (1,))
assert_size_stride(primals_10, (2048, 30976), (30976, 1))
assert_size_stride(primals_11, (2048,), (1,))
assert_size_stride(primals_12, (512, 2048), (2048, 1))
assert_size_stride(primals_13, (512,), (1,))
assert_size_stride(primals_14, (128, 512), (512, 1))
assert_size_stride(primals_15, (128,), (1,))
assert_size_stride(primals_16, (2, 128), (128, 1))
assert_size_stride(primals_17, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((6, 3, 5, 5), (75, 1, 15, 3), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(18, 25)](primals_1, buf0, 18, 25, XBLOCK=32,
YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 3, 216, 216), (139968, 1, 648, 3),
torch.float32)
triton_poi_fused_1[grid(12, 46656)](primals_3, buf1, 12, 46656,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((16, 6, 5, 5), (150, 1, 30, 6), torch.float32
)
triton_poi_fused_2[grid(96, 25)](primals_4, buf2, 96, 25, XBLOCK=32,
YBLOCK=32, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((64, 16, 3, 3), (144, 1, 48, 16), torch.
float32)
triton_poi_fused_3[grid(1024, 9)](primals_6, buf3, 1024, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((256, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_4[grid(16384, 9)](primals_8, buf4, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf5 = extern_kernels.convolution(buf1, buf0, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 6, 212, 212), (269664, 1, 1272, 6))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_5[grid(1078656)](buf6, primals_2,
1078656, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf7 = empty_strided_cuda((4, 6, 106, 106), (67416, 1, 636, 6),
torch.float32)
buf8 = empty_strided_cuda((4, 6, 106, 106), (67416, 1, 636, 6),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_6[grid(269664)](buf6, buf7,
buf8, 269664, XBLOCK=512, num_warps=8, num_stages=1)
buf9 = extern_kernels.convolution(buf7, buf2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 16, 102, 102), (166464, 1, 1632, 16))
buf10 = buf9
del buf9
triton_poi_fused_convolution_relu_7[grid(665856)](buf10, primals_5,
665856, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf11 = empty_strided_cuda((4, 16, 51, 51), (41616, 1, 816, 16),
torch.float32)
buf12 = empty_strided_cuda((4, 16, 51, 51), (41616, 1, 816, 16),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_8[grid(166464)](buf10,
buf11, buf12, 166464, XBLOCK=512, num_warps=8, num_stages=1)
buf13 = extern_kernels.convolution(buf11, buf3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (4, 64, 49, 49), (153664, 1, 3136, 64))
buf14 = buf13
del buf13
triton_poi_fused_convolution_relu_9[grid(614656)](buf14, primals_7,
614656, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf15 = empty_strided_cuda((4, 64, 24, 24), (36864, 1, 1536, 64),
torch.float32)
buf16 = empty_strided_cuda((4, 64, 24, 24), (36864, 1, 1536, 64),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_10[grid(147456)](buf14,
buf15, buf16, 147456, XBLOCK=1024, num_warps=4, num_stages=1)
buf17 = extern_kernels.convolution(buf15, buf4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 256, 22, 22), (123904, 1, 5632, 256))
buf18 = buf17
del buf17
triton_poi_fused_convolution_relu_11[grid(495616)](buf18, primals_9,
495616, XBLOCK=512, num_warps=8, num_stages=1)
del primals_9
buf19 = empty_strided_cuda((4, 256, 11, 11), (30976, 1, 2816, 256),
torch.int8)
buf20 = empty_strided_cuda((4, 256, 11, 11), (30976, 121, 11, 1),
torch.float32)
triton_poi_fused_max_pool2d_with_indices_12[grid(484, 256)](buf18,
buf19, buf20, 484, 256, XBLOCK=256, YBLOCK=4, num_warps=4,
num_stages=1)
buf21 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf20, (4, 30976), (30976, 1),
0), reinterpret_tensor(primals_10, (30976, 2048), (1, 30976), 0
), out=buf21)
buf22 = buf21
del buf21
triton_poi_fused_relu_13[grid(8192)](buf22, primals_11, 8192,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf23 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
extern_kernels.mm(buf22, reinterpret_tensor(primals_12, (2048, 512),
(1, 2048), 0), out=buf23)
buf24 = buf23
del buf23
triton_poi_fused_relu_14[grid(2048)](buf24, primals_13, 2048,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_13
buf25 = empty_strided_cuda((4, 128), (128, 1), torch.float32)
extern_kernels.mm(buf24, reinterpret_tensor(primals_14, (512, 128),
(1, 512), 0), out=buf25)
buf26 = buf25
del buf25
triton_poi_fused_relu_15[grid(512)](buf26, primals_15, 512, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_15
buf27 = empty_strided_cuda((4, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_17, buf26, reinterpret_tensor(
primals_16, (128, 2), (1, 128), 0), alpha=1, beta=1, out=buf27)
del primals_17
return (buf27, buf0, buf1, buf2, buf3, buf4, buf6, buf7, buf8, buf10,
buf11, buf12, buf14, buf15, buf16, buf18, buf19, reinterpret_tensor
(buf20, (4, 30976), (30976, 1), 0), buf22, buf24, buf26, primals_16,
primals_14, primals_12, primals_10)
class ToyNetNew(nn.Module):
def __init__(self):
super(ToyNetNew, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.conv3 = nn.Conv2d(16, 64, 3)
self.conv4 = nn.Conv2d(64, 256, 3)
self.fc0 = nn.Linear(256 * 11 * 11, 2048)
self.fc1 = nn.Linear(2048, 512)
self.fc2 = nn.Linear(512, 128)
self.fc3 = nn.Linear(128, 2)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.fc0.weight
primals_11 = self.fc0.bias
primals_12 = self.fc1.weight
primals_13 = self.fc1.bias
primals_14 = self.fc2.weight
primals_15 = self.fc2.bias
primals_16 = self.fc3.weight
primals_17 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17])
return output[0]
|
asalmanp/MIVisionX
|
ToyNet
| false
| 15,028
|
[
"MIT"
] | 153
|
a964774944331827c8d6e9bb1ffbb2578f335056
|
https://github.com/asalmanp/MIVisionX/tree/a964774944331827c8d6e9bb1ffbb2578f335056
|
MS_Block
|
import torch
import torch.nn as nn
import torch.multiprocessing
class MS_Block(nn.Module):
def __init__(self, input_feature, out_feature, d=[1, 2, 4], group=1):
super(MS_Block, self).__init__()
self.l1 = nn.Conv2d(input_feature, out_feature, 3, padding=d[0],
dilation=d[0], bias=False, groups=group)
self.l2 = nn.Conv2d(input_feature, out_feature, 3, padding=d[1],
dilation=d[1], bias=False, groups=group)
self.l3 = nn.Conv2d(input_feature, out_feature, 3, padding=d[2],
dilation=d[2], bias=False, groups=group)
def forward(self, x):
out = self.l1(x) + self.l2(x) + self.l3(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_feature': 4, 'out_feature': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_add_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp3 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,
1), padding=(1, 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 = extern_kernels.convolution(primals_2, primals_3, stride=(1,
1), padding=(2, 2), dilation=(2, 2), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = extern_kernels.convolution(primals_2, primals_4, stride=(1,
1), padding=(4, 4), dilation=(4, 4), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf3, buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
del buf2
return buf3, primals_1, primals_2, primals_3, primals_4
class MS_BlockNew(nn.Module):
def __init__(self, input_feature, out_feature, d=[1, 2, 4], group=1):
super(MS_BlockNew, self).__init__()
self.l1 = nn.Conv2d(input_feature, out_feature, 3, padding=d[0],
dilation=d[0], bias=False, groups=group)
self.l2 = nn.Conv2d(input_feature, out_feature, 3, padding=d[1],
dilation=d[1], bias=False, groups=group)
self.l3 = nn.Conv2d(input_feature, out_feature, 3, padding=d[2],
dilation=d[2], bias=False, groups=group)
def forward(self, input_0):
primals_1 = self.l1.weight
primals_3 = self.l2.weight
primals_4 = self.l3.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
chiukin/RANet
|
MS_Block
| false
| 15,029
|
[
"Apache-2.0"
] | 267
|
681a47d9b1f114653290678f02f2d3ecdf4010bc
|
https://github.com/chiukin/RANet/tree/681a47d9b1f114653290678f02f2d3ecdf4010bc
|
InvertibleUpsampling2D
|
from torch.autograd import Function
import torch
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_2_t
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleUpsampling2D(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_2_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_pair(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels // channel_multiplier
super(InvertibleUpsampling2D, self).__init__(*args,
low_channel_number=self.out_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def forward(self, x):
return F.conv_transpose2d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def inverse(self, x):
return F.conv2d(x, self.kernel, stride=self.stride, groups=self.
low_channel_number)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_2_t
from torch.nn.modules.utils import _pair
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_eye_sub_0(in_ptr0, 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
y0 = yindex
x1 = xindex
tmp6 = tl.load(in_ptr0 + (x1 + 4 * y0), xmask & ymask)
tmp7 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
tmp0 = y0
tmp1 = x1
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x1 + 4 * y0), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x1 + 4 * y0), tmp10, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(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)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((1, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(4, 4)](primals_1, buf0, buf5, 4,
4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = reinterpret_tensor(buf0, (4, 1, 2, 2), (4, 4, 2, 1), 0)
del buf0
triton_poi_fused_convolution_1[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK
=4, YBLOCK=4, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(primals_2, buf8, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 1, 8, 8), (64, 64, 8, 1))
del buf8
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
buf11 = buf10
del buf10
return buf9, primals_2, buf5, reinterpret_tensor(buf7, (4, 1, 2, 2), (1,
16, 8, 4), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleUpsampling2DNew(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_2_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_pair(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels // channel_multiplier
super(InvertibleUpsampling2DNew, self).__init__(*args,
low_channel_number=self.out_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def inverse(self, x):
return F.conv2d(x, self.kernel, stride=self.stride, groups=self.
low_channel_number)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleUpsampling2D
| false
| 15,030
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
EPE
|
import torch
from torch import nn
import torch.utils.cpp_extension
class EPE(nn.Module):
def __init__(self):
super(EPE, self).__init__()
def forward(self, flow, gt, loss_mask):
loss_map = (flow - gt.detach()) ** 2
loss_map = (loss_map.sum(1, True) + 1e-06) ** 0.5
return loss_map * loss_mask
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.utils.cpp_extension
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_pow_sub_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp4 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp10 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp14 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp15 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = 1e-06
tmp20 = tmp18 + tmp19
tmp21 = libdevice.sqrt(tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_poi_fused_add_mul_pow_sub_sum_1(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_pow_sub_sum_0[grid(64)](arg1_1, arg0_1, buf0,
64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_pow_sub_sum_1[grid(256)](buf0, arg2_1,
buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg2_1
del buf0
return buf1,
class EPENew(nn.Module):
def __init__(self):
super(EPENew, self).__init__()
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
P2Oileen/oh-my-face
|
EPE
| false
| 15,031
|
[
"MIT"
] | 45
|
b73cb8ea713205bbf2bc1408145fa668c715359b
|
https://github.com/P2Oileen/oh-my-face/tree/b73cb8ea713205bbf2bc1408145fa668c715359b
|
InvertibleDownsampling1D
|
from torch.autograd import Function
import torch
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_1_t
from torch.nn.modules.utils import _single
import torch.nn.functional as F
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleDownsampling1D(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_1_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_single(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels * channel_multiplier
super(InvertibleDownsampling1D, self).__init__(*args,
low_channel_number=self.in_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def forward(self, x):
return F.conv1d(x, self.kernel, stride=self.stride, groups=self.
low_channel_number)
def inverse(self, x):
return F.conv_transpose1d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
import numpy as np
from warnings import warn
from typing import Union
from typing import Tuple
from torch.nn.common_types import _size_1_t
from torch.nn.modules.utils import _single
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_eye_sub_0(in_ptr0, out_ptr0, out_ptr1, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 8
xnumel = 2
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
y0 = yindex % 2
x2 = xindex
y3 = yindex
y1 = yindex // 2
tmp6 = tl.load(in_ptr0 + (x2 + 2 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (y0 + 2 * x2 + 4 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp0 = y0
tmp1 = x2
tmp2 = tmp0 == tmp1
tmp3 = 1.0
tmp4 = 0.0
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp8 = tmp6 - tmp7
tmp9 = tmp5 + tmp8
tmp10 = tmp5 - tmp8
tl.store(out_ptr0 + (x2 + 2 * y3), tmp9, xmask & ymask)
tl.store(out_ptr1 + (x2 + 2 * y3), tmp10, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 8
xnumel = 2
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 2
y1 = yindex // 2
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 2 * x2 + 4 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 2 * y3), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 2, 2), (4, 2, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 2, 2), (4, 2, 1), torch.float32)
buf5 = empty_strided_cuda((4, 2, 2), (4, 2, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_eye_sub_0[grid(8, 2)](primals_1, buf0, buf5, 8,
2, XBLOCK=2, YBLOCK=8, num_warps=1, num_stages=1)
del primals_1
buf1 = torch.ops.aten.linalg_lu_factor_ex.default(buf0)
buf2 = buf1[0]
buf3 = buf1[1]
del buf1
buf6 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf5)
buf7 = buf6
del buf6
buf8 = buf0
del buf0
triton_poi_fused_clone_1[grid(8, 2)](buf7, buf8, 8, 2, XBLOCK=2,
YBLOCK=8, num_warps=1, num_stages=1)
buf9 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1,
4, 4), (16, 4, 1), 0), reinterpret_tensor(buf8, (8, 1, 2), (2,
0, 1), 0), stride=(2,), padding=(0,), dilation=(1,), transposed
=False, output_padding=(0,), groups=4, bias=None)
assert_size_stride(buf9, (1, 8, 2), (16, 2, 1))
buf10 = torch.ops.aten.linalg_lu_solve.default(buf2, buf3, buf7)
del buf2
del buf3
del buf7
buf11 = buf10
del buf10
return reinterpret_tensor(buf9, (8, 2), (2, 1), 0
), buf5, reinterpret_tensor(buf8, (8, 1, 2), (2, 2, 1), 0
), reinterpret_tensor(primals_2, (1, 4, 4), (16, 4, 1), 0), buf11
def _cayley(A):
I = torch.eye(A.shape[-1], device=A.device)
LU = torch.lu(I + A, pivot=True)
return torch.lu_solve(I - A, *LU)
def _cayley_frechet(A, H, Q=None):
I = torch.eye(A.shape[-1], device=A.device)
if Q is None:
Q = _cayley(A)
_LU = torch.lu(I + A, pivot=True)
p = torch.lu_solve(Q, *_LU)
_LU = torch.lu(I - A, pivot=True)
q = torch.lu_solve(H, *_LU)
return 2.0 * q @ p
def __calculate_kernel_matrix_cayley__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return cayley.apply(skew_symmetric_matrix)
def matrix_1_norm(A):
"""Calculates the 1-norm of a matrix or a batch of matrices.
Args:
A (torch.Tensor): Can be either of size (n,n) or (m,n,n).
Returns:
torch.Tensor : The 1-norm of A.
"""
norm, _indices = torch.max(torch.sum(torch.abs(A), axis=-2), axis=-1)
return norm
def _compute_scales(A):
"""Compute optimal parameters for scaling-and-squaring algorithm.
The constants used in this function are determined by the MATLAB
function found in
https://github.com/cetmann/pytorch_expm/blob/master/determine_frechet_scaling_constant.m
"""
norm = matrix_1_norm(A)
max_norm = torch.max(norm)
s = torch.zeros_like(norm)
if A.dtype == torch.float64:
if A.requires_grad:
ell = {(3): 0.010813385777848, (5): 0.199806320697895, (7):
0.783460847296204, (9): 1.782448623969279, (13):
4.740307543765127}
else:
ell = {(3): 0.014955852179582, (5): 0.253939833006323, (7):
0.950417899616293, (9): 2.097847961257068, (13):
5.371920351148152}
if max_norm >= ell[9]:
m = 13
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5, 7, 9]:
if max_norm < ell[m]:
magic_number = ell[m]
break
elif A.dtype == torch.float32:
if A.requires_grad:
ell = {(3): 0.30803304184533, (5): 1.482532614793145, (7):
3.248671755200478}
else:
ell = {(3): 0.425873001692283, (5): 1.880152677804762, (7):
3.92572478313866}
if max_norm >= ell[5]:
m = 7
magic_number = ell[m]
s = torch.relu_(torch.ceil(torch.log2_(norm / magic_number)))
else:
for m in [3, 5]:
if max_norm < ell[m]:
magic_number = ell[m]
break
return s, m
def _eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def _expm_frechet_pade(A, E, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
if m >= 3:
M_2 = A @ E + E @ A
A_2 = A @ A
U = b[3] * A_2
V = b[2] * A_2
L_U = b[3] * M_2
L_V = b[2] * M_2
if m >= 5:
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
L_U = L_U + b[5] * M_4
L_V = L_V + b[4] * M_4
if m >= 7:
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
L_U = L_U + b[7] * M_6
L_V = L_V + b[6] * M_6
if m == 9:
M_8 = A_4 @ M_4 + M_4 @ A_4
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
L_U = L_U + b[9] * M_8
L_V = L_V + b[8] * M_8
U = U + b[1] * I
V = U + b[0] * I
del I
L_U = A @ L_U
L_U = L_U + E @ U
U = A @ U
else:
M_2 = A @ E + E @ A
A_2 = A @ A
M_4 = A_2 @ M_2 + M_2 @ A_2
A_4 = A_2 @ A_2
M_6 = A_4 @ M_2 + M_4 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
L_W1 = b[13] * M_6 + b[11] * M_4 + b[9] * M_2
L_W2 = b[7] * M_6 + b[5] * M_4 + b[3] * M_2
L_Z1 = b[12] * M_6 + b[10] * M_4 + b[8] * M_2
L_Z2 = b[6] * M_6 + b[4] * M_4 + b[2] * M_2
L_W = A_6 @ L_W1 + M_6 @ W_1 + L_W2
L_U = A @ L_W + E @ W
L_V = A_6 @ L_Z1 + M_6 @ Z_1 + L_Z2
lu_decom = torch.lu(-U + V)
exp_A = torch.lu_solve(U + V, *lu_decom)
dexp_A = torch.lu_solve(L_U + L_V + (L_U - L_V) @ exp_A, *lu_decom)
return exp_A, dexp_A
def _square(s, R, L=None):
"""The `squaring` part of the `scaling-and-squaring` algorithm.
This works both for the forward as well as the derivative of
the matrix exponential.
"""
s_max = torch.max(s).int()
if s_max > 0:
I = _eye_like(R)
if L is not None:
O = torch.zeros_like(R)
indices = [(1) for k in range(len(R.shape) - 1)]
for i in range(s_max):
mask = i >= s
matrices_mask = mask.view(-1, *indices)
temp_eye = torch.clone(R).masked_scatter(matrices_mask, I)
if L is not None:
temp_zeros = torch.clone(R).masked_scatter(matrices_mask, O)
L = temp_eye @ L + temp_zeros @ L
R = R @ temp_eye
del temp_eye, mask
if L is not None:
return R, L
else:
return R
def _expm_frechet_scaling_squaring(A, E, adjoint=False):
"""Numerical Fréchet derivative of matrix exponentiation.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
if adjoint is True:
A = torch.transpose(A, -1, -2)
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
scaling_factors = torch.pow(2, -s).view(-1, *indices)
A = A * scaling_factors
E = E * scaling_factors
exp_A, dexp_A = _expm_frechet_pade(A, E, m)
exp_A, dexp_A = _square(s, exp_A, dexp_A)
return dexp_A
def _expm_pade(A, m=7):
assert m in [3, 5, 7, 9, 13]
if m == 3:
b = [120.0, 60.0, 12.0, 1.0]
elif m == 5:
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
elif m == 7:
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0,
56.0, 1.0]
elif m == 9:
b = [17643225600.0, 8821612800.0, 2075673600.0, 302702400.0,
30270240.0, 2162160.0, 110880.0, 3960.0, 90.0, 1.0]
elif m == 13:
b = [6.476475253248e+16, 3.238237626624e+16, 7771770303897600.0,
1187353796428800.0, 129060195264000.0, 10559470521600.0,
670442572800.0, 33522128640.0, 1323241920.0, 40840800.0,
960960.0, 16380.0, 182.0, 1.0]
I = _eye_like(A)
if m != 13:
U = b[1] * I
V = b[0] * I
if m >= 3:
A_2 = A @ A
U = U + b[3] * A_2
V = V + b[2] * A_2
if m >= 5:
A_4 = A_2 @ A_2
U = U + b[5] * A_4
V = V + b[4] * A_4
if m >= 7:
A_6 = A_4 @ A_2
U = U + b[7] * A_6
V = V + b[6] * A_6
if m == 9:
A_8 = A_4 @ A_4
U = U + b[9] * A_8
V = V + b[8] * A_8
U = A @ U
else:
A_2 = A @ A
A_4 = A_2 @ A_2
A_6 = A_4 @ A_2
W_1 = b[13] * A_6 + b[11] * A_4 + b[9] * A_2
W_2 = b[7] * A_6 + b[5] * A_4 + b[3] * A_2 + b[1] * I
W = A_6 @ W_1 + W_2
Z_1 = b[12] * A_6 + b[10] * A_4 + b[8] * A_2
Z_2 = b[6] * A_6 + b[4] * A_4 + b[2] * A_2 + b[0] * I
U = A @ W
V = A_6 @ Z_1 + Z_2
del A_2
if m >= 5:
del A_4
if m >= 7:
del A_6
if m == 9:
del A_8
R = torch.lu_solve(U + V, *torch.lu(-U + V))
del U, V
return R
def _expm_scaling_squaring(A):
"""Scaling-and-squaring algorithm for matrix eponentiation.
This is based on the observation that exp(A) = exp(A/k)^k, where
e.g. k=2^s. The exponential exp(A/(2^s)) is calculated by a diagonal
Padé approximation, where s is chosen based on the 1-norm of A, such
that certain approximation guarantees can be given. exp(A) is then
calculated by repeated squaring via exp(A/(2^s))^(2^s). This function
works both for (n,n)-tensors as well as batchwise for (m,n,n)-tensors.
"""
assert A.shape[-1] == A.shape[-2] and len(A.shape) in [2, 3]
True if len(A.shape) == 3 else False
s, m = _compute_scales(A)
if torch.max(s) > 0:
indices = [(1) for k in range(len(A.shape) - 1)]
A = A * torch.pow(2, -s).view(-1, *indices)
exp_A = _expm_pade(A, m)
exp_A = _square(s, exp_A)
return exp_A
def __calculate_kernel_matrix_exp__(weight, **kwargs):
skew_symmetric_matrix = weight - torch.transpose(weight, -1, -2)
return expm.apply(skew_symmetric_matrix)
def eye_like(M, device=None, dtype=None):
"""Creates an identity matrix of the same shape as another matrix.
For matrix M, the output is same shape as M, if M is a (n,n)-matrix.
If M is a batch of m matrices (i.e. a (m,n,n)-tensor), create a batch of
(n,n)-identity-matrices.
Args:
M (torch.Tensor) : A tensor of either shape (n,n) or (m,n,n), for
which either an identity matrix or a batch of identity matrices
of the same shape will be created.
device (torch.device, optional) : The device on which the output
will be placed. By default, it is placed on the same device
as M.
dtype (torch.dtype, optional) : The dtype of the output. By default,
it is the same dtype as M.
Returns:
torch.Tensor : Identity matrix or batch of identity matrices.
"""
assert len(M.shape) in [2, 3]
assert M.shape[-1] == M.shape[-2]
n = M.shape[-1]
if device is None:
device = M.device
if dtype is None:
dtype = M.dtype
eye = torch.eye(M.shape[-1], device=device, dtype=dtype)
if len(M.shape) == 2:
return eye
else:
m = M.shape[0]
return eye.view(-1, n, n).expand(m, -1, -1)
def householder_matrix(unit_vector):
if unit_vector.shape[-1] != 1:
if len(unit_vector.shape) == 1:
return torch.ones_like(unit_vector)
unit_vector = unit_vector.view(*tuple(unit_vector.shape), 1)
transform = 2 * unit_vector @ torch.transpose(unit_vector, -1, -2)
return eye_like(transform) - transform
def normalize_matrix_rows(matrix, eps=1e-06):
norms = torch.sqrt(torch.sum(matrix ** 2, dim=-2, keepdim=True) + eps)
return matrix / norms
def householder_transform(matrix, n_reflections=-1, eps=1e-06):
"""Implements a product of Householder transforms.
"""
if n_reflections == -1:
n_reflections = matrix.shape[-1]
if n_reflections > matrix.shape[-1]:
warn('n_reflections is set higher than the number of rows.')
n_reflections = matrix.shape[-1]
matrix = normalize_matrix_rows(matrix, eps)
if n_reflections == 0:
output = torch.eye(matrix.shape[-2], dtype=matrix.dtype, device=
matrix.device)
if len(matrix.shape) == 3:
output = output.view(1, matrix.shape[1], matrix.shape[1])
output = output.expand(matrix.shape[0], -1, -1)
for i in range(n_reflections):
unit_vector = matrix[..., i:i + 1]
householder = householder_matrix(unit_vector)
if i == 0:
output = householder
else:
output = output @ householder
return output
def __calculate_kernel_matrix_householder__(weight, **kwargs):
n_reflections = kwargs.get('n_reflections', -1)
eps = kwargs.get('eps', 1e-06)
weight.shape[-1]
weight = weight[..., n_reflections:]
return householder_transform(weight, n_reflections, eps)
def __initialize_weight__(kernel_matrix_shape: 'Tuple[int, ...]', stride:
'Tuple[int, ...]', method: 'str'='cayley', init: 'str'='haar', dtype:
'str'='float32', *args, **kwargs):
"""Function which computes specific orthogonal matrices.
For some chosen method of parametrizing orthogonal matrices, this
function outputs the required weights necessary to represent a
chosen initialization as a Pytorch tensor of matrices.
Args:
kernel_matrix_shape : The output shape of the
orthogonal matrices. Should be (num_matrices, height, width).
stride : The stride for the invertible up- or
downsampling for which this matrix is to be used. The length
of ``stride`` should match the dimensionality of the data.
method : The method for parametrising orthogonal matrices.
Should be 'exp' or 'cayley'
init : The matrix which should be represented. Should be
'squeeze', 'pixel_shuffle', 'haar' or 'random'. 'haar' is only
possible if ``stride`` is only 2.
dtype : Numpy dtype which should be used for the matrix.
*args: Variable length argument iterable.
**kwargs: Arbitrary keyword arguments.
Returns:
Tensor : Orthogonal matrices of shape ``kernel_matrix_shape``.
"""
dim = len(stride)
num_matrices = kernel_matrix_shape[0]
assert method in ['exp', 'cayley', 'householder']
if method == 'householder':
warn(
'Householder parametrization not fully implemented yet. Only random initialization currently working.'
)
init = 'random'
if init == 'random':
return torch.randn(kernel_matrix_shape)
if init == 'haar' and set(stride) != {2}:
None
None
init = 'squeeze'
if init == 'haar' and set(stride) == {2}:
if method == 'exp':
p = np.pi / 4
if dim == 1:
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
weight = np.array([[[0, p, p, 0, p, 0, 0, 0], [0, 0, 0, p,
0, p, 0, 0], [0, 0, 0, p, 0, 0, p, 0], [0, 0, 0, 0, 0,
0, 0, p], [0, 0, 0, 0, 0, p, p, 0], [0, 0, 0, 0, 0, 0,
0, p], [0, 0, 0, 0, 0, 0, 0, p], [0, 0, 0, 0, 0, 0, 0,
0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
elif method == 'cayley':
if dim == 1:
p = -np.sqrt(2) / (2 - np.sqrt(2))
weight = np.array([[[0, p], [0, 0]]], dtype=dtype)
if dim == 2:
p = 0.5
weight = np.array([[[0, 0, p, p], [0, 0, -p, -p], [0, 0, 0,
0], [0, 0, 0, 0]]], dtype=dtype)
if dim == 3:
p = 1 / np.sqrt(2)
weight = np.array([[[0, -p, -p, 0, -p, 0, 0, 1 - p], [0, 0,
0, -p, 0, -p, p - 1, 0], [0, 0, 0, -p, 0, p - 1, -p, 0],
[0, 0, 0, 0, 1 - p, 0, 0, -p], [0, 0, 0, 0, 0, -p, -p,
0], [0, 0, 0, 0, 0, 0, 0, -p], [0, 0, 0, 0, 0, 0, 0, -p
], [0, 0, 0, 0, 0, 0, 0, 0]]], dtype=dtype)
return torch.tensor(weight).repeat(num_matrices, 1, 1)
if init in ['squeeze', 'pixel_shuffle', 'zeros']:
if method == 'exp' or method == 'cayley':
return torch.zeros(*kernel_matrix_shape)
if type(init) is np.ndarray:
init = torch.tensor(init.astype(dtype))
if torch.is_tensor(init):
if len(init.shape) == 2:
init = init.reshape(1, *init.shape)
if init.shape[0] == 1:
init = init.repeat(num_matrices, 1, 1)
assert init.shape == kernel_matrix_shape
return init
else:
raise NotImplementedError('Unknown initialization.')
class cayley(Function):
"""Computes the Cayley transform.
"""
@staticmethod
def forward(ctx, M):
cayley_M = _cayley(M)
ctx.save_for_backward(M, cayley_M)
return cayley_M
@staticmethod
def backward(ctx, grad_out):
M, cayley_M = ctx.saved_tensors
dcayley_M = _cayley_frechet(M, grad_out, Q=cayley_M)
return dcayley_M
class expm(Function):
"""Computes the matrix exponential.
"""
@staticmethod
def forward(ctx, M):
expm_M = _expm_scaling_squaring(M)
ctx.save_for_backward(M)
return expm_M
@staticmethod
def backward(ctx, grad_out):
M = ctx.saved_tensors[0]
dexpm = _expm_frechet_scaling_squaring(M, grad_out, adjoint=True)
return dexpm
class OrthogonalResamplingLayer(torch.nn.Module):
"""Base class for orthogonal up- and downsampling operators.
:param low_channel_number:
Lower number of channels. These are the input
channels in the case of downsampling ops, and the output
channels in the case of upsampling ops.
:param stride:
The downsampling / upsampling factor for each dimension.
:param channel_multiplier:
The channel multiplier, i.e. the number
by which the number of channels are multiplied (downsampling)
or divided (upsampling).
:param method:
Which method to use for parametrizing orthogonal
matrices which are used as convolutional kernels.
"""
def __init__(self, low_channel_number: 'int', stride:
'Union[int, Tuple[int, ...]]', method: 'str'='cayley', init:
'Union[str, np.ndarray, torch.Tensor]'='haar', learnable: 'bool'=
True, init_kwargs: 'dict'=None, **kwargs):
super(OrthogonalResamplingLayer, self).__init__()
self.low_channel_number = low_channel_number
self.method = method
self.stride = stride
self.channel_multiplier = int(np.prod(stride))
self.high_channel_number = self.channel_multiplier * low_channel_number
if init_kwargs is None:
init_kwargs = {}
self.init_kwargs = init_kwargs
self.kwargs = kwargs
assert method in ['exp', 'cayley', 'householder']
if method == 'exp':
self.__calculate_kernel_matrix__ = __calculate_kernel_matrix_exp__
elif method == 'cayley':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_cayley__)
elif method == 'householder':
self.__calculate_kernel_matrix__ = (
__calculate_kernel_matrix_householder__)
self._kernel_matrix_shape = (self.low_channel_number,) + (self.
channel_multiplier,) * 2
self._kernel_shape = (self.high_channel_number, 1) + self.stride
self.weight = torch.nn.Parameter(__initialize_weight__(
kernel_matrix_shape=self._kernel_matrix_shape, stride=self.
stride, method=self.method, init=init, **self.init_kwargs))
self.weight.requires_grad = learnable
@property
def kernel_matrix(self):
"""The orthogonal matrix created by the chosen parametrisation method.
"""
return self.__calculate_kernel_matrix__(self.weight, **self.kwargs)
@property
def kernel(self):
"""The kernel associated with the invertible up-/downsampling.
"""
return self.kernel_matrix.reshape(*self._kernel_shape)
class InvertibleDownsampling1DNew(OrthogonalResamplingLayer):
def __init__(self, in_channels: 'int', stride: '_size_1_t'=2, method:
'str'='cayley', init: 'str'='haar', learnable: 'bool'=True, *args,
**kwargs):
stride = tuple(_single(stride))
channel_multiplier = int(np.prod(stride))
self.in_channels = in_channels
self.out_channels = in_channels * channel_multiplier
super(InvertibleDownsampling1DNew, self).__init__(*args,
low_channel_number=self.in_channels, stride=stride, method=
method, init=init, learnable=learnable, **kwargs)
def inverse(self, x):
return F.conv_transpose1d(x, self.kernel, stride=self.stride,
groups=self.low_channel_number)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
cetmann/iunets
|
InvertibleDownsampling1D
| false
| 15,032
|
[
"MIT"
] | 86
|
80ed7cce0e505a0396c42359eaf27819222d71f6
|
https://github.com/cetmann/iunets/tree/80ed7cce0e505a0396c42359eaf27819222d71f6
|
MLP_G
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class MLP_G(nn.Module):
def __init__(self, opt):
super(MLP_G, self).__init__()
self.fc1 = nn.Linear(opt.attSize + opt.nz, opt.ngh)
self.fc2 = nn.Linear(opt.ngh, opt.resSize)
self.lrelu = nn.LeakyReLU(0.2, True)
self.relu = nn.ReLU(True)
self.apply(weights_init)
def forward(self, noise, att):
h = torch.cat((noise, att), 1)
h = self.lrelu(self.fc1(h))
h = self.relu(self.fc2(h))
return h
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'opt': _mock_config(attSize=4, nz=4, ngh=4, resSize=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_leaky_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x2, tmp7, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 8), (8, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8
), 0), out=buf1)
del primals_3
buf2 = buf1
del buf1
triton_poi_fused_leaky_relu_1[grid(16)](buf2, primals_4, 16, XBLOCK
=16, num_warps=1, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4
), 0), out=buf3)
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(16)](buf4,
primals_6, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_6
return buf4, buf0, buf2, buf5, primals_5
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
m.weight.data.normal_(0.0, 0.02)
m.bias.data.fill_(0)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class MLP_GNew(nn.Module):
def __init__(self, opt):
super(MLP_GNew, self).__init__()
self.fc1 = nn.Linear(opt.attSize + opt.nz, opt.ngh)
self.fc2 = nn.Linear(opt.ngh, opt.resSize)
self.lrelu = nn.LeakyReLU(0.2, True)
self.relu = nn.ReLU(True)
self.apply(weights_init)
def forward(self, input_0, input_1):
primals_3 = self.fc1.weight
primals_4 = self.fc1.bias
primals_1 = self.fc2.weight
primals_6 = self.fc2.bias
primals_2 = input_0
primals_5 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
Huihui-z/CE-GZSL
|
MLP_G
| false
| 15,033
|
[
"MIT"
] | 58
|
7bf5358ac4727ea1dc2dc9dec2f453b014500bd8
|
https://github.com/Huihui-z/CE-GZSL/tree/7bf5358ac4727ea1dc2dc9dec2f453b014500bd8
|
SqueezeExcite
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from itertools import product as product
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
if new_v < 0.9 * v:
new_v += divisor
return new_v
def hard_sigmoid(x, inplace: 'bool'=False):
if inplace:
return x.add_(3.0).clamp_(0.0, 6.0).div_(6.0)
else:
return F.relu6(x + 3.0) / 6.0
class SqueezeExcite(nn.Module):
def __init__(self, in_chs, se_ratio=0.25, reduced_base_chs=None,
act_layer=nn.ReLU, gate_fn=hard_sigmoid, divisor=4, **_):
super(SqueezeExcite, self).__init__()
self.gate_fn = gate_fn
reduced_chs = _make_divisible((reduced_base_chs or in_chs) *
se_ratio, divisor)
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv_reduce = nn.Conv2d(in_chs, reduced_chs, 1, bias=True)
self.act1 = act_layer(inplace=True)
self.conv_expand = nn.Conv2d(reduced_chs, in_chs, 1, bias=True)
def forward(self, x):
x_se = self.avg_pool(x)
x_se = self.conv_reduce(x_se)
x_se = self.act1(x_se)
x_se = self.conv_expand(x_se)
x = x * self.gate_fn(x_se)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_chs': 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
from itertools import product as product
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
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_add_convolution_div_hardtanh_mul_2(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
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')
tmp3 = tmp1 + tmp2
tmp4 = 3.0
tmp5 = tmp3 + tmp4
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = 6.0
tmp9 = triton_helpers.minimum(tmp7, tmp8)
tmp10 = 0.16666666666666666
tmp11 = tmp9 * tmp10
tmp12 = tmp0 * tmp11
tl.store(out_ptr0 + x3, tmp12, xmask)
@triton.jit
def triton_poi_fused_add_convolution_hardtanh_backward_3(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 3.0
tmp4 = tmp2 + tmp3
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tmp7 = 6.0
tmp8 = tmp4 >= tmp7
tmp9 = tmp6 | tmp8
tl.store(out_ptr0 + x2, tmp9, 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=1,
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 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_convolution_div_hardtanh_mul_2[grid(256)](
primals_1, buf4, primals_5, buf5, 256, XBLOCK=256, num_warps=4,
num_stages=1)
buf6 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.bool)
triton_poi_fused_add_convolution_hardtanh_backward_3[grid(16)](buf4,
primals_5, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf4
del primals_5
return buf5, primals_1, primals_2, primals_4, buf1, buf3, buf6
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
if new_v < 0.9 * v:
new_v += divisor
return new_v
def hard_sigmoid(x, inplace: 'bool'=False):
if inplace:
return x.add_(3.0).clamp_(0.0, 6.0).div_(6.0)
else:
return F.relu6(x + 3.0) / 6.0
class SqueezeExciteNew(nn.Module):
def __init__(self, in_chs, se_ratio=0.25, reduced_base_chs=None,
act_layer=nn.ReLU, gate_fn=hard_sigmoid, divisor=4, **_):
super(SqueezeExciteNew, self).__init__()
self.gate_fn = gate_fn
reduced_chs = _make_divisible((reduced_base_chs or in_chs) *
se_ratio, divisor)
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv_reduce = nn.Conv2d(in_chs, reduced_chs, 1, bias=True)
self.act1 = act_layer(inplace=True)
self.conv_expand = nn.Conv2d(reduced_chs, in_chs, 1, bias=True)
def forward(self, input_0):
primals_2 = self.conv_reduce.weight
primals_3 = self.conv_reduce.bias
primals_4 = self.conv_expand.weight
primals_5 = self.conv_expand.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
chuanli11/SynergyNet
|
SqueezeExcite
| false
| 15,034
|
[
"MIT"
] | 82
|
a8044d8dabbfb811d4299f59e64e0fb749027e86
|
https://github.com/chuanli11/SynergyNet/tree/a8044d8dabbfb811d4299f59e64e0fb749027e86
|
BasicBlock_ins
|
import torch
import torch.nn as nn
import torch.multiprocessing
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock_ins(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock_ins, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.InstanceNorm2d(planes, affine=True,
track_running_stats=False)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.InstanceNorm2d(planes, affine=True,
track_running_stats=False)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__native_batch_norm_legit_relu_repeat_0(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr3, out_ptr4, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex
r1 = rindex
x2 = xindex % 4
tmp0 = tl.load(in_ptr0 + x0 % 4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0), xmask, other=0.0)
tmp26 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tl.where(xmask, tmp2, 0)
tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp7 = tl.where(xmask, tmp5, 0)
tmp8 = tl.sum(tmp7, 1)[:, None]
tmp9 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 / tmp10
tmp12 = tmp2 - tmp11
tmp13 = tmp12 * tmp12
tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
tmp16 = tl.where(xmask, tmp14, 0)
tmp17 = tl.sum(tmp16, 1)[:, None]
tmp18 = tmp1 - tmp11
tmp19 = 16.0
tmp20 = tmp17 / tmp19
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tmp24 = tmp18 * tmp23
tmp25 = tmp24 * tmp0
tmp27 = tmp25 + tmp26
tmp28 = tl.full([1, 1], 0, tl.int32)
tmp29 = triton_helpers.maximum(tmp28, tmp27)
tl.store(out_ptr0 + x0, tmp0, xmask)
tl.store(out_ptr3 + (r1 + 16 * x0), tmp29, xmask)
tl.store(out_ptr4 + x0, tmp23, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_relu_repeat_threshold_backward_1(
in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, out_ptr1, out_ptr3,
out_ptr4, out_ptr5, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
x0 = xindex
r1 = rindex
x2 = xindex % 4
tmp0 = tl.load(in_ptr0 + x0 % 4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0), xmask, other=0.0)
tmp26 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp28 = tl.load(in_ptr3 + (r1 + 16 * x0), xmask, other=0.0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tl.where(xmask, tmp2, 0)
tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp7 = tl.where(xmask, tmp5, 0)
tmp8 = tl.sum(tmp7, 1)[:, None]
tmp9 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp10 = tmp9.to(tl.float32)
tmp11 = tmp8 / tmp10
tmp12 = tmp2 - tmp11
tmp13 = tmp12 * tmp12
tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
tmp16 = tl.where(xmask, tmp14, 0)
tmp17 = tl.sum(tmp16, 1)[:, None]
tmp18 = tmp1 - tmp11
tmp19 = 16.0
tmp20 = tmp17 / tmp19
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tmp24 = tmp18 * tmp23
tmp25 = tmp24 * tmp0
tmp27 = tmp25 + tmp26
tmp29 = tmp27 + tmp28
tmp30 = tl.full([1, 1], 0, tl.int32)
tmp31 = triton_helpers.maximum(tmp30, tmp29)
tmp32 = 0.0
tmp33 = tmp31 <= tmp32
tl.store(out_ptr0 + x0, tmp0, xmask)
tl.store(out_ptr3 + (r1 + 16 * x0), tmp31, xmask)
tl.store(out_ptr4 + (r1 + 16 * x0), tmp33, xmask)
tl.store(out_ptr5 + x0, tmp23, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = empty_strided_cuda((16,), (1,), torch.float32)
buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf5 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_relu_repeat_0[grid(16)](
primals_3, buf0, primals_4, buf1, buf2, buf6, buf5, 16, 16,
XBLOCK=8, num_warps=2, num_stages=1)
del primals_3
del primals_4
buf7 = extern_kernels.convolution(buf6, primals_5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 4, 4, 4), (64, 16, 4, 1))
buf8 = empty_strided_cuda((16,), (1,), torch.float32)
buf9 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf13 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf12 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
triton_per_fused__native_batch_norm_legit_relu_repeat_threshold_backward_1[
grid(16)](primals_6, buf7, primals_7, primals_1, buf8, buf9,
buf13, buf14, buf12, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del primals_6
del primals_7
return (buf13, primals_1, primals_2, primals_5, buf0, buf1,
reinterpret_tensor(buf5, (16,), (1,), 0), buf6, buf7, buf8,
reinterpret_tensor(buf12, (16,), (1,), 0), buf14,
reinterpret_tensor(buf9, (1, 16, 1, 1), (16, 1, 1, 1), 0),
reinterpret_tensor(buf2, (1, 16, 1, 1), (16, 1, 1, 1), 0))
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock_insNew(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock_insNew, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.InstanceNorm2d(planes, affine=True,
track_running_stats=False)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.InstanceNorm2d(planes, affine=True,
track_running_stats=False)
self.downsample = downsample
self.stride = stride
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.bn1.weight
primals_4 = self.bn1.bias
primals_5 = self.conv2.weight
primals_6 = self.bn2.weight
primals_7 = self.bn2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
chiukin/RANet
|
BasicBlock_ins
| false
| 15,035
|
[
"Apache-2.0"
] | 267
|
681a47d9b1f114653290678f02f2d3ecdf4010bc
|
https://github.com/chiukin/RANet/tree/681a47d9b1f114653290678f02f2d3ecdf4010bc
|
ResBlock2
|
import torch
import torch.nn as nn
import torch.multiprocessing
class ResBlock2(nn.Module):
def __init__(self, input_feature, planes, dilated=1, group=1):
super(ResBlock2, self).__init__()
self.conv1 = nn.Conv2d(input_feature, planes, kernel_size=1, bias=
False, groups=group)
self.bn1 = nn.InstanceNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1 *
dilated, bias=False, dilation=dilated, groups=group)
self.bn2 = nn.InstanceNorm2d(planes)
self.conv3 = nn.Conv2d(planes, input_feature, kernel_size=1, bias=
False, groups=group)
self.bn3 = nn.InstanceNorm2d(input_feature)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
out += residual
out = self.relu(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_feature': 4, 'planes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__native_batch_norm_legit_relu_0(in_ptr0, out_ptr0,
out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp0 - tmp10
tmp18 = 16.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp24 = tl.full([1, 1], 0, tl.int32)
tmp25 = triton_helpers.maximum(tmp24, tmp23)
tl.store(out_ptr2 + (r1 + 16 * x0), tmp25, xmask)
tl.store(out_ptr3 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_relu_threshold_backward_1(in_ptr0
, in_ptr1, out_ptr0, out_ptr2, out_ptr3, out_ptr4, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp24 = tl.load(in_ptr1 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp0 - tmp10
tmp18 = 16.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 + tmp24
tmp26 = tl.full([1, 1], 0, tl.int32)
tmp27 = triton_helpers.maximum(tmp26, tmp25)
tmp28 = 0.0
tmp29 = tmp27 <= tmp28
tl.store(out_ptr2 + (r1 + 16 * x0), tmp27, xmask)
tl.store(out_ptr3 + (r1 + 16 * x0), tmp29, xmask)
tl.store(out_ptr4 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, 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 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_relu_0[grid(16)](buf0,
buf1, buf5, buf4, 16, 16, XBLOCK=8, num_warps=2, num_stages=1)
buf6 = extern_kernels.convolution(buf5, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 4, 4, 4), (64, 16, 4, 1))
buf7 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32
)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf10 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
triton_per_fused__native_batch_norm_legit_relu_0[grid(16)](buf6,
buf7, buf11, buf10, 16, 16, XBLOCK=8, num_warps=2, num_stages=1)
buf12 = extern_kernels.convolution(buf11, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 4, 4, 4), (64, 16, 4, 1))
buf13 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
buf17 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf18 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf16 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.
float32)
triton_per_fused__native_batch_norm_legit_relu_threshold_backward_1[
grid(16)](buf12, primals_1, buf13, buf17, buf18, buf16, 16, 16,
XBLOCK=1, num_warps=2, num_stages=1)
return (buf17, primals_1, primals_2, primals_3, primals_4, buf0,
reinterpret_tensor(buf4, (16,), (1,), 0), buf5, buf6,
reinterpret_tensor(buf10, (16,), (1,), 0), buf11, buf12,
reinterpret_tensor(buf16, (16,), (1,), 0), buf18,
reinterpret_tensor(buf13, (1, 16, 1, 1), (16, 1, 1, 1), 0),
reinterpret_tensor(buf7, (1, 16, 1, 1), (16, 1, 1, 1), 0),
reinterpret_tensor(buf1, (1, 16, 1, 1), (16, 1, 1, 1), 0))
class ResBlock2New(nn.Module):
def __init__(self, input_feature, planes, dilated=1, group=1):
super(ResBlock2New, self).__init__()
self.conv1 = nn.Conv2d(input_feature, planes, kernel_size=1, bias=
False, groups=group)
self.bn1 = nn.InstanceNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1 *
dilated, bias=False, dilation=dilated, groups=group)
self.bn2 = nn.InstanceNorm2d(planes)
self.conv3 = nn.Conv2d(planes, input_feature, kernel_size=1, bias=
False, groups=group)
self.bn3 = nn.InstanceNorm2d(input_feature)
self.relu = nn.ReLU(inplace=True)
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]
|
chiukin/RANet
|
ResBlock2
| false
| 15,036
|
[
"Apache-2.0"
] | 267
|
681a47d9b1f114653290678f02f2d3ecdf4010bc
|
https://github.com/chiukin/RANet/tree/681a47d9b1f114653290678f02f2d3ecdf4010bc
|
FPNHead
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
class FPNHead(nn.Module):
def __init__(self, num_in, num_mid, num_out):
super().__init__()
self.block0 = nn.Conv2d(num_in, num_mid, kernel_size=3, padding=1,
bias=False)
self.block1 = nn.Conv2d(num_mid, num_out, kernel_size=3, padding=1,
bias=False)
def forward(self, x):
x = nn.functional.relu(self.block0(x), inplace=True)
x = nn.functional.relu(self.block1(x), inplace=True)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_in': 4, 'num_mid': 4, 'num_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
import torch.nn as nn
import torch.nn.parallel
import torch.optim
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_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_relu_threshold_backward_1(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1,
1), padding=(1, 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_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
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256)](buf3, buf4,
256, XBLOCK=128, num_warps=4, num_stages=1)
return buf3, primals_1, primals_2, primals_3, buf1, buf4
class FPNHeadNew(nn.Module):
def __init__(self, num_in, num_mid, num_out):
super().__init__()
self.block0 = nn.Conv2d(num_in, num_mid, kernel_size=3, padding=1,
bias=False)
self.block1 = nn.Conv2d(num_mid, num_out, kernel_size=3, padding=1,
bias=False)
def forward(self, input_0):
primals_1 = self.block0.weight
primals_3 = self.block1.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
choprahetarth/DeblurGANv2
|
FPNHead
| false
| 15,037
|
[
"BSD-3-Clause"
] | 321
|
e36dc2fef169b8a37036abe62192b6a925fb6c81
|
https://github.com/choprahetarth/DeblurGANv2/tree/e36dc2fef169b8a37036abe62192b6a925fb6c81
|
ScaledDotProductAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ScaledDotProductAttention(nn.Module):
""" Scaled Dot-Product Attention """
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=2)
def forward(self, q, k, v):
attn = torch.bmm(q, k.transpose(1, 2))
attn = attn / self.temperature
log_attn = F.log_softmax(attn, 2)
attn = self.softmax(attn)
attn = self.dropout(attn)
output = torch.bmm(attn, v)
return output, attn, log_attn
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'temperature': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, 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
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.25
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x2, tmp17, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__log_softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
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):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(arg1_1, reinterpret_tensor(arg0_1, (4, 4, 4), (
16, 1, 4), 0), out=buf0)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf0, buf1, buf4, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf2 = buf0
del buf0
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf3 = buf1
del buf1
extern_kernels.bmm(buf2, arg2_1, out=buf3)
del arg2_1
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__log_softmax_2[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf4
return buf3, buf2, buf5
class ScaledDotProductAttentionNew(nn.Module):
""" Scaled Dot-Product Attention """
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temperature
self.dropout = nn.Dropout(attn_dropout)
self.softmax = nn.Softmax(dim=2)
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0], output[1], output[2]
|
cjy97/FEAT
|
ScaledDotProductAttention
| false
| 15,038
|
[
"MIT"
] | 330
|
9d48b254bc5f0a2211c2aad0a60388a8a2c8081c
|
https://github.com/cjy97/FEAT/tree/9d48b254bc5f0a2211c2aad0a60388a8a2c8081c
|
MFBFusion
|
from _paritybench_helpers import _mock_config
import time
import torch
from torch import nn
class BaseModel(nn.Module):
def __init__(self):
super(BaseModel, self).__init__()
self.model_name = str(type(self))
def load(self, path):
self.load_state_dict(torch.load(path))
def save(self, name=None):
if name is None:
prefix = 'checkpoints/' + self.model_name + '_'
name = time.strftime(prefix + '%m%d_%H:%M:%S.pth')
torch.save(self.state_dict(), name)
return name
def forward(self, *input):
raise NotImplementedError
class MFBFusion(BaseModel):
def __init__(self, mfb_fusion_option: 'MFBFusionOption'):
super(MFBFusion, self).__init__()
self.out_dim = mfb_fusion_option.outdim
self.linear1 = nn.Linear(mfb_fusion_option.text_size,
mfb_fusion_option.joint_emb_size)
self.linear2 = nn.Linear(mfb_fusion_option.image_size,
mfb_fusion_option.joint_emb_size)
self.dropout = nn.Dropout(p=mfb_fusion_option.dropout)
def forward(self, text_feat, image_feat):
batch_size = text_feat.size(0)
text_proj = self.linear1(text_feat)
image_proj = self.linear2(image_feat)
mm_eltwise = torch.mul(text_proj, image_proj)
mm_drop = self.dropout(mm_eltwise)
mm_resh = mm_drop.view(batch_size, 1, self.out_dim, -1)
mm_sumpool = torch.sum(mm_resh, 3, keepdim=True)
mfb_out = torch.squeeze(mm_sumpool)
return mfb_out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'mfb_fusion_option': _mock_config(outdim=4, text_size=4,
joint_emb_size=4, image_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
import time
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0), 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]
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (64,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((4, 1, 4, 1), (4, 16, 1, 16), torch.float32)
get_raw_stream(0)
triton_per_fused_sum_0[grid(16)](buf0, buf1, buf2, 16, 16, XBLOCK=1,
num_warps=2, num_stages=1)
return reinterpret_tensor(buf2, (4, 4), (4, 1), 0), reinterpret_tensor(
primals_1, (64, 4), (4, 1), 0), buf0, reinterpret_tensor(primals_6,
(64, 4), (4, 1), 0), buf1
class BaseModel(nn.Module):
def __init__(self):
super(BaseModel, self).__init__()
self.model_name = str(type(self))
def load(self, path):
self.load_state_dict(torch.load(path))
def save(self, name=None):
if name is None:
prefix = 'checkpoints/' + self.model_name + '_'
name = time.strftime(prefix + '%m%d_%H:%M:%S.pth')
torch.save(self.state_dict(), name)
return name
def forward(self, *input):
raise NotImplementedError
class MFBFusionNew(BaseModel):
def __init__(self, mfb_fusion_option: 'MFBFusionOption'):
super(MFBFusionNew, self).__init__()
self.out_dim = mfb_fusion_option.outdim
self.linear1 = nn.Linear(mfb_fusion_option.text_size,
mfb_fusion_option.joint_emb_size)
self.linear2 = nn.Linear(mfb_fusion_option.image_size,
mfb_fusion_option.joint_emb_size)
self.dropout = nn.Dropout(p=mfb_fusion_option.dropout)
def forward(self, input_0, input_1):
primals_2 = self.linear1.weight
primals_3 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_1 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
chorseng/UMD
|
MFBFusion
| false
| 15,039
|
[
"MIT"
] | 48
|
680681fea76abcea02ff5f351727bcbb468c372a
|
https://github.com/chorseng/UMD/tree/680681fea76abcea02ff5f351727bcbb468c372a
|
SimpleConvNetBlock
|
import torch
import torch.nn as nn
class SimpleConvNetBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel):
nn.Module.__init__(self)
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel, padding=1)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(2)
def forward(self, x):
y = self.conv(x)
y = self.relu(y)
y = self.maxpool(y)
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 9 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 9 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 9 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (3 + 9 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (4 + 9 * x0), 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 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 3, 3), (36, 9, 3, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(144)](buf1, primals_2, 144,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(16)](buf1, buf2,
buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
return buf2, primals_1, primals_3, buf1, buf3
class SimpleConvNetBlockNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel):
nn.Module.__init__(self)
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel, padding=1)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(2)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
cle-ros/RoutingNetworks
|
SimpleConvNetBlock
| false
| 15,040
|
[
"Apache-2.0"
] | 63
|
0f1fe1221c67a224a02bca6247d3c4488ede0a04
|
https://github.com/cle-ros/RoutingNetworks/tree/0f1fe1221c67a224a02bca6247d3c4488ede0a04
|
PositionwiseFeedForward
|
import math
import torch
from torch import nn
def gelu(x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden layer size of the second-layer
of the FNN.
dropout (float): dropout probability in :math:`[0, 1)`.
"""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)
self.actv = gelu
self.dropout_1 = nn.Dropout(dropout)
self.dropout_2 = nn.Dropout(dropout)
def forward(self, x):
inter = self.dropout_1(self.actv(self.w_1(self.layer_norm(x))))
output = self.dropout_2(self.w_2(inter))
return output + x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'd_ff': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import math
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-06
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x0, tmp8, xmask)
tl.store(out_ptr1 + x0, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 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
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_mul_pow_tanh_2(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = tmp0 * tmp0
tmp4 = tmp3 * tmp0
tmp5 = 0.044715
tmp6 = tmp4 * tmp5
tmp7 = tmp0 + tmp6
tmp8 = 0.7978845608028654
tmp9 = tmp7 * tmp8
tmp10 = libdevice.tanh(tmp9)
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x0, tmp13, xmask)
@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_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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((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_3, 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_1[grid(256)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf0
del buf1
del primals_1
del primals_2
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 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_pow_tanh_2[grid(256)](buf3, buf4, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf5)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused_add_3[grid(256)](buf6, primals_7, primals_3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
return buf6, primals_3, reinterpret_tensor(buf2, (64, 4), (4, 1), 0
), buf3, reinterpret_tensor(buf4, (64, 4), (4, 1), 0
), primals_6, primals_4
def gelu(x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class PositionwiseFeedForwardNew(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden layer size of the second-layer
of the FNN.
dropout (float): dropout probability in :math:`[0, 1)`.
"""
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForwardNew, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.layer_norm = nn.LayerNorm(d_model, eps=1e-06)
self.actv = gelu
self.dropout_1 = nn.Dropout(dropout)
self.dropout_2 = nn.Dropout(dropout)
def forward(self, input_0):
primals_4 = self.w_1.weight
primals_1 = self.w_1.bias
primals_6 = self.w_2.weight
primals_2 = self.w_2.bias
primals_5 = self.layer_norm.weight
primals_7 = self.layer_norm.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
clairett/fast-bert
|
PositionwiseFeedForward
| false
| 15,041
|
[
"Apache-2.0"
] | 1,542
|
506771b930aa70e7ca2852e5e8ebb14656d97bfa
|
https://github.com/clairett/fast-bert/tree/506771b930aa70e7ca2852e5e8ebb14656d97bfa
|
SparsemaxBisect
|
from torch.autograd import Function
import torch
import torch.nn as nn
def sparsemax_bisect(X, dim=-1, n_iter=50, ensure_sum_one=True):
"""sparsemax: normalizing sparse transform (a la softmax), via bisection.
Solves the projection:
min_p ||x - p||_2 s.t. p >= 0, sum(p) == 1.
Parameters
----------
X : torch.Tensor
The input tensor.
dim : int
The dimension along which to apply sparsemax.
n_iter : int
Number of bisection iterations. For float32, 24 iterations should
suffice for machine precision.
ensure_sum_one : bool,
Whether to divide the result by its sum. If false, the result might
sum to close but not exactly 1, which might cause downstream problems.
Note: This function does not yet support normalizing along anything except
the last dimension. Please use transposing and views to achieve more
general behavior.
Returns
-------
P : torch tensor, same shape as X
The projection result, such that P.sum(dim=dim) == 1 elementwise.
"""
return SparsemaxBisectFunction.apply(X, dim, n_iter, ensure_sum_one)
class EntmaxBisectFunction(Function):
@classmethod
def _gp(cls, x, alpha):
return x ** (alpha - 1)
@classmethod
def _gp_inv(cls, y, alpha):
return y ** (1 / (alpha - 1))
@classmethod
def _p(cls, X, alpha):
return cls._gp_inv(torch.clamp(X, min=0), alpha)
@classmethod
def forward(cls, ctx, X, alpha=1.5, dim=-1, n_iter=50, ensure_sum_one=True
):
if not isinstance(alpha, torch.Tensor):
alpha = torch.tensor(alpha, dtype=X.dtype, device=X.device)
alpha_shape = list(X.shape)
alpha_shape[dim] = 1
alpha = alpha.expand(*alpha_shape)
ctx.alpha = alpha
ctx.dim = dim
d = X.shape[dim]
max_val, _ = X.max(dim=dim, keepdim=True)
X = X * (alpha - 1)
max_val = max_val * (alpha - 1)
tau_lo = max_val - cls._gp(1, alpha)
tau_hi = max_val - cls._gp(1 / d, alpha)
f_lo = cls._p(X - tau_lo, alpha).sum(dim) - 1
dm = tau_hi - tau_lo
for it in range(n_iter):
dm /= 2
tau_m = tau_lo + dm
p_m = cls._p(X - tau_m, alpha)
f_m = p_m.sum(dim) - 1
mask = (f_m * f_lo >= 0).unsqueeze(dim)
tau_lo = torch.where(mask, tau_m, tau_lo)
if ensure_sum_one:
p_m /= p_m.sum(dim=dim).unsqueeze(dim=dim)
ctx.save_for_backward(p_m)
return p_m
@classmethod
def backward(cls, ctx, dY):
Y, = ctx.saved_tensors
gppr = torch.where(Y > 0, Y ** (2 - ctx.alpha), Y.new_zeros(1))
dX = dY * gppr
q = dX.sum(ctx.dim) / gppr.sum(ctx.dim)
q = q.unsqueeze(ctx.dim)
dX -= q * gppr
d_alpha = None
if ctx.needs_input_grad[1]:
S = torch.where(Y > 0, Y * torch.log(Y), Y.new_zeros(1))
ent = S.sum(ctx.dim).unsqueeze(ctx.dim)
Y_skewed = gppr / gppr.sum(ctx.dim).unsqueeze(ctx.dim)
d_alpha = dY * (Y - Y_skewed) / (ctx.alpha - 1) ** 2
d_alpha -= dY * (S - Y_skewed * ent) / (ctx.alpha - 1)
d_alpha = d_alpha.sum(ctx.dim).unsqueeze(ctx.dim)
return dX, d_alpha, None, None, None
class SparsemaxBisectFunction(EntmaxBisectFunction):
@classmethod
def _gp(cls, x, alpha):
return x
@classmethod
def _gp_inv(cls, y, alpha):
return y
@classmethod
def _p(cls, x, alpha):
return torch.clamp(x, min=0)
@classmethod
def forward(cls, ctx, X, dim=-1, n_iter=50, ensure_sum_one=True):
return super().forward(ctx, X, alpha=2, dim=dim, n_iter=50,
ensure_sum_one=True)
@classmethod
def backward(cls, ctx, dY):
Y, = ctx.saved_tensors
gppr = Y > 0
dX = dY * gppr
q = dX.sum(ctx.dim) / gppr.sum(ctx.dim)
q = q.unsqueeze(ctx.dim)
dX -= q * gppr
return dX, None, None, None
class SparsemaxBisect(nn.Module):
def __init__(self, dim=-1, n_iter=None):
"""sparsemax: normalizing sparse transform (a la softmax) via bisection
Solves the projection:
min_p ||x - p||_2 s.t. p >= 0, sum(p) == 1.
Parameters
----------
dim : int
The dimension along which to apply sparsemax.
n_iter : int
Number of bisection iterations. For float32, 24 iterations should
suffice for machine precision.
"""
self.dim = dim
self.n_iter = n_iter
super().__init__()
def forward(self, X):
return sparsemax_bisect(X, dim=self.dim, n_iter=self.n_iter)
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.autograd import Function
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_clamp_div_max_mul_sub_sum_where_0(in_out_ptr8,
in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp7 = 1.0
tmp8 = tmp6 - tmp7
tmp9 = 0.25
tmp10 = tmp6 - tmp9
tmp11 = tmp10 - tmp8
tmp12 = 0.5
tmp13 = tmp11 * tmp12
tmp14 = tmp8 + tmp13
tmp15 = tmp0 - tmp14
tmp16 = 0.0
tmp17 = triton_helpers.maximum(tmp15, tmp16)
tmp18 = tmp1 - tmp14
tmp19 = triton_helpers.maximum(tmp18, tmp16)
tmp20 = tmp17 + tmp19
tmp21 = tmp3 - tmp14
tmp22 = triton_helpers.maximum(tmp21, tmp16)
tmp23 = tmp20 + tmp22
tmp24 = tmp5 - tmp14
tmp25 = triton_helpers.maximum(tmp24, tmp16)
tmp26 = tmp23 + tmp25
tmp27 = tmp26 - tmp7
tmp28 = tmp0 - tmp8
tmp29 = triton_helpers.maximum(tmp28, tmp16)
tmp30 = tmp1 - tmp8
tmp31 = triton_helpers.maximum(tmp30, tmp16)
tmp32 = tmp29 + tmp31
tmp33 = tmp3 - tmp8
tmp34 = triton_helpers.maximum(tmp33, tmp16)
tmp35 = tmp32 + tmp34
tmp36 = tmp5 - tmp8
tmp37 = triton_helpers.maximum(tmp36, tmp16)
tmp38 = tmp35 + tmp37
tmp39 = tmp38 - tmp7
tmp40 = tmp27 * tmp39
tmp41 = tmp40 >= tmp16
tmp42 = tl.where(tmp41, tmp14, tmp8)
tmp43 = tmp13 * tmp12
tmp44 = tmp42 + tmp43
tmp45 = tmp0 - tmp44
tmp46 = triton_helpers.maximum(tmp45, tmp16)
tmp47 = tmp1 - tmp44
tmp48 = triton_helpers.maximum(tmp47, tmp16)
tmp49 = tmp46 + tmp48
tmp50 = tmp3 - tmp44
tmp51 = triton_helpers.maximum(tmp50, tmp16)
tmp52 = tmp49 + tmp51
tmp53 = tmp5 - tmp44
tmp54 = triton_helpers.maximum(tmp53, tmp16)
tmp55 = tmp52 + tmp54
tmp56 = tmp55 - tmp7
tmp57 = tmp56 * tmp39
tmp58 = tmp57 >= tmp16
tmp59 = tl.where(tmp58, tmp44, tmp42)
tmp60 = tmp43 * tmp12
tmp61 = tmp59 + tmp60
tmp62 = tmp0 - tmp61
tmp63 = triton_helpers.maximum(tmp62, tmp16)
tmp64 = tmp1 - tmp61
tmp65 = triton_helpers.maximum(tmp64, tmp16)
tmp66 = tmp63 + tmp65
tmp67 = tmp3 - tmp61
tmp68 = triton_helpers.maximum(tmp67, tmp16)
tmp69 = tmp66 + tmp68
tmp70 = tmp5 - tmp61
tmp71 = triton_helpers.maximum(tmp70, tmp16)
tmp72 = tmp69 + tmp71
tmp73 = tmp72 - tmp7
tmp74 = tmp73 * tmp39
tmp75 = tmp74 >= tmp16
tmp76 = tl.where(tmp75, tmp61, tmp59)
tmp77 = tmp60 * tmp12
tmp78 = tmp76 + tmp77
tmp79 = tmp0 - tmp78
tmp80 = triton_helpers.maximum(tmp79, tmp16)
tmp81 = tmp1 - tmp78
tmp82 = triton_helpers.maximum(tmp81, tmp16)
tmp83 = tmp80 + tmp82
tmp84 = tmp3 - tmp78
tmp85 = triton_helpers.maximum(tmp84, tmp16)
tmp86 = tmp83 + tmp85
tmp87 = tmp5 - tmp78
tmp88 = triton_helpers.maximum(tmp87, tmp16)
tmp89 = tmp86 + tmp88
tmp90 = tmp89 - tmp7
tmp91 = tmp90 * tmp39
tmp92 = tmp91 >= tmp16
tmp93 = tl.where(tmp92, tmp78, tmp76)
tmp94 = tmp77 * tmp12
tmp95 = tmp93 + tmp94
tmp96 = tmp0 - tmp95
tmp97 = triton_helpers.maximum(tmp96, tmp16)
tmp98 = tmp1 - tmp95
tmp99 = triton_helpers.maximum(tmp98, tmp16)
tmp100 = tmp97 + tmp99
tmp101 = tmp3 - tmp95
tmp102 = triton_helpers.maximum(tmp101, tmp16)
tmp103 = tmp100 + tmp102
tmp104 = tmp5 - tmp95
tmp105 = triton_helpers.maximum(tmp104, tmp16)
tmp106 = tmp103 + tmp105
tmp107 = tmp106 - tmp7
tmp108 = tmp107 * tmp39
tmp109 = tmp108 >= tmp16
tmp110 = tl.where(tmp109, tmp95, tmp93)
tmp111 = tmp94 * tmp12
tmp112 = tmp110 + tmp111
tmp113 = tmp0 - tmp112
tmp114 = triton_helpers.maximum(tmp113, tmp16)
tmp115 = tmp1 - tmp112
tmp116 = triton_helpers.maximum(tmp115, tmp16)
tmp117 = tmp114 + tmp116
tmp118 = tmp3 - tmp112
tmp119 = triton_helpers.maximum(tmp118, tmp16)
tmp120 = tmp117 + tmp119
tmp121 = tmp5 - tmp112
tmp122 = triton_helpers.maximum(tmp121, tmp16)
tmp123 = tmp120 + tmp122
tmp124 = tmp123 - tmp7
tmp125 = tmp124 * tmp39
tmp126 = tmp125 >= tmp16
tmp127 = tl.where(tmp126, tmp112, tmp110)
tmp128 = tmp111 * tmp12
tmp129 = tmp127 + tmp128
tmp130 = tmp0 - tmp129
tmp131 = triton_helpers.maximum(tmp130, tmp16)
tmp132 = tmp1 - tmp129
tmp133 = triton_helpers.maximum(tmp132, tmp16)
tmp134 = tmp131 + tmp133
tmp135 = tmp3 - tmp129
tmp136 = triton_helpers.maximum(tmp135, tmp16)
tmp137 = tmp134 + tmp136
tmp138 = tmp5 - tmp129
tmp139 = triton_helpers.maximum(tmp138, tmp16)
tmp140 = tmp137 + tmp139
tmp141 = tmp140 - tmp7
tmp142 = tmp141 * tmp39
tmp143 = tmp142 >= tmp16
tmp144 = tl.where(tmp143, tmp129, tmp127)
tmp145 = tmp128 * tmp12
tmp146 = tmp144 + tmp145
tmp147 = tmp0 - tmp146
tmp148 = triton_helpers.maximum(tmp147, tmp16)
tmp149 = tmp1 - tmp146
tmp150 = triton_helpers.maximum(tmp149, tmp16)
tmp151 = tmp148 + tmp150
tmp152 = tmp3 - tmp146
tmp153 = triton_helpers.maximum(tmp152, tmp16)
tmp154 = tmp151 + tmp153
tmp155 = tmp5 - tmp146
tmp156 = triton_helpers.maximum(tmp155, tmp16)
tmp157 = tmp154 + tmp156
tmp158 = tmp157 - tmp7
tmp159 = tmp158 * tmp39
tmp160 = tmp159 >= tmp16
tmp161 = tl.where(tmp160, tmp146, tmp144)
tmp162 = tmp145 * tmp12
tmp163 = tmp161 + tmp162
tmp164 = tmp0 - tmp163
tmp165 = triton_helpers.maximum(tmp164, tmp16)
tmp166 = tmp1 - tmp163
tmp167 = triton_helpers.maximum(tmp166, tmp16)
tmp168 = tmp165 + tmp167
tmp169 = tmp3 - tmp163
tmp170 = triton_helpers.maximum(tmp169, tmp16)
tmp171 = tmp168 + tmp170
tmp172 = tmp5 - tmp163
tmp173 = triton_helpers.maximum(tmp172, tmp16)
tmp174 = tmp171 + tmp173
tmp175 = tmp174 - tmp7
tmp176 = tmp175 * tmp39
tmp177 = tmp176 >= tmp16
tmp178 = tl.where(tmp177, tmp163, tmp161)
tmp179 = tmp162 * tmp12
tmp180 = tmp178 + tmp179
tmp181 = tmp0 - tmp180
tmp182 = triton_helpers.maximum(tmp181, tmp16)
tmp183 = tmp1 - tmp180
tmp184 = triton_helpers.maximum(tmp183, tmp16)
tmp185 = tmp182 + tmp184
tmp186 = tmp3 - tmp180
tmp187 = triton_helpers.maximum(tmp186, tmp16)
tmp188 = tmp185 + tmp187
tmp189 = tmp5 - tmp180
tmp190 = triton_helpers.maximum(tmp189, tmp16)
tmp191 = tmp188 + tmp190
tmp192 = tmp191 - tmp7
tmp193 = tmp192 * tmp39
tmp194 = tmp193 >= tmp16
tmp195 = tl.where(tmp194, tmp180, tmp178)
tmp196 = tmp179 * tmp12
tmp197 = tmp195 + tmp196
tmp198 = tmp0 - tmp197
tmp199 = triton_helpers.maximum(tmp198, tmp16)
tmp200 = tmp1 - tmp197
tmp201 = triton_helpers.maximum(tmp200, tmp16)
tmp202 = tmp199 + tmp201
tmp203 = tmp3 - tmp197
tmp204 = triton_helpers.maximum(tmp203, tmp16)
tmp205 = tmp202 + tmp204
tmp206 = tmp5 - tmp197
tmp207 = triton_helpers.maximum(tmp206, tmp16)
tmp208 = tmp205 + tmp207
tmp209 = tmp208 - tmp7
tmp210 = tmp209 * tmp39
tmp211 = tmp210 >= tmp16
tmp212 = tl.where(tmp211, tmp197, tmp195)
tmp213 = tmp196 * tmp12
tmp214 = tmp212 + tmp213
tmp215 = tmp0 - tmp214
tmp216 = triton_helpers.maximum(tmp215, tmp16)
tmp217 = tmp1 - tmp214
tmp218 = triton_helpers.maximum(tmp217, tmp16)
tmp219 = tmp216 + tmp218
tmp220 = tmp3 - tmp214
tmp221 = triton_helpers.maximum(tmp220, tmp16)
tmp222 = tmp219 + tmp221
tmp223 = tmp5 - tmp214
tmp224 = triton_helpers.maximum(tmp223, tmp16)
tmp225 = tmp222 + tmp224
tmp226 = tmp225 - tmp7
tmp227 = tmp226 * tmp39
tmp228 = tmp227 >= tmp16
tmp229 = tl.where(tmp228, tmp214, tmp212)
tmp230 = tmp213 * tmp12
tmp231 = tmp229 + tmp230
tmp232 = tmp0 - tmp231
tmp233 = triton_helpers.maximum(tmp232, tmp16)
tmp234 = tmp1 - tmp231
tmp235 = triton_helpers.maximum(tmp234, tmp16)
tmp236 = tmp233 + tmp235
tmp237 = tmp3 - tmp231
tmp238 = triton_helpers.maximum(tmp237, tmp16)
tmp239 = tmp236 + tmp238
tmp240 = tmp5 - tmp231
tmp241 = triton_helpers.maximum(tmp240, tmp16)
tmp242 = tmp239 + tmp241
tmp243 = tmp242 - tmp7
tmp244 = tmp243 * tmp39
tmp245 = tmp244 >= tmp16
tmp246 = tl.where(tmp245, tmp231, tmp229)
tmp247 = tmp230 * tmp12
tmp248 = tmp246 + tmp247
tmp249 = tmp0 - tmp248
tmp250 = triton_helpers.maximum(tmp249, tmp16)
tmp251 = tmp1 - tmp248
tmp252 = triton_helpers.maximum(tmp251, tmp16)
tmp253 = tmp250 + tmp252
tmp254 = tmp3 - tmp248
tmp255 = triton_helpers.maximum(tmp254, tmp16)
tmp256 = tmp253 + tmp255
tmp257 = tmp5 - tmp248
tmp258 = triton_helpers.maximum(tmp257, tmp16)
tmp259 = tmp256 + tmp258
tmp260 = tmp259 - tmp7
tmp261 = tmp260 * tmp39
tmp262 = tmp261 >= tmp16
tmp263 = tl.where(tmp262, tmp248, tmp246)
tmp264 = tmp247 * tmp12
tmp265 = tmp263 + tmp264
tmp266 = tmp0 - tmp265
tmp267 = triton_helpers.maximum(tmp266, tmp16)
tmp268 = tmp1 - tmp265
tmp269 = triton_helpers.maximum(tmp268, tmp16)
tmp270 = tmp267 + tmp269
tmp271 = tmp3 - tmp265
tmp272 = triton_helpers.maximum(tmp271, tmp16)
tmp273 = tmp270 + tmp272
tmp274 = tmp5 - tmp265
tmp275 = triton_helpers.maximum(tmp274, tmp16)
tmp276 = tmp273 + tmp275
tmp277 = tmp276 - tmp7
tmp278 = tmp277 * tmp39
tmp279 = tmp278 >= tmp16
tmp280 = tl.where(tmp279, tmp265, tmp263)
tmp281 = tmp264 * tmp12
tmp282 = tmp280 + tmp281
tmp283 = tmp0 - tmp282
tmp284 = triton_helpers.maximum(tmp283, tmp16)
tmp285 = tmp1 - tmp282
tmp286 = triton_helpers.maximum(tmp285, tmp16)
tmp287 = tmp284 + tmp286
tmp288 = tmp3 - tmp282
tmp289 = triton_helpers.maximum(tmp288, tmp16)
tmp290 = tmp287 + tmp289
tmp291 = tmp5 - tmp282
tmp292 = triton_helpers.maximum(tmp291, tmp16)
tmp293 = tmp290 + tmp292
tmp294 = tmp293 - tmp7
tmp295 = tmp294 * tmp39
tmp296 = tmp295 >= tmp16
tmp297 = tl.where(tmp296, tmp282, tmp280)
tmp298 = tmp281 * tmp12
tmp299 = tmp297 + tmp298
tmp300 = tmp0 - tmp299
tmp301 = triton_helpers.maximum(tmp300, tmp16)
tmp302 = tmp1 - tmp299
tmp303 = triton_helpers.maximum(tmp302, tmp16)
tmp304 = tmp301 + tmp303
tmp305 = tmp3 - tmp299
tmp306 = triton_helpers.maximum(tmp305, tmp16)
tmp307 = tmp304 + tmp306
tmp308 = tmp5 - tmp299
tmp309 = triton_helpers.maximum(tmp308, tmp16)
tmp310 = tmp307 + tmp309
tmp311 = tmp310 - tmp7
tmp312 = tmp311 * tmp39
tmp313 = tmp312 >= tmp16
tmp314 = tl.where(tmp313, tmp299, tmp297)
tl.store(in_out_ptr8 + x0, tmp314, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_1(in_out_ptr16,
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr1 + x0, xmask)
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp7 = 0.25
tmp8 = tmp6 - tmp7
tmp9 = 1.0
tmp10 = tmp6 - tmp9
tmp11 = tmp8 - tmp10
tmp12 = 0.5
tmp13 = tmp11 * tmp12
tmp14 = tmp13 * tmp12
tmp15 = tmp14 * tmp12
tmp16 = tmp15 * tmp12
tmp17 = tmp16 * tmp12
tmp18 = tmp17 * tmp12
tmp19 = tmp18 * tmp12
tmp20 = tmp19 * tmp12
tmp21 = tmp20 * tmp12
tmp22 = tmp21 * tmp12
tmp23 = tmp22 * tmp12
tmp24 = tmp23 * tmp12
tmp25 = tmp24 * tmp12
tmp26 = tmp25 * tmp12
tmp27 = tmp26 * tmp12
tmp28 = tmp27 * tmp12
tmp29 = tmp28 * tmp12
tmp30 = tmp29 * tmp12
tmp32 = tmp31 + tmp30
tmp33 = tmp0 - tmp32
tmp34 = 0.0
tmp35 = triton_helpers.maximum(tmp33, tmp34)
tmp36 = tmp1 - tmp32
tmp37 = triton_helpers.maximum(tmp36, tmp34)
tmp38 = tmp35 + tmp37
tmp39 = tmp3 - tmp32
tmp40 = triton_helpers.maximum(tmp39, tmp34)
tmp41 = tmp38 + tmp40
tmp42 = tmp5 - tmp32
tmp43 = triton_helpers.maximum(tmp42, tmp34)
tmp44 = tmp41 + tmp43
tmp45 = tmp44 - tmp9
tmp46 = tmp0 - tmp10
tmp47 = triton_helpers.maximum(tmp46, tmp34)
tmp48 = tmp1 - tmp10
tmp49 = triton_helpers.maximum(tmp48, tmp34)
tmp50 = tmp47 + tmp49
tmp51 = tmp3 - tmp10
tmp52 = triton_helpers.maximum(tmp51, tmp34)
tmp53 = tmp50 + tmp52
tmp54 = tmp5 - tmp10
tmp55 = triton_helpers.maximum(tmp54, tmp34)
tmp56 = tmp53 + tmp55
tmp57 = tmp56 - tmp9
tmp58 = tmp45 * tmp57
tmp59 = tmp58 >= tmp34
tmp60 = tl.where(tmp59, tmp32, tmp31)
tmp61 = tmp30 * tmp12
tmp62 = tmp60 + tmp61
tmp63 = tmp0 - tmp62
tmp64 = triton_helpers.maximum(tmp63, tmp34)
tmp65 = tmp1 - tmp62
tmp66 = triton_helpers.maximum(tmp65, tmp34)
tmp67 = tmp64 + tmp66
tmp68 = tmp3 - tmp62
tmp69 = triton_helpers.maximum(tmp68, tmp34)
tmp70 = tmp67 + tmp69
tmp71 = tmp5 - tmp62
tmp72 = triton_helpers.maximum(tmp71, tmp34)
tmp73 = tmp70 + tmp72
tmp74 = tmp73 - tmp9
tmp75 = tmp74 * tmp57
tmp76 = tmp75 >= tmp34
tmp77 = tl.where(tmp76, tmp62, tmp60)
tmp78 = tmp61 * tmp12
tmp79 = tmp77 + tmp78
tmp80 = tmp0 - tmp79
tmp81 = triton_helpers.maximum(tmp80, tmp34)
tmp82 = tmp1 - tmp79
tmp83 = triton_helpers.maximum(tmp82, tmp34)
tmp84 = tmp81 + tmp83
tmp85 = tmp3 - tmp79
tmp86 = triton_helpers.maximum(tmp85, tmp34)
tmp87 = tmp84 + tmp86
tmp88 = tmp5 - tmp79
tmp89 = triton_helpers.maximum(tmp88, tmp34)
tmp90 = tmp87 + tmp89
tmp91 = tmp90 - tmp9
tmp92 = tmp91 * tmp57
tmp93 = tmp92 >= tmp34
tmp94 = tl.where(tmp93, tmp79, tmp77)
tmp95 = tmp78 * tmp12
tmp96 = tmp94 + tmp95
tmp97 = tmp0 - tmp96
tmp98 = triton_helpers.maximum(tmp97, tmp34)
tmp99 = tmp1 - tmp96
tmp100 = triton_helpers.maximum(tmp99, tmp34)
tmp101 = tmp98 + tmp100
tmp102 = tmp3 - tmp96
tmp103 = triton_helpers.maximum(tmp102, tmp34)
tmp104 = tmp101 + tmp103
tmp105 = tmp5 - tmp96
tmp106 = triton_helpers.maximum(tmp105, tmp34)
tmp107 = tmp104 + tmp106
tmp108 = tmp107 - tmp9
tmp109 = tmp108 * tmp57
tmp110 = tmp109 >= tmp34
tmp111 = tl.where(tmp110, tmp96, tmp94)
tmp112 = tmp95 * tmp12
tmp113 = tmp111 + tmp112
tmp114 = tmp0 - tmp113
tmp115 = triton_helpers.maximum(tmp114, tmp34)
tmp116 = tmp1 - tmp113
tmp117 = triton_helpers.maximum(tmp116, tmp34)
tmp118 = tmp115 + tmp117
tmp119 = tmp3 - tmp113
tmp120 = triton_helpers.maximum(tmp119, tmp34)
tmp121 = tmp118 + tmp120
tmp122 = tmp5 - tmp113
tmp123 = triton_helpers.maximum(tmp122, tmp34)
tmp124 = tmp121 + tmp123
tmp125 = tmp124 - tmp9
tmp126 = tmp125 * tmp57
tmp127 = tmp126 >= tmp34
tmp128 = tl.where(tmp127, tmp113, tmp111)
tmp129 = tmp112 * tmp12
tmp130 = tmp128 + tmp129
tmp131 = tmp0 - tmp130
tmp132 = triton_helpers.maximum(tmp131, tmp34)
tmp133 = tmp1 - tmp130
tmp134 = triton_helpers.maximum(tmp133, tmp34)
tmp135 = tmp132 + tmp134
tmp136 = tmp3 - tmp130
tmp137 = triton_helpers.maximum(tmp136, tmp34)
tmp138 = tmp135 + tmp137
tmp139 = tmp5 - tmp130
tmp140 = triton_helpers.maximum(tmp139, tmp34)
tmp141 = tmp138 + tmp140
tmp142 = tmp141 - tmp9
tmp143 = tmp142 * tmp57
tmp144 = tmp143 >= tmp34
tmp145 = tl.where(tmp144, tmp130, tmp128)
tmp146 = tmp129 * tmp12
tmp147 = tmp145 + tmp146
tmp148 = tmp0 - tmp147
tmp149 = triton_helpers.maximum(tmp148, tmp34)
tmp150 = tmp1 - tmp147
tmp151 = triton_helpers.maximum(tmp150, tmp34)
tmp152 = tmp149 + tmp151
tmp153 = tmp3 - tmp147
tmp154 = triton_helpers.maximum(tmp153, tmp34)
tmp155 = tmp152 + tmp154
tmp156 = tmp5 - tmp147
tmp157 = triton_helpers.maximum(tmp156, tmp34)
tmp158 = tmp155 + tmp157
tmp159 = tmp158 - tmp9
tmp160 = tmp159 * tmp57
tmp161 = tmp160 >= tmp34
tmp162 = tl.where(tmp161, tmp147, tmp145)
tmp163 = tmp146 * tmp12
tmp164 = tmp162 + tmp163
tmp165 = tmp0 - tmp164
tmp166 = triton_helpers.maximum(tmp165, tmp34)
tmp167 = tmp1 - tmp164
tmp168 = triton_helpers.maximum(tmp167, tmp34)
tmp169 = tmp166 + tmp168
tmp170 = tmp3 - tmp164
tmp171 = triton_helpers.maximum(tmp170, tmp34)
tmp172 = tmp169 + tmp171
tmp173 = tmp5 - tmp164
tmp174 = triton_helpers.maximum(tmp173, tmp34)
tmp175 = tmp172 + tmp174
tmp176 = tmp175 - tmp9
tmp177 = tmp176 * tmp57
tmp178 = tmp177 >= tmp34
tmp179 = tl.where(tmp178, tmp164, tmp162)
tmp180 = tmp163 * tmp12
tmp181 = tmp179 + tmp180
tmp182 = tmp0 - tmp181
tmp183 = triton_helpers.maximum(tmp182, tmp34)
tmp184 = tmp1 - tmp181
tmp185 = triton_helpers.maximum(tmp184, tmp34)
tmp186 = tmp183 + tmp185
tmp187 = tmp3 - tmp181
tmp188 = triton_helpers.maximum(tmp187, tmp34)
tmp189 = tmp186 + tmp188
tmp190 = tmp5 - tmp181
tmp191 = triton_helpers.maximum(tmp190, tmp34)
tmp192 = tmp189 + tmp191
tmp193 = tmp192 - tmp9
tmp194 = tmp193 * tmp57
tmp195 = tmp194 >= tmp34
tmp196 = tl.where(tmp195, tmp181, tmp179)
tmp197 = tmp180 * tmp12
tmp198 = tmp196 + tmp197
tmp199 = tmp0 - tmp198
tmp200 = triton_helpers.maximum(tmp199, tmp34)
tmp201 = tmp1 - tmp198
tmp202 = triton_helpers.maximum(tmp201, tmp34)
tmp203 = tmp200 + tmp202
tmp204 = tmp3 - tmp198
tmp205 = triton_helpers.maximum(tmp204, tmp34)
tmp206 = tmp203 + tmp205
tmp207 = tmp5 - tmp198
tmp208 = triton_helpers.maximum(tmp207, tmp34)
tmp209 = tmp206 + tmp208
tmp210 = tmp209 - tmp9
tmp211 = tmp210 * tmp57
tmp212 = tmp211 >= tmp34
tmp213 = tl.where(tmp212, tmp198, tmp196)
tmp214 = tmp197 * tmp12
tmp215 = tmp213 + tmp214
tmp216 = tmp0 - tmp215
tmp217 = triton_helpers.maximum(tmp216, tmp34)
tmp218 = tmp1 - tmp215
tmp219 = triton_helpers.maximum(tmp218, tmp34)
tmp220 = tmp217 + tmp219
tmp221 = tmp3 - tmp215
tmp222 = triton_helpers.maximum(tmp221, tmp34)
tmp223 = tmp220 + tmp222
tmp224 = tmp5 - tmp215
tmp225 = triton_helpers.maximum(tmp224, tmp34)
tmp226 = tmp223 + tmp225
tmp227 = tmp226 - tmp9
tmp228 = tmp227 * tmp57
tmp229 = tmp228 >= tmp34
tmp230 = tl.where(tmp229, tmp215, tmp213)
tmp231 = tmp214 * tmp12
tmp232 = tmp230 + tmp231
tmp233 = tmp0 - tmp232
tmp234 = triton_helpers.maximum(tmp233, tmp34)
tmp235 = tmp1 - tmp232
tmp236 = triton_helpers.maximum(tmp235, tmp34)
tmp237 = tmp234 + tmp236
tmp238 = tmp3 - tmp232
tmp239 = triton_helpers.maximum(tmp238, tmp34)
tmp240 = tmp237 + tmp239
tmp241 = tmp5 - tmp232
tmp242 = triton_helpers.maximum(tmp241, tmp34)
tmp243 = tmp240 + tmp242
tmp244 = tmp243 - tmp9
tmp245 = tmp244 * tmp57
tmp246 = tmp245 >= tmp34
tmp247 = tl.where(tmp246, tmp232, tmp230)
tmp248 = tmp231 * tmp12
tmp249 = tmp247 + tmp248
tmp250 = tmp0 - tmp249
tmp251 = triton_helpers.maximum(tmp250, tmp34)
tmp252 = tmp1 - tmp249
tmp253 = triton_helpers.maximum(tmp252, tmp34)
tmp254 = tmp251 + tmp253
tmp255 = tmp3 - tmp249
tmp256 = triton_helpers.maximum(tmp255, tmp34)
tmp257 = tmp254 + tmp256
tmp258 = tmp5 - tmp249
tmp259 = triton_helpers.maximum(tmp258, tmp34)
tmp260 = tmp257 + tmp259
tmp261 = tmp260 - tmp9
tmp262 = tmp261 * tmp57
tmp263 = tmp262 >= tmp34
tmp264 = tl.where(tmp263, tmp249, tmp247)
tmp265 = tmp248 * tmp12
tmp266 = tmp264 + tmp265
tmp267 = tmp0 - tmp266
tmp268 = triton_helpers.maximum(tmp267, tmp34)
tmp269 = tmp1 - tmp266
tmp270 = triton_helpers.maximum(tmp269, tmp34)
tmp271 = tmp268 + tmp270
tmp272 = tmp3 - tmp266
tmp273 = triton_helpers.maximum(tmp272, tmp34)
tmp274 = tmp271 + tmp273
tmp275 = tmp5 - tmp266
tmp276 = triton_helpers.maximum(tmp275, tmp34)
tmp277 = tmp274 + tmp276
tmp278 = tmp277 - tmp9
tmp279 = tmp278 * tmp57
tmp280 = tmp279 >= tmp34
tmp281 = tl.where(tmp280, tmp266, tmp264)
tmp282 = tmp265 * tmp12
tmp283 = tmp281 + tmp282
tmp284 = tmp0 - tmp283
tmp285 = triton_helpers.maximum(tmp284, tmp34)
tmp286 = tmp1 - tmp283
tmp287 = triton_helpers.maximum(tmp286, tmp34)
tmp288 = tmp285 + tmp287
tmp289 = tmp3 - tmp283
tmp290 = triton_helpers.maximum(tmp289, tmp34)
tmp291 = tmp288 + tmp290
tmp292 = tmp5 - tmp283
tmp293 = triton_helpers.maximum(tmp292, tmp34)
tmp294 = tmp291 + tmp293
tmp295 = tmp294 - tmp9
tmp296 = tmp295 * tmp57
tmp297 = tmp296 >= tmp34
tmp298 = tl.where(tmp297, tmp283, tmp281)
tmp299 = tmp282 * tmp12
tmp300 = tmp298 + tmp299
tmp301 = tmp0 - tmp300
tmp302 = triton_helpers.maximum(tmp301, tmp34)
tmp303 = tmp1 - tmp300
tmp304 = triton_helpers.maximum(tmp303, tmp34)
tmp305 = tmp302 + tmp304
tmp306 = tmp3 - tmp300
tmp307 = triton_helpers.maximum(tmp306, tmp34)
tmp308 = tmp305 + tmp307
tmp309 = tmp5 - tmp300
tmp310 = triton_helpers.maximum(tmp309, tmp34)
tmp311 = tmp308 + tmp310
tmp312 = tmp311 - tmp9
tmp313 = tmp312 * tmp57
tmp314 = tmp313 >= tmp34
tmp315 = tl.where(tmp314, tmp300, tmp298)
tmp316 = tmp299 * tmp12
tmp317 = tmp315 + tmp316
tmp318 = tmp0 - tmp317
tmp319 = triton_helpers.maximum(tmp318, tmp34)
tmp320 = tmp1 - tmp317
tmp321 = triton_helpers.maximum(tmp320, tmp34)
tmp322 = tmp319 + tmp321
tmp323 = tmp3 - tmp317
tmp324 = triton_helpers.maximum(tmp323, tmp34)
tmp325 = tmp322 + tmp324
tmp326 = tmp5 - tmp317
tmp327 = triton_helpers.maximum(tmp326, tmp34)
tmp328 = tmp325 + tmp327
tmp329 = tmp328 - tmp9
tmp330 = tmp329 * tmp57
tmp331 = tmp330 >= tmp34
tmp332 = tl.where(tmp331, tmp317, tmp315)
tmp333 = tmp316 * tmp12
tmp334 = tmp332 + tmp333
tmp335 = tmp0 - tmp334
tmp336 = triton_helpers.maximum(tmp335, tmp34)
tmp337 = tmp1 - tmp334
tmp338 = triton_helpers.maximum(tmp337, tmp34)
tmp339 = tmp336 + tmp338
tmp340 = tmp3 - tmp334
tmp341 = triton_helpers.maximum(tmp340, tmp34)
tmp342 = tmp339 + tmp341
tmp343 = tmp5 - tmp334
tmp344 = triton_helpers.maximum(tmp343, tmp34)
tmp345 = tmp342 + tmp344
tmp346 = tmp345 - tmp9
tmp347 = tmp346 * tmp57
tmp348 = tmp347 >= tmp34
tmp349 = tl.where(tmp348, tmp334, tmp332)
tmp350 = tmp333 * tmp12
tmp351 = tmp349 + tmp350
tmp352 = tmp0 - tmp351
tmp353 = triton_helpers.maximum(tmp352, tmp34)
tmp354 = tmp1 - tmp351
tmp355 = triton_helpers.maximum(tmp354, tmp34)
tmp356 = tmp353 + tmp355
tmp357 = tmp3 - tmp351
tmp358 = triton_helpers.maximum(tmp357, tmp34)
tmp359 = tmp356 + tmp358
tmp360 = tmp5 - tmp351
tmp361 = triton_helpers.maximum(tmp360, tmp34)
tmp362 = tmp359 + tmp361
tmp363 = tmp362 - tmp9
tmp364 = tmp363 * tmp57
tmp365 = tmp364 >= tmp34
tmp366 = tl.where(tmp365, tmp351, tmp349)
tmp367 = tmp350 * tmp12
tmp368 = tmp366 + tmp367
tmp369 = tmp0 - tmp368
tmp370 = triton_helpers.maximum(tmp369, tmp34)
tmp371 = tmp1 - tmp368
tmp372 = triton_helpers.maximum(tmp371, tmp34)
tmp373 = tmp370 + tmp372
tmp374 = tmp3 - tmp368
tmp375 = triton_helpers.maximum(tmp374, tmp34)
tmp376 = tmp373 + tmp375
tmp377 = tmp5 - tmp368
tmp378 = triton_helpers.maximum(tmp377, tmp34)
tmp379 = tmp376 + tmp378
tmp380 = tmp379 - tmp9
tmp381 = tmp380 * tmp57
tmp382 = tmp381 >= tmp34
tmp383 = tl.where(tmp382, tmp368, tmp366)
tmp384 = tmp367 * tmp12
tmp385 = tmp383 + tmp384
tmp386 = tmp0 - tmp385
tmp387 = triton_helpers.maximum(tmp386, tmp34)
tmp388 = tmp1 - tmp385
tmp389 = triton_helpers.maximum(tmp388, tmp34)
tmp390 = tmp387 + tmp389
tmp391 = tmp3 - tmp385
tmp392 = triton_helpers.maximum(tmp391, tmp34)
tmp393 = tmp390 + tmp392
tmp394 = tmp5 - tmp385
tmp395 = triton_helpers.maximum(tmp394, tmp34)
tmp396 = tmp393 + tmp395
tmp397 = tmp396 - tmp9
tmp398 = tmp397 * tmp57
tmp399 = tmp398 >= tmp34
tmp400 = tl.where(tmp399, tmp385, tmp383)
tmp401 = tmp384 * tmp12
tmp402 = tmp400 + tmp401
tmp403 = tmp0 - tmp402
tmp404 = triton_helpers.maximum(tmp403, tmp34)
tmp405 = tmp1 - tmp402
tmp406 = triton_helpers.maximum(tmp405, tmp34)
tmp407 = tmp404 + tmp406
tmp408 = tmp3 - tmp402
tmp409 = triton_helpers.maximum(tmp408, tmp34)
tmp410 = tmp407 + tmp409
tmp411 = tmp5 - tmp402
tmp412 = triton_helpers.maximum(tmp411, tmp34)
tmp413 = tmp410 + tmp412
tmp414 = tmp413 - tmp9
tmp415 = tmp414 * tmp57
tmp416 = tmp415 >= tmp34
tmp417 = tl.where(tmp416, tmp402, tmp400)
tmp418 = tmp401 * tmp12
tmp419 = tmp417 + tmp418
tmp420 = tmp0 - tmp419
tmp421 = triton_helpers.maximum(tmp420, tmp34)
tmp422 = tmp1 - tmp419
tmp423 = triton_helpers.maximum(tmp422, tmp34)
tmp424 = tmp421 + tmp423
tmp425 = tmp3 - tmp419
tmp426 = triton_helpers.maximum(tmp425, tmp34)
tmp427 = tmp424 + tmp426
tmp428 = tmp5 - tmp419
tmp429 = triton_helpers.maximum(tmp428, tmp34)
tmp430 = tmp427 + tmp429
tmp431 = tmp430 - tmp9
tmp432 = tmp431 * tmp57
tmp433 = tmp432 >= tmp34
tmp434 = tl.where(tmp433, tmp419, tmp417)
tl.store(out_ptr0 + x0, tmp30, xmask)
tl.store(in_out_ptr16 + x0, tmp434, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_sub_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp6 * tmp3
tmp8 = tmp7 * tmp3
tmp9 = tmp8 * tmp3
tmp10 = tmp9 * tmp3
tmp11 = tmp10 * tmp3
tmp12 = tmp11 * tmp3
tmp13 = tmp12 * tmp3
tmp14 = tmp13 * tmp3
tmp15 = tmp14 * tmp3
tmp16 = tmp15 * tmp3
tmp17 = tmp16 * tmp3
tmp18 = tmp17 * tmp3
tmp19 = tmp18 * tmp3
tmp20 = tmp19 * tmp3
tmp21 = tmp20 * tmp3
tmp22 = tmp21 * tmp3
tmp23 = tmp22 * tmp3
tmp24 = tmp23 * tmp3
tmp25 = tmp24 * tmp3
tmp26 = tmp25 * tmp3
tmp27 = tmp1 + tmp26
tmp28 = tmp0 - tmp27
tmp29 = 0.0
tmp30 = triton_helpers.maximum(tmp28, tmp29)
tl.store(out_ptr0 + x2, tmp30, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_3(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp9 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp32 = tl.load(in_out_ptr0 + x0, xmask)
tmp33 = tl.load(in_ptr2 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 1.0
tmp8 = tmp6 - tmp7
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp13 = triton_helpers.maximum(tmp11, tmp12)
tmp15 = triton_helpers.maximum(tmp13, tmp14)
tmp16 = tmp15 - tmp7
tmp17 = tmp9 - tmp16
tmp18 = 0.0
tmp19 = triton_helpers.maximum(tmp17, tmp18)
tmp20 = tmp10 - tmp16
tmp21 = triton_helpers.maximum(tmp20, tmp18)
tmp22 = tmp19 + tmp21
tmp23 = tmp12 - tmp16
tmp24 = triton_helpers.maximum(tmp23, tmp18)
tmp25 = tmp22 + tmp24
tmp26 = tmp14 - tmp16
tmp27 = triton_helpers.maximum(tmp26, tmp18)
tmp28 = tmp25 + tmp27
tmp29 = tmp28 - tmp7
tmp30 = tmp8 * tmp29
tmp31 = tmp30 >= tmp18
tmp34 = 0.5
tmp35 = tmp33 * tmp34
tmp36 = tmp35 * tmp34
tmp37 = tmp36 * tmp34
tmp38 = tmp37 * tmp34
tmp39 = tmp38 * tmp34
tmp40 = tmp39 * tmp34
tmp41 = tmp40 * tmp34
tmp42 = tmp41 * tmp34
tmp43 = tmp42 * tmp34
tmp44 = tmp43 * tmp34
tmp45 = tmp44 * tmp34
tmp46 = tmp45 * tmp34
tmp47 = tmp46 * tmp34
tmp48 = tmp47 * tmp34
tmp49 = tmp48 * tmp34
tmp50 = tmp49 * tmp34
tmp51 = tmp50 * tmp34
tmp52 = tmp51 * tmp34
tmp53 = tmp52 * tmp34
tmp54 = tmp53 * tmp34
tmp55 = tmp54 * tmp34
tmp56 = tmp55 * tmp34
tmp57 = tmp56 * tmp34
tmp58 = tmp32 + tmp57
tmp59 = tl.where(tmp31, tmp58, tmp32)
tl.store(in_out_ptr0 + x0, tmp59, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_sub_4(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp6 * tmp3
tmp8 = tmp7 * tmp3
tmp9 = tmp8 * tmp3
tmp10 = tmp9 * tmp3
tmp11 = tmp10 * tmp3
tmp12 = tmp11 * tmp3
tmp13 = tmp12 * tmp3
tmp14 = tmp13 * tmp3
tmp15 = tmp14 * tmp3
tmp16 = tmp15 * tmp3
tmp17 = tmp16 * tmp3
tmp18 = tmp17 * tmp3
tmp19 = tmp18 * tmp3
tmp20 = tmp19 * tmp3
tmp21 = tmp20 * tmp3
tmp22 = tmp21 * tmp3
tmp23 = tmp22 * tmp3
tmp24 = tmp23 * tmp3
tmp25 = tmp24 * tmp3
tmp26 = tmp25 * tmp3
tmp27 = tmp26 * tmp3
tmp28 = tmp1 + tmp27
tmp29 = tmp0 - tmp28
tmp30 = 0.0
tmp31 = triton_helpers.maximum(tmp29, tmp30)
tl.store(out_ptr0 + x2, tmp31, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_5(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp9 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp32 = tl.load(in_out_ptr0 + x0, xmask)
tmp33 = tl.load(in_ptr2 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 1.0
tmp8 = tmp6 - tmp7
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp13 = triton_helpers.maximum(tmp11, tmp12)
tmp15 = triton_helpers.maximum(tmp13, tmp14)
tmp16 = tmp15 - tmp7
tmp17 = tmp9 - tmp16
tmp18 = 0.0
tmp19 = triton_helpers.maximum(tmp17, tmp18)
tmp20 = tmp10 - tmp16
tmp21 = triton_helpers.maximum(tmp20, tmp18)
tmp22 = tmp19 + tmp21
tmp23 = tmp12 - tmp16
tmp24 = triton_helpers.maximum(tmp23, tmp18)
tmp25 = tmp22 + tmp24
tmp26 = tmp14 - tmp16
tmp27 = triton_helpers.maximum(tmp26, tmp18)
tmp28 = tmp25 + tmp27
tmp29 = tmp28 - tmp7
tmp30 = tmp8 * tmp29
tmp31 = tmp30 >= tmp18
tmp34 = 0.5
tmp35 = tmp33 * tmp34
tmp36 = tmp35 * tmp34
tmp37 = tmp36 * tmp34
tmp38 = tmp37 * tmp34
tmp39 = tmp38 * tmp34
tmp40 = tmp39 * tmp34
tmp41 = tmp40 * tmp34
tmp42 = tmp41 * tmp34
tmp43 = tmp42 * tmp34
tmp44 = tmp43 * tmp34
tmp45 = tmp44 * tmp34
tmp46 = tmp45 * tmp34
tmp47 = tmp46 * tmp34
tmp48 = tmp47 * tmp34
tmp49 = tmp48 * tmp34
tmp50 = tmp49 * tmp34
tmp51 = tmp50 * tmp34
tmp52 = tmp51 * tmp34
tmp53 = tmp52 * tmp34
tmp54 = tmp53 * tmp34
tmp55 = tmp54 * tmp34
tmp56 = tmp55 * tmp34
tmp57 = tmp56 * tmp34
tmp58 = tmp57 * tmp34
tmp59 = tmp32 + tmp58
tmp60 = tl.where(tmp31, tmp59, tmp32)
tl.store(in_out_ptr0 + x0, tmp60, xmask)
@triton.jit
def triton_poi_fused_add_div_sub_6(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp6 * tmp3
tmp8 = tmp7 * tmp3
tmp9 = tmp8 * tmp3
tmp10 = tmp9 * tmp3
tmp11 = tmp10 * tmp3
tmp12 = tmp11 * tmp3
tmp13 = tmp12 * tmp3
tmp14 = tmp13 * tmp3
tmp15 = tmp14 * tmp3
tmp16 = tmp15 * tmp3
tmp17 = tmp16 * tmp3
tmp18 = tmp17 * tmp3
tmp19 = tmp18 * tmp3
tmp20 = tmp19 * tmp3
tmp21 = tmp20 * tmp3
tmp22 = tmp21 * tmp3
tmp23 = tmp22 * tmp3
tmp24 = tmp23 * tmp3
tmp25 = tmp24 * tmp3
tmp26 = tmp25 * tmp3
tmp27 = tmp26 * tmp3
tmp28 = tmp27 * tmp3
tmp29 = tmp1 + tmp28
tmp30 = tmp0 - tmp29
tl.store(out_ptr0 + x2, tmp30, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_7(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_out_ptr0 + x0, xmask)
tmp37 = tl.load(in_ptr2 + x0, xmask)
tmp1 = 0.0
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp3, tmp1)
tmp5 = tmp2 + tmp4
tmp7 = triton_helpers.maximum(tmp6, tmp1)
tmp8 = tmp5 + tmp7
tmp10 = triton_helpers.maximum(tmp9, tmp1)
tmp11 = tmp8 + tmp10
tmp12 = 1.0
tmp13 = tmp11 - tmp12
tmp16 = triton_helpers.maximum(tmp14, tmp15)
tmp18 = triton_helpers.maximum(tmp16, tmp17)
tmp20 = triton_helpers.maximum(tmp18, tmp19)
tmp21 = tmp20 - tmp12
tmp22 = tmp14 - tmp21
tmp23 = triton_helpers.maximum(tmp22, tmp1)
tmp24 = tmp15 - tmp21
tmp25 = triton_helpers.maximum(tmp24, tmp1)
tmp26 = tmp23 + tmp25
tmp27 = tmp17 - tmp21
tmp28 = triton_helpers.maximum(tmp27, tmp1)
tmp29 = tmp26 + tmp28
tmp30 = tmp19 - tmp21
tmp31 = triton_helpers.maximum(tmp30, tmp1)
tmp32 = tmp29 + tmp31
tmp33 = tmp32 - tmp12
tmp34 = tmp13 * tmp33
tmp35 = tmp34 >= tmp1
tmp38 = 0.5
tmp39 = tmp37 * tmp38
tmp40 = tmp39 * tmp38
tmp41 = tmp40 * tmp38
tmp42 = tmp41 * tmp38
tmp43 = tmp42 * tmp38
tmp44 = tmp43 * tmp38
tmp45 = tmp44 * tmp38
tmp46 = tmp45 * tmp38
tmp47 = tmp46 * tmp38
tmp48 = tmp47 * tmp38
tmp49 = tmp48 * tmp38
tmp50 = tmp49 * tmp38
tmp51 = tmp50 * tmp38
tmp52 = tmp51 * tmp38
tmp53 = tmp52 * tmp38
tmp54 = tmp53 * tmp38
tmp55 = tmp54 * tmp38
tmp56 = tmp55 * tmp38
tmp57 = tmp56 * tmp38
tmp58 = tmp57 * tmp38
tmp59 = tmp58 * tmp38
tmp60 = tmp59 * tmp38
tmp61 = tmp60 * tmp38
tmp62 = tmp61 * tmp38
tmp63 = tmp62 * tmp38
tmp64 = tmp36 + tmp63
tmp65 = tl.where(tmp35, tmp64, tmp36)
tl.store(in_out_ptr0 + x0, tmp65, xmask)
@triton.jit
def triton_poi_fused_add_div_sub_8(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp6 * tmp3
tmp8 = tmp7 * tmp3
tmp9 = tmp8 * tmp3
tmp10 = tmp9 * tmp3
tmp11 = tmp10 * tmp3
tmp12 = tmp11 * tmp3
tmp13 = tmp12 * tmp3
tmp14 = tmp13 * tmp3
tmp15 = tmp14 * tmp3
tmp16 = tmp15 * tmp3
tmp17 = tmp16 * tmp3
tmp18 = tmp17 * tmp3
tmp19 = tmp18 * tmp3
tmp20 = tmp19 * tmp3
tmp21 = tmp20 * tmp3
tmp22 = tmp21 * tmp3
tmp23 = tmp22 * tmp3
tmp24 = tmp23 * tmp3
tmp25 = tmp24 * tmp3
tmp26 = tmp25 * tmp3
tmp27 = tmp26 * tmp3
tmp28 = tmp27 * tmp3
tmp29 = tmp28 * tmp3
tmp30 = tmp1 + tmp29
tmp31 = tmp0 - tmp30
tl.store(out_ptr0 + x2, tmp31, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_9(in_out_ptr0,
in_out_ptr2, in_ptr0, in_ptr1, in_ptr2, out_ptr4, out_ptr7, 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')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_out_ptr0 + x0, xmask)
tmp37 = tl.load(in_ptr2 + x0, xmask)
tmp1 = 0.0
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp3, tmp1)
tmp5 = tmp2 + tmp4
tmp7 = triton_helpers.maximum(tmp6, tmp1)
tmp8 = tmp5 + tmp7
tmp10 = triton_helpers.maximum(tmp9, tmp1)
tmp11 = tmp8 + tmp10
tmp12 = 1.0
tmp13 = tmp11 - tmp12
tmp16 = triton_helpers.maximum(tmp14, tmp15)
tmp18 = triton_helpers.maximum(tmp16, tmp17)
tmp20 = triton_helpers.maximum(tmp18, tmp19)
tmp21 = tmp20 - tmp12
tmp22 = tmp14 - tmp21
tmp23 = triton_helpers.maximum(tmp22, tmp1)
tmp24 = tmp15 - tmp21
tmp25 = triton_helpers.maximum(tmp24, tmp1)
tmp26 = tmp23 + tmp25
tmp27 = tmp17 - tmp21
tmp28 = triton_helpers.maximum(tmp27, tmp1)
tmp29 = tmp26 + tmp28
tmp30 = tmp19 - tmp21
tmp31 = triton_helpers.maximum(tmp30, tmp1)
tmp32 = tmp29 + tmp31
tmp33 = tmp32 - tmp12
tmp34 = tmp13 * tmp33
tmp35 = tmp34 >= tmp1
tmp38 = 0.5
tmp39 = tmp37 * tmp38
tmp40 = tmp39 * tmp38
tmp41 = tmp40 * tmp38
tmp42 = tmp41 * tmp38
tmp43 = tmp42 * tmp38
tmp44 = tmp43 * tmp38
tmp45 = tmp44 * tmp38
tmp46 = tmp45 * tmp38
tmp47 = tmp46 * tmp38
tmp48 = tmp47 * tmp38
tmp49 = tmp48 * tmp38
tmp50 = tmp49 * tmp38
tmp51 = tmp50 * tmp38
tmp52 = tmp51 * tmp38
tmp53 = tmp52 * tmp38
tmp54 = tmp53 * tmp38
tmp55 = tmp54 * tmp38
tmp56 = tmp55 * tmp38
tmp57 = tmp56 * tmp38
tmp58 = tmp57 * tmp38
tmp59 = tmp58 * tmp38
tmp60 = tmp59 * tmp38
tmp61 = tmp60 * tmp38
tmp62 = tmp61 * tmp38
tmp63 = tmp62 * tmp38
tmp64 = tmp63 * tmp38
tmp65 = tmp36 + tmp64
tmp66 = tl.where(tmp35, tmp65, tmp36)
tmp67 = tmp64 * tmp38
tmp68 = tmp66 + tmp67
tmp69 = tmp14 - tmp68
tmp70 = triton_helpers.maximum(tmp69, tmp1)
tmp71 = tmp15 - tmp68
tmp72 = triton_helpers.maximum(tmp71, tmp1)
tmp73 = tmp70 + tmp72
tmp74 = tmp17 - tmp68
tmp75 = triton_helpers.maximum(tmp74, tmp1)
tmp76 = tmp73 + tmp75
tmp77 = tmp19 - tmp68
tmp78 = triton_helpers.maximum(tmp77, tmp1)
tmp79 = tmp76 + tmp78
tmp80 = tmp79 - tmp12
tmp81 = tmp80 * tmp33
tmp82 = tmp81 >= tmp1
tmp83 = tl.where(tmp82, tmp68, tmp66)
tmp84 = tmp67 * tmp38
tmp85 = tmp83 + tmp84
tmp86 = tmp14 - tmp85
tmp87 = triton_helpers.maximum(tmp86, tmp1)
tmp88 = tmp15 - tmp85
tmp89 = triton_helpers.maximum(tmp88, tmp1)
tmp90 = tmp87 + tmp89
tmp91 = tmp17 - tmp85
tmp92 = triton_helpers.maximum(tmp91, tmp1)
tmp93 = tmp90 + tmp92
tmp94 = tmp19 - tmp85
tmp95 = triton_helpers.maximum(tmp94, tmp1)
tmp96 = tmp93 + tmp95
tmp97 = tmp96 - tmp12
tmp98 = tmp97 * tmp33
tmp99 = tmp98 >= tmp1
tmp100 = tl.where(tmp99, tmp85, tmp83)
tmp101 = tmp84 * tmp38
tmp102 = tmp100 + tmp101
tmp103 = tmp14 - tmp102
tmp104 = triton_helpers.maximum(tmp103, tmp1)
tmp105 = tmp15 - tmp102
tmp106 = triton_helpers.maximum(tmp105, tmp1)
tmp107 = tmp104 + tmp106
tmp108 = tmp17 - tmp102
tmp109 = triton_helpers.maximum(tmp108, tmp1)
tmp110 = tmp107 + tmp109
tmp111 = tmp19 - tmp102
tmp112 = triton_helpers.maximum(tmp111, tmp1)
tmp113 = tmp110 + tmp112
tmp114 = tmp113 - tmp12
tmp115 = tmp114 * tmp33
tmp116 = tmp115 >= tmp1
tmp117 = tl.where(tmp116, tmp102, tmp100)
tmp118 = tmp101 * tmp38
tmp119 = tmp117 + tmp118
tmp120 = tmp14 - tmp119
tmp121 = triton_helpers.maximum(tmp120, tmp1)
tmp122 = tmp15 - tmp119
tmp123 = triton_helpers.maximum(tmp122, tmp1)
tmp124 = tmp121 + tmp123
tmp125 = tmp17 - tmp119
tmp126 = triton_helpers.maximum(tmp125, tmp1)
tmp127 = tmp124 + tmp126
tmp128 = tmp19 - tmp119
tmp129 = triton_helpers.maximum(tmp128, tmp1)
tmp130 = tmp127 + tmp129
tmp131 = tmp130 - tmp12
tmp132 = tmp131 * tmp33
tmp133 = tmp132 >= tmp1
tmp134 = tl.where(tmp133, tmp119, tmp117)
tmp135 = tmp118 * tmp38
tmp136 = tmp134 + tmp135
tmp137 = tmp14 - tmp136
tmp138 = triton_helpers.maximum(tmp137, tmp1)
tmp139 = tmp15 - tmp136
tmp140 = triton_helpers.maximum(tmp139, tmp1)
tmp141 = tmp138 + tmp140
tmp142 = tmp17 - tmp136
tmp143 = triton_helpers.maximum(tmp142, tmp1)
tmp144 = tmp141 + tmp143
tmp145 = tmp19 - tmp136
tmp146 = triton_helpers.maximum(tmp145, tmp1)
tmp147 = tmp144 + tmp146
tmp148 = tmp147 - tmp12
tmp149 = tmp148 * tmp33
tmp150 = tmp149 >= tmp1
tmp151 = tl.where(tmp150, tmp136, tmp134)
tmp152 = tmp135 * tmp38
tmp153 = tmp151 + tmp152
tmp154 = tmp14 - tmp153
tmp155 = triton_helpers.maximum(tmp154, tmp1)
tmp156 = tmp15 - tmp153
tmp157 = triton_helpers.maximum(tmp156, tmp1)
tmp158 = tmp155 + tmp157
tmp159 = tmp17 - tmp153
tmp160 = triton_helpers.maximum(tmp159, tmp1)
tmp161 = tmp158 + tmp160
tmp162 = tmp19 - tmp153
tmp163 = triton_helpers.maximum(tmp162, tmp1)
tmp164 = tmp161 + tmp163
tl.store(out_ptr4 + x0, tmp101, xmask)
tl.store(in_out_ptr2 + x0, tmp151, xmask)
tl.store(out_ptr7 + x0, tmp164, xmask)
@triton.jit
def triton_poi_fused_add_clamp_div_sub_10(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp3 = 0.5
tmp4 = tmp2 * tmp3
tmp5 = tmp4 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp1 + tmp6
tmp8 = tmp0 - tmp7
tmp9 = 0.0
tmp10 = triton_helpers.maximum(tmp8, tmp9)
tmp12 = tmp10 / tmp11
tl.store(out_ptr0 + x2, tmp12, 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)
buf40 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf41 = reinterpret_tensor(buf40, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf40
get_raw_stream(0)
triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_0[grid(64)](buf41,
arg0_1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf42 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf81 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf82 = reinterpret_tensor(buf81, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf81
triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_1[grid(64)](buf82,
arg0_1, buf41, buf42, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf83 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_clamp_div_sub_2[grid(256)](arg0_1, buf82,
buf42, buf83, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf85 = buf82
del buf82
triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_3[grid(64)](buf85,
buf83, arg0_1, buf42, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf86 = buf83
del buf83
triton_poi_fused_add_clamp_div_sub_4[grid(256)](arg0_1, buf85,
buf42, buf86, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf88 = buf85
del buf85
triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_5[grid(64)](buf88,
buf86, arg0_1, buf42, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf89 = buf86
del buf86
triton_poi_fused_add_div_sub_6[grid(256)](arg0_1, buf88, buf42,
buf89, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf91 = buf88
del buf88
triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_7[grid(64)](buf91,
buf89, arg0_1, buf42, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf92 = buf89
del buf89
triton_poi_fused_add_div_sub_8[grid(256)](arg0_1, buf91, buf42,
buf92, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf94 = buf91
del buf91
buf100 = buf41
del buf41
buf103 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf104 = reinterpret_tensor(buf103, (4, 4, 4, 1), (16, 4, 1, 64), 0)
del buf103
buf105 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_clamp_div_max_mul_sub_sum_where_9[grid(64)](buf94,
buf104, buf92, arg0_1, buf42, buf100, buf105, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf42
del buf94
buf106 = buf92
del buf92
triton_poi_fused_add_clamp_div_sub_10[grid(256)](arg0_1, buf104,
buf100, buf105, buf106, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del buf100
del buf104
del buf105
return buf106,
def sparsemax_bisect(X, dim=-1, n_iter=50, ensure_sum_one=True):
"""sparsemax: normalizing sparse transform (a la softmax), via bisection.
Solves the projection:
min_p ||x - p||_2 s.t. p >= 0, sum(p) == 1.
Parameters
----------
X : torch.Tensor
The input tensor.
dim : int
The dimension along which to apply sparsemax.
n_iter : int
Number of bisection iterations. For float32, 24 iterations should
suffice for machine precision.
ensure_sum_one : bool,
Whether to divide the result by its sum. If false, the result might
sum to close but not exactly 1, which might cause downstream problems.
Note: This function does not yet support normalizing along anything except
the last dimension. Please use transposing and views to achieve more
general behavior.
Returns
-------
P : torch tensor, same shape as X
The projection result, such that P.sum(dim=dim) == 1 elementwise.
"""
return SparsemaxBisectFunction.apply(X, dim, n_iter, ensure_sum_one)
class EntmaxBisectFunction(Function):
@classmethod
def _gp(cls, x, alpha):
return x ** (alpha - 1)
@classmethod
def _gp_inv(cls, y, alpha):
return y ** (1 / (alpha - 1))
@classmethod
def _p(cls, X, alpha):
return cls._gp_inv(torch.clamp(X, min=0), alpha)
@classmethod
def forward(cls, ctx, X, alpha=1.5, dim=-1, n_iter=50, ensure_sum_one=True
):
if not isinstance(alpha, torch.Tensor):
alpha = torch.tensor(alpha, dtype=X.dtype, device=X.device)
alpha_shape = list(X.shape)
alpha_shape[dim] = 1
alpha = alpha.expand(*alpha_shape)
ctx.alpha = alpha
ctx.dim = dim
d = X.shape[dim]
max_val, _ = X.max(dim=dim, keepdim=True)
X = X * (alpha - 1)
max_val = max_val * (alpha - 1)
tau_lo = max_val - cls._gp(1, alpha)
tau_hi = max_val - cls._gp(1 / d, alpha)
f_lo = cls._p(X - tau_lo, alpha).sum(dim) - 1
dm = tau_hi - tau_lo
for it in range(n_iter):
dm /= 2
tau_m = tau_lo + dm
p_m = cls._p(X - tau_m, alpha)
f_m = p_m.sum(dim) - 1
mask = (f_m * f_lo >= 0).unsqueeze(dim)
tau_lo = torch.where(mask, tau_m, tau_lo)
if ensure_sum_one:
p_m /= p_m.sum(dim=dim).unsqueeze(dim=dim)
ctx.save_for_backward(p_m)
return p_m
@classmethod
def backward(cls, ctx, dY):
Y, = ctx.saved_tensors
gppr = torch.where(Y > 0, Y ** (2 - ctx.alpha), Y.new_zeros(1))
dX = dY * gppr
q = dX.sum(ctx.dim) / gppr.sum(ctx.dim)
q = q.unsqueeze(ctx.dim)
dX -= q * gppr
d_alpha = None
if ctx.needs_input_grad[1]:
S = torch.where(Y > 0, Y * torch.log(Y), Y.new_zeros(1))
ent = S.sum(ctx.dim).unsqueeze(ctx.dim)
Y_skewed = gppr / gppr.sum(ctx.dim).unsqueeze(ctx.dim)
d_alpha = dY * (Y - Y_skewed) / (ctx.alpha - 1) ** 2
d_alpha -= dY * (S - Y_skewed * ent) / (ctx.alpha - 1)
d_alpha = d_alpha.sum(ctx.dim).unsqueeze(ctx.dim)
return dX, d_alpha, None, None, None
class SparsemaxBisectFunction(EntmaxBisectFunction):
@classmethod
def _gp(cls, x, alpha):
return x
@classmethod
def _gp_inv(cls, y, alpha):
return y
@classmethod
def _p(cls, x, alpha):
return torch.clamp(x, min=0)
@classmethod
def forward(cls, ctx, X, dim=-1, n_iter=50, ensure_sum_one=True):
return super().forward(ctx, X, alpha=2, dim=dim, n_iter=50,
ensure_sum_one=True)
@classmethod
def backward(cls, ctx, dY):
Y, = ctx.saved_tensors
gppr = Y > 0
dX = dY * gppr
q = dX.sum(ctx.dim) / gppr.sum(ctx.dim)
q = q.unsqueeze(ctx.dim)
dX -= q * gppr
return dX, None, None, None
class SparsemaxBisectNew(nn.Module):
def __init__(self, dim=-1, n_iter=None):
"""sparsemax: normalizing sparse transform (a la softmax) via bisection
Solves the projection:
min_p ||x - p||_2 s.t. p >= 0, sum(p) == 1.
Parameters
----------
dim : int
The dimension along which to apply sparsemax.
n_iter : int
Number of bisection iterations. For float32, 24 iterations should
suffice for machine precision.
"""
self.dim = dim
self.n_iter = n_iter
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
cifkao/entmax
|
SparsemaxBisect
| false
| 15,042
|
[
"MIT"
] | 298
|
f18bab9318f9d2471a36545ee0b4c97be6d48a87
|
https://github.com/cifkao/entmax/tree/f18bab9318f9d2471a36545ee0b4c97be6d48a87
|
AttentionModule
|
from _paritybench_helpers import _mock_config
import torch
class AttentionModule(torch.nn.Module):
"""
SimGNN Attention Module to make a pass on graph.
"""
def __init__(self, args):
"""
:param args: Arguments object.
"""
super(AttentionModule, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
def setup_weights(self):
"""
Defining weights.
"""
self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.
filters_3, self.args.filters_3))
def init_parameters(self):
"""
Initializing weights.
"""
torch.nn.init.xavier_uniform_(self.weight_matrix)
def forward(self, embedding):
"""
Making a forward propagation pass to create a graph level representation.
:param embedding: Result of the GCN.
:return representation: A graph level representation vector.
"""
batch_size = embedding.shape[0]
global_context = torch.mean(torch.matmul(embedding, self.
weight_matrix), dim=1)
transformed_global = torch.tanh(global_context)
sigmoid_scores = torch.sigmoid(torch.matmul(embedding,
transformed_global.view(batch_size, -1, 1)))
representation = torch.matmul(embedding.permute(0, 2, 1),
sigmoid_scores)
return representation, sigmoid_scores
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'args': _mock_config(filters_3=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mean_tanh_tanh_backward_0(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = libdevice.tanh(tmp8)
tmp10 = tmp9 * tmp9
tmp11 = 1.0
tmp12 = tmp11 - tmp10
tl.store(out_ptr0 + x2, tmp9, xmask)
tl.store(out_ptr1 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused_sigmoid_1(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 = tl.sigmoid(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (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),
primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_tanh_tanh_backward_0[grid(16)](buf0, buf1,
buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
del buf0
buf2 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(primals_1, reinterpret_tensor(buf1, (4, 4, 1), (
4, 1, 0), 0), out=buf2)
buf3 = buf2
del buf2
triton_poi_fused_sigmoid_1[grid(16)](buf3, 16, XBLOCK=16, num_warps
=1, num_stages=1)
buf4 = reinterpret_tensor(buf1, (4, 4, 1), (4, 1, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(primals_1, (4, 4, 4), (16, 1,
4), 0), buf3, out=buf4)
return buf4, buf3, primals_1, buf3, buf5
class AttentionModuleNew(torch.nn.Module):
"""
SimGNN Attention Module to make a pass on graph.
"""
def __init__(self, args):
"""
:param args: Arguments object.
"""
super(AttentionModuleNew, self).__init__()
self.args = args
self.setup_weights()
self.init_parameters()
def setup_weights(self):
"""
Defining weights.
"""
self.weight_matrix = torch.nn.Parameter(torch.Tensor(self.args.
filters_3, self.args.filters_3))
def init_parameters(self):
"""
Initializing weights.
"""
torch.nn.init.xavier_uniform_(self.weight_matrix)
def forward(self, input_0):
primals_2 = self.weight_matrix
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0], output[1]
|
cloudcjf/SG_PR
|
AttentionModule
| false
| 15,043
|
[
"MIT"
] | 105
|
1339d00811ea3c4c18963efa24bf6fc778e15794
|
https://github.com/cloudcjf/SG_PR/tree/1339d00811ea3c4c18963efa24bf6fc778e15794
|
GraphConvolution
|
from torch.nn import Module
import torch
from torch.nn import Parameter
from torch.nn import functional as F
import torch.multiprocessing
import torch.utils.data
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
import torch.nn.modules.loss
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, dropout=0.0, act=F.relu):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.dropout = dropout
self.act = act
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.xavier_uniform_(self.weight)
def forward(self, input, adj):
input = F.dropout(input, self.dropout, self.training)
support = torch.mm(input, self.weight)
output = torch.spmm(adj, support)
output = self.act(output)
return output
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch.nn import Module
from torch.nn import Parameter
from torch.nn import functional as F
import torch.multiprocessing
import torch.utils.data
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
import torch.nn.modules.loss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 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_1, primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_3, buf0, out=buf1)
del buf0
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16)](buf2, buf3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
return buf2, buf3, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0
), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0)
class GraphConvolutionNew(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, dropout=0.0, act=F.relu):
super(GraphConvolutionNew, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.dropout = dropout
self.act = act
self.weight = Parameter(torch.FloatTensor(in_features, out_features))
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.xavier_uniform_(self.weight)
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
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]
|
cminusQAQ/graph4nlp
|
GraphConvolution
| false
| 15,044
|
[
"Apache-2.0"
] | 1,269
|
d980e897131f1b9d3766750c06316d94749904fa
|
https://github.com/cminusQAQ/graph4nlp/tree/d980e897131f1b9d3766750c06316d94749904fa
|
DilatedResidualLayer
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class DilatedResidualLayer(nn.Module):
def __init__(self, dilation, in_channels, out_channels):
super(DilatedResidualLayer, self).__init__()
self.conv_dilated = nn.Conv1d(in_channels, out_channels, 3, padding
=dilation, dilation=dilation)
self.conv_1x1 = nn.Conv1d(out_channels, out_channels, 1)
self.dropout = nn.Dropout()
def forward(self, x):
out = F.relu(self.conv_dilated(x))
out = self.conv_1x1(out)
out = self.dropout(out)
return x + out
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'dilation': 1, 'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
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 = 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_out_ptr0 + x2, 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 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_out_ptr0 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3), (12, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4), (16, 4, 1), 0), primals_1, stride=(1,), padding=(1,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (1, 4, 4), (16, 4, 1))
buf1 = reinterpret_tensor(buf0, (4, 4), (4, 1), 0)
del buf0
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(16)](buf1,
primals_2, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 4
), (0, 4, 1), 0), primals_4, 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 = reinterpret_tensor(buf2, (4, 4), (4, 1), 0)
del buf2
triton_poi_fused_add_1[grid(16)](buf3, primals_3, primals_5, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return buf3, primals_1, primals_4, reinterpret_tensor(primals_3, (1, 4,
4), (16, 4, 1), 0), reinterpret_tensor(buf1, (1, 4, 4), (16, 4, 1), 0
), buf4
class DilatedResidualLayerNew(nn.Module):
def __init__(self, dilation, in_channels, out_channels):
super(DilatedResidualLayerNew, self).__init__()
self.conv_dilated = nn.Conv1d(in_channels, out_channels, 3, padding
=dilation, dilation=dilation)
self.conv_1x1 = nn.Conv1d(out_channels, out_channels, 1)
self.dropout = nn.Dropout()
def forward(self, input_0):
primals_1 = self.conv_dilated.weight
primals_2 = self.conv_dilated.bias
primals_4 = self.conv_1x1.weight
primals_5 = self.conv_1x1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
cmhungsteve/SSTDA
|
DilatedResidualLayer
| false
| 15,045
|
[
"MIT"
] | 154
|
9c5e1df952bd122ea474046d91e3ac6fa79ec312
|
https://github.com/cmhungsteve/SSTDA/tree/9c5e1df952bd122ea474046d91e3ac6fa79ec312
|
MeanEmbedding
|
import torch
import torch.nn as nn
import torch.multiprocessing
import torch.utils.data
import torch.nn.modules.loss
class MeanEmbedding(nn.Module):
"""Mean embedding class."""
def __init__(self):
super(MeanEmbedding, self).__init__()
def forward(self, emb, len_):
"""Compute average embeddings.
Parameters
----------
emb : torch.Tensor
The input embedding tensor.
len_ : torch.Tensor
The sequence length tensor.
Returns
-------
torch.Tensor
The average embedding tensor.
"""
summed = torch.sum(emb, dim=-2)
len_ = len_.unsqueeze(-1).expand_as(summed).float()
return summed / len_
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
import torch.nn as nn
import torch.multiprocessing
import torch.utils.data
import torch.nn.modules.loss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_div_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
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), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_sum_0[grid(64)](arg0_1, arg1_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class MeanEmbeddingNew(nn.Module):
"""Mean embedding class."""
def __init__(self):
super(MeanEmbeddingNew, 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]
|
cminusQAQ/graph4nlp
|
MeanEmbedding
| false
| 15,046
|
[
"Apache-2.0"
] | 1,269
|
d980e897131f1b9d3766750c06316d94749904fa
|
https://github.com/cminusQAQ/graph4nlp/tree/d980e897131f1b9d3766750c06316d94749904fa
|
SoftDiceLoss
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SoftDiceLoss(nn.Module):
def __init__(self, weight=None, size_average=True):
super(SoftDiceLoss, self).__init__()
def forward(self, logits, targets):
num = targets.size(0)
probs = F.sigmoid(logits)
m1 = probs.view(num, -1)
m2 = targets.view(num, -1)
intersection = m1 * m2
score = 2.0 * (intersection.sum(1) + 1) / (m1.sum(1) + m2.sum(1) + 1)
score = 1 - score.sum() / num
return score
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
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 + (r1 + 64 * x0), xmask, other=0.0)
tmp2 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp10 = tl.where(xmask, tmp8, 0)
tmp11 = tl.sum(tmp10, 1)[:, None]
tmp12 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp14 = tl.where(xmask, tmp12, 0)
tmp15 = tl.sum(tmp14, 1)[:, None]
tl.store(out_ptr0 + x0, tmp7, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
tl.store(out_ptr2 + x0, tmp15, xmask)
@triton.jit
def triton_per_fused_add_div_mul_rsub_sum_1(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp5 = tl.load(in_ptr1 + r0, None)
tmp6 = tl.load(in_ptr2 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp3 = 2.0
tmp4 = tmp2 * tmp3
tmp7 = tmp5 + tmp6
tmp8 = tmp7 + tmp1
tmp9 = tmp4 / tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.sum(tmp10, 1)[:, None]
tmp13 = 0.25
tmp14 = tmp12 * tmp13
tmp15 = tmp1 - tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((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)](arg1_1, arg0_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)
buf4 = buf3
del buf3
triton_per_fused_add_div_mul_rsub_sum_1[grid(1)](buf4, buf0, buf1,
buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf2
return buf4,
class SoftDiceLossNew(nn.Module):
def __init__(self, weight=None, size_average=True):
super(SoftDiceLossNew, 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]
|
cmarasinou/carvana-challenge
|
SoftDiceLoss
| false
| 15,047
|
[
"MIT"
] | 93
|
4e1c43f306cfbef1df267acfce59bdcf19504850
|
https://github.com/cmarasinou/carvana-challenge/tree/4e1c43f306cfbef1df267acfce59bdcf19504850
|
InnerProductDecoder
|
import torch
import torch.nn as nn
from torch.nn import functional as F
import torch.multiprocessing
import torch.utils.data
import torch.nn.modules.loss
class InnerProductDecoder(nn.Module):
"""Decoder for using inner product for prediction."""
def __init__(self, dropout, act=torch.sigmoid):
super(InnerProductDecoder, self).__init__()
self.dropout = dropout
self.act = act
def forward(self, z):
z = F.dropout(z, self.dropout, training=self.training)
adj = self.act(torch.mm(z, z.t()))
return adj
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.multiprocessing
import torch.utils.data
import torch.nn.modules.loss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sigmoid_0(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.sigmoid(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
0), out=buf0)
del arg0_1
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_sigmoid_0[grid(16)](buf1, 16, XBLOCK=16, num_warps
=1, num_stages=1)
return buf1,
class InnerProductDecoderNew(nn.Module):
"""Decoder for using inner product for prediction."""
def __init__(self, dropout, act=torch.sigmoid):
super(InnerProductDecoderNew, self).__init__()
self.dropout = dropout
self.act = act
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
cminusQAQ/graph4nlp
|
InnerProductDecoder
| false
| 15,048
|
[
"Apache-2.0"
] | 1,269
|
d980e897131f1b9d3766750c06316d94749904fa
|
https://github.com/cminusQAQ/graph4nlp/tree/d980e897131f1b9d3766750c06316d94749904fa
|
BCELoss2d
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class BCELoss2d(nn.Module):
def __init__(self, weight=None, size_average=True):
super(BCELoss2d, self).__init__()
self.bce_loss = nn.BCELoss(weight, size_average)
def forward(self, logits, targets):
probs = F.sigmoid(logits)
probs_flat = probs.view(-1)
targets_flat = targets.view(-1)
return self.bce_loss(probs_flat, targets_flat)
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_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 - tmp1
tmp4 = tl.sigmoid(tmp3)
tmp5 = -tmp4
tmp6 = libdevice.log1p(tmp5)
tmp7 = -100.0
tmp8 = triton_helpers.maximum(tmp6, tmp7)
tmp9 = tmp2 * tmp8
tmp10 = tl_math.log(tmp4)
tmp11 = triton_helpers.maximum(tmp10, tmp7)
tmp12 = tmp0 * tmp11
tmp13 = tmp9 - tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = 256.0
tmp18 = tmp16 / tmp17
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp18, None)
def call(args):
arg0_1, arg1_1 = 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_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 BCELoss2dNew(nn.Module):
def __init__(self, weight=None, size_average=True):
super(BCELoss2dNew, self).__init__()
self.bce_loss = nn.BCELoss(weight, size_average)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
cmarasinou/carvana-challenge
|
BCELoss2d
| false
| 15,049
|
[
"MIT"
] | 93
|
4e1c43f306cfbef1df267acfce59bdcf19504850
|
https://github.com/cmarasinou/carvana-challenge/tree/4e1c43f306cfbef1df267acfce59bdcf19504850
|
mlpblock
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class linearblock(nn.Module):
def __init__(self, in_features, out_features, bias=True, dropout='none'):
super(linearblock, self).__init__()
self.conv = nn.Linear(in_features, out_features, bias=bias)
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(inplace=True)
self.dropoutoption = dropout
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
if self.dropoutoption == 'normal':
x = self.dropout(x)
return x
class mlpblock(nn.Module):
def __init__(self, inputdim, outputdim, nlayer=2, hiddendim=10,
activation='ReLU'):
super(mlpblock, self).__init__()
self.nlayer = nlayer
self.hiddendim = hiddendim
self.inputdim = inputdim
self.outputdim = outputdim
if activation == 'ReLU':
self.act = F.relu
else:
raise NotImplementedError
self.fc1 = nn.Linear(self.inputdim, self.hiddendim)
fc_iter = []
for n in range(self.nlayer - 2):
fc_iter.append(linearblock(self.hiddendim, self.hiddendim))
self.fc_iter = nn.Sequential(*fc_iter)
self.fc_final = nn.Linear(self.hiddendim, self.outputdim)
def forward(self, x):
x = self.act(self.fc1(x))
x = self.fc_iter(x)
x = self.fc_final(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inputdim': 4, 'outputdim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 640
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 10
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (10, 4), (4, 1))
assert_size_stride(primals_2, (10,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 10), (10, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 10), (10, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 10), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 10), (160, 40, 10, 1), 0)
del buf0
buf3 = empty_strided_cuda((4, 4, 4, 10), (160, 40, 10, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(640)](buf1,
primals_2, buf3, 640, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 10),
(10, 1), 0), reinterpret_tensor(primals_4, (10, 4), (1, 10), 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, 10), (10, 1), 0), primals_4, buf3
class linearblock(nn.Module):
def __init__(self, in_features, out_features, bias=True, dropout='none'):
super(linearblock, self).__init__()
self.conv = nn.Linear(in_features, out_features, bias=bias)
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(inplace=True)
self.dropoutoption = dropout
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
if self.dropoutoption == 'normal':
x = self.dropout(x)
return x
class mlpblockNew(nn.Module):
def __init__(self, inputdim, outputdim, nlayer=2, hiddendim=10,
activation='ReLU'):
super(mlpblockNew, self).__init__()
self.nlayer = nlayer
self.hiddendim = hiddendim
self.inputdim = inputdim
self.outputdim = outputdim
if activation == 'ReLU':
self.act = F.relu
else:
raise NotImplementedError
self.fc1 = nn.Linear(self.inputdim, self.hiddendim)
fc_iter = []
for n in range(self.nlayer - 2):
fc_iter.append(linearblock(self.hiddendim, self.hiddendim))
self.fc_iter = nn.Sequential(*fc_iter)
self.fc_final = nn.Linear(self.hiddendim, self.outputdim)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc_final.weight
primals_5 = self.fc_final.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
coallaoh/WhitenBlackBox
|
mlpblock
| false
| 15,050
|
[
"MIT"
] | 46
|
816363c59a11248e79ffed70f1a14510b0967dab
|
https://github.com/coallaoh/WhitenBlackBox/tree/816363c59a11248e79ffed70f1a14510b0967dab
|
ShiftedSoftplus
|
import torch
import torch.nn.functional as F
from torch import nn
class ShiftedSoftplus(nn.Module):
__constants__ = ['beta', 'threshold']
beta: 'int'
threshold: 'int'
def __init__(self, beta: 'int'=1, threshold: 'int'=20) ->None:
super(ShiftedSoftplus, self).__init__()
self.beta = beta
self.threshold = threshold
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
return F.softplus(x - 1, self.beta, self.threshold)
def extra_repr(self) ->str:
return 'beta={}, threshold={}'.format(self.beta, self.threshold)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch 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_softplus_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 - tmp1
tmp3 = 20.0
tmp4 = tmp2 > tmp3
tmp5 = tl_math.exp(tmp2)
tmp6 = libdevice.log1p(tmp5)
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_softplus_sub_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ShiftedSoftplusNew(nn.Module):
__constants__ = ['beta', 'threshold']
beta: 'int'
threshold: 'int'
def __init__(self, beta: 'int'=1, threshold: 'int'=20) ->None:
super(ShiftedSoftplusNew, self).__init__()
self.beta = beta
self.threshold = threshold
def extra_repr(self) ->str:
return 'beta={}, threshold={}'.format(self.beta, self.threshold)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
cmusatyalab/mega-nerf
|
ShiftedSoftplus
| false
| 15,051
|
[
"MIT"
] | 107
|
306e06cc316dd4f5c84d0610308bcbc208228fc3
|
https://github.com/cmusatyalab/mega-nerf/tree/306e06cc316dd4f5c84d0610308bcbc208228fc3
|
Accuracy
|
import torch
from torch import nn
class Accuracy(nn.Module):
label = 'Accuracy'
def forward(self, prediction, truth):
prediction = prediction.argmax(dim=1)
correct = prediction == truth
accuracy = correct.float().mean()
return accuracy
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
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_argmax_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)
tmp17 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp32 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 > tmp1
tmp3 = tmp0 == tmp1
tmp4 = tmp0 != tmp0
tmp5 = tmp1 != tmp1
tmp6 = tmp4 > tmp5
tmp7 = tmp2 | tmp6
tmp8 = tmp4 & tmp5
tmp9 = tmp3 | tmp8
tmp10 = tl.full([1], 0, tl.int64)
tmp11 = tl.full([1], 1, tl.int64)
tmp12 = tmp10 < tmp11
tmp13 = tmp9 & tmp12
tmp14 = tmp7 | tmp13
tmp15 = tl.where(tmp14, tmp0, tmp1)
tmp16 = tl.where(tmp14, tmp10, tmp11)
tmp18 = tmp15 > tmp17
tmp19 = tmp15 == tmp17
tmp20 = tmp15 != tmp15
tmp21 = tmp17 != tmp17
tmp22 = tmp20 > tmp21
tmp23 = tmp18 | tmp22
tmp24 = tmp20 & tmp21
tmp25 = tmp19 | tmp24
tmp26 = tl.full([1], 2, tl.int64)
tmp27 = tmp16 < tmp26
tmp28 = tmp25 & tmp27
tmp29 = tmp23 | tmp28
tmp30 = tl.where(tmp29, tmp15, tmp17)
tmp31 = tl.where(tmp29, tmp16, tmp26)
tmp33 = tmp30 > tmp32
tmp34 = tmp30 == tmp32
tmp35 = tmp30 != tmp30
tmp36 = tmp32 != tmp32
tmp37 = tmp35 > tmp36
tmp38 = tmp33 | tmp37
tmp39 = tmp35 & tmp36
tmp40 = tmp34 | tmp39
tmp41 = tl.full([1], 3, tl.int64)
tmp42 = tmp31 < tmp41
tmp43 = tmp40 & tmp42
tmp44 = tmp38 | tmp43
tl.where(tmp44, tmp30, tmp32)
tmp46 = tl.where(tmp44, tmp31, tmp41)
tl.store(out_ptr0 + x2, tmp46, xmask)
@triton.jit
def triton_per_fused__to_copy_eq_mean_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)
r0 = rindex % 64
r2 = rindex
tmp0 = tl.load(in_ptr0 + r0, None, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + r2, None)
tmp1 = tmp0.to(tl.float32)
tmp3 = tmp1 == tmp2
tmp4 = tmp3.to(tl.float32)
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = 256.0
tmp9 = tmp7 / tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp9, None)
def call(args):
arg0_1, arg1_1 = 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.int64)
get_raw_stream(0)
triton_poi_fused_argmax_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__to_copy_eq_mean_1[grid(1)](buf2, buf0, arg1_1, 1,
256, num_warps=2, num_stages=1)
del arg1_1
del buf0
return buf2,
class AccuracyNew(nn.Module):
label = 'Accuracy'
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
cms-flash/beauty-net
|
Accuracy
| false
| 15,052
|
[
"MIT"
] | 155
|
668210a95ccb4462d7beff10505e4e83532682f2
|
https://github.com/cms-flash/beauty-net/tree/668210a95ccb4462d7beff10505e4e83532682f2
|
ConvBlock
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class ConvBlock(nn.Module):
def __init__(self):
super(ConvBlock, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
return x
def get_inputs():
return [torch.rand([4, 3, 32, 32])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 18816
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 784 % 6
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4704
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 14
x3 = xindex // 14
x2 = xindex // 1176
x4 = xindex % 1176
tmp0 = tl.load(in_ptr0 + (2 * x0 + 56 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 56 * x3), xmask, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (28 + 2 * x0 + 56 * x3), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (29 + 2 * x0 + 56 * x3), 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 + (x4 + 1184 * x2), tmp6, xmask)
tl.store(out_ptr1 + (x4 + 1280 * x2), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 100 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1600
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 20 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 20 * x1), xmask, eviction_policy
='evict_last')
tmp7 = tl.load(in_ptr0 + (10 + 2 * x0 + 20 * x1), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (11 + 2 * x0 + 20 * x1), xmask,
eviction_policy='evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, xmask)
tl.store(out_ptr1 + x2, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (6, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_2, (6,), (1,))
assert_size_stride(primals_3, (4, 3, 32, 32), (3072, 1024, 32, 1))
assert_size_stride(primals_4, (16, 6, 5, 5), (150, 25, 5, 1))
assert_size_stride(primals_5, (16,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 6, 28, 28), (4704, 784, 28, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(18816)](buf1, primals_2,
18816, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 6, 14, 14), (1184, 196, 14, 1), torch
.float32)
buf3 = empty_strided_cuda((4, 6, 14, 14), (1280, 196, 14, 1), torch
.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(4704)](buf1, buf2,
buf3, 4704, XBLOCK=256, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 16, 10, 10), (1600, 100, 10, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(6400)](buf5, primals_5,
6400, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.int8)
buf7 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.float32
)
triton_poi_fused_max_pool2d_with_indices_3[grid(1600)](buf5, buf6,
buf7, 1600, XBLOCK=128, num_warps=4, num_stages=1)
return reinterpret_tensor(buf7, (4, 400), (400, 1), 0
), primals_1, primals_3, primals_4, buf1, buf2, buf3, buf5, buf6
class ConvBlockNew(nn.Module):
def __init__(self):
super(ConvBlockNew, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
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]
|
coasxu/FedMA
|
ConvBlock
| false
| 15,053
|
[
"MIT"
] | 254
|
21f4d32338fd2563ebd97c737e3b9f4f470029d9
|
https://github.com/coasxu/FedMA/tree/21f4d32338fd2563ebd97c737e3b9f4f470029d9
|
HirarchicalAttention
|
from torch.nn import Module
import torch
from typing import *
import torch.utils.data
import torch.nn as nn
import torch.onnx.operators
import torch.optim
class HirarchicalAttention(Module):
"""
ref: Hierarchical Attention Networks for Document Classification
"""
def __init__(self, hidden_size: 'int'):
super(HirarchicalAttention, self).__init__()
self.w_linear = nn.Linear(hidden_size, hidden_size)
self.u_w = nn.Linear(hidden_size, 1, bias=False)
def forward(self, input: 'torch.Tensor') ->torch.Tensor:
u_it = torch.tanh(self.w_linear(input))
a_it = torch.softmax(self.u_w(u_it), dim=1)
s_i = (input * a_it).sum(dim=1)
return s_i
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch.nn import Module
from typing import *
import torch.utils.data
import torch.nn as nn
import torch.onnx.operators
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_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
x3 = xindex
x0 = xindex % 4
x2 = xindex // 16
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_sum_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 16
x3 = xindex % 16
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x3 + 64 * x2), xmask)
tmp1 = tl.load(in_ptr1 + (x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x3 + 64 * x2), xmask)
tmp4 = tl.load(in_ptr1 + (4 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x3 + 64 * x2), xmask)
tmp8 = tl.load(in_ptr1 + (8 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x3 + 64 * x2), xmask)
tmp12 = tl.load(in_ptr1 + (12 + x1 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x4, tmp14, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (1, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 1), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_2[grid(64)](buf3, buf4, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0)
del buf3
triton_poi_fused__softmax_mul_sum_3[grid(64)](primals_3, buf4, buf5,
64, XBLOCK=64, num_warps=1, num_stages=1)
del buf4
return buf5, primals_3, buf1, buf2, primals_4
class HirarchicalAttentionNew(Module):
"""
ref: Hierarchical Attention Networks for Document Classification
"""
def __init__(self, hidden_size: 'int'):
super(HirarchicalAttentionNew, self).__init__()
self.w_linear = nn.Linear(hidden_size, hidden_size)
self.u_w = nn.Linear(hidden_size, 1, bias=False)
def forward(self, input_0):
primals_1 = self.w_linear.weight
primals_2 = self.w_linear.bias
primals_4 = self.u_w.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
code-backdoor/code-backdoor
|
HirarchicalAttention
| false
| 15,054
|
[
"MIT"
] | 71
|
1eeb3d79aa8a54c8f08e8d0156b569de5edd974e
|
https://github.com/code-backdoor/code-backdoor/tree/1eeb3d79aa8a54c8f08e8d0156b569de5edd974e
|
ConvLayer
|
import torch
import torch.nn.functional as F
from typing import *
import torch.utils.data
import torch.nn as nn
import torch.onnx.operators
import torch.optim
class ConvLayer(nn.Module):
def __init__(self, in_channels, out_channels):
super(ConvLayer, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels,
1, 1))
nn.init.constant_(self.weight, 0.1)
def forward(self, edges):
edges = (edges * F.softmax(self.weight, dim=1)).sum(dim=1)
return edges
def extra_repr(self) ->str:
return 'ConV {}'.format(self.weight.size())
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from typing import *
import torch.utils.data
import torch.nn as nn
import torch.onnx.operators
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp8 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp5 = tmp3 * tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 * tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 * tmp12
tmp14 = tmp10 + tmp13
tl.store(out_ptr0 + x2, tmp14, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(16)](primals_1, buf0, 16, XBLOCK=
16, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
triton_poi_fused__softmax_1[grid(16)](buf0, buf1, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf0
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_mul_sum_2[grid(64)](primals_2, buf1, buf2,
64, XBLOCK=64, num_warps=1, num_stages=1)
del buf1
return buf2, primals_1, primals_2
class ConvLayerNew(nn.Module):
def __init__(self, in_channels, out_channels):
super(ConvLayerNew, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels,
1, 1))
nn.init.constant_(self.weight, 0.1)
def extra_repr(self) ->str:
return 'ConV {}'.format(self.weight.size())
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
code-backdoor/code-backdoor
|
ConvLayer
| false
| 15,055
|
[
"MIT"
] | 71
|
1eeb3d79aa8a54c8f08e8d0156b569de5edd974e
|
https://github.com/code-backdoor/code-backdoor/tree/1eeb3d79aa8a54c8f08e8d0156b569de5edd974e
|
SimpleCNNContainerConvBlocks
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SimpleCNNContainerConvBlocks(nn.Module):
def __init__(self, input_channel, num_filters, kernel_size, output_dim=10):
super(SimpleCNNContainerConvBlocks, self).__init__()
"""
A testing cnn container, which allows initializing a CNN with given dims
We use this one to estimate matched output of conv blocks
num_filters (list) :: number of convolution filters
hidden_dims (list) :: number of neurons in hidden layers
Assumptions:
i) we use only two conv layers and three hidden layers (including the output layer)
ii) kernel size in the two conv layers are identical
"""
self.conv1 = nn.Conv2d(input_channel, num_filters[0], kernel_size)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(num_filters[0], num_filters[1], kernel_size)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
return x
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'input_channel': 4, 'num_filters': [4, 4], 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 59536
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 3721 % 4
x0 = xindex % 3721
x4 = xindex // 3721
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (x0 + 3744 * x4), tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 14400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 30
x1 = xindex // 30 % 30
x4 = xindex // 900
x3 = xindex // 3600
x5 = xindex % 3600
tmp0 = tl.load(in_ptr0 + (2 * x0 + 122 * x1 + 3744 * x4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 122 * x1 + 3744 * x4), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (61 + 2 * x0 + 122 * x1 + 3744 * x4), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (62 + 2 * x0 + 122 * x1 + 3744 * x4), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (x5 + 3616 * x3), tmp6, xmask)
tl.store(out_ptr1 + (x5 + 3712 * x3), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 11664
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 729 % 4
x2 = xindex // 2916
x4 = xindex % 2916
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(out_ptr0 + (x4 + 2944 * x2), tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 2704
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 13
x1 = xindex // 13 % 13
x2 = xindex // 169 % 4
x3 = xindex // 676
x4 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 54 * x1 + 729 * x2 + 2944 * x3),
xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 54 * x1 + 729 * x2 + 2944 * x3),
xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (27 + 2 * x0 + 54 * x1 + 729 * x2 + 2944 * x3),
xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (28 + 2 * x0 + 54 * x1 + 729 * x2 + 2944 * x3),
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 + x4, tmp6, xmask)
tl.store(out_ptr1 + x4, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 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))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 61, 61), (14884, 3721, 61, 1))
buf1 = empty_strided_cuda((4, 4, 61, 61), (14976, 3744, 61, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(59536)](buf0, primals_2,
buf1, 59536, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
buf2 = empty_strided_cuda((4, 4, 30, 30), (3616, 900, 30, 1), torch
.float32)
buf3 = empty_strided_cuda((4, 4, 30, 30), (3712, 900, 30, 1), torch
.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(14400)](buf1, buf2,
buf3, 14400, XBLOCK=256, num_warps=4, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 27, 27), (2916, 729, 27, 1))
buf5 = empty_strided_cuda((4, 4, 27, 27), (2944, 729, 27, 1), torch
.float32)
triton_poi_fused_convolution_relu_2[grid(11664)](buf4, primals_5,
buf5, 11664, XBLOCK=256, num_warps=4, num_stages=1)
del buf4
del primals_5
buf6 = empty_strided_cuda((4, 4, 13, 13), (676, 169, 13, 1), torch.
float32)
buf7 = empty_strided_cuda((4, 4, 13, 13), (676, 169, 13, 1), torch.int8
)
triton_poi_fused_max_pool2d_with_indices_3[grid(2704)](buf5, buf6,
buf7, 2704, XBLOCK=128, num_warps=4, num_stages=1)
return buf6, primals_1, primals_3, primals_4, buf1, buf2, buf3, buf5, buf7
class SimpleCNNContainerConvBlocksNew(nn.Module):
def __init__(self, input_channel, num_filters, kernel_size, output_dim=10):
super(SimpleCNNContainerConvBlocksNew, self).__init__()
"""
A testing cnn container, which allows initializing a CNN with given dims
We use this one to estimate matched output of conv blocks
num_filters (list) :: number of convolution filters
hidden_dims (list) :: number of neurons in hidden layers
Assumptions:
i) we use only two conv layers and three hidden layers (including the output layer)
ii) kernel size in the two conv layers are identical
"""
self.conv1 = nn.Conv2d(input_channel, num_filters[0], kernel_size)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(num_filters[0], num_filters[1], kernel_size)
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]
|
coasxu/FedMA
|
SimpleCNNContainerConvBlocks
| false
| 15,056
|
[
"MIT"
] | 254
|
21f4d32338fd2563ebd97c737e3b9f4f470029d9
|
https://github.com/coasxu/FedMA/tree/21f4d32338fd2563ebd97c737e3b9f4f470029d9
|
UNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class down(nn.Module):
"""
A class for creating neural network blocks containing layers:
Average Pooling --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels, filterSize):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used as input and output channels for the
second convolutional layer.
filterSize : int
filter size for the convolution filter. input N would create
a N x N filter.
"""
super(down, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, filterSize, stride=
1, padding=int((filterSize - 1) / 2))
self.conv2 = nn.Conv2d(outChannels, outChannels, filterSize, stride
=1, padding=int((filterSize - 1) / 2))
def forward(self, x):
"""
Returns output tensor after passing input `x` to the neural network
block.
Parameters
----------
x : tensor
input to the NN block.
Returns
-------
tensor
output of the NN block.
"""
x = F.avg_pool2d(x, 2)
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
x = F.leaky_relu(self.conv2(x), negative_slope=0.1)
return x
class up(nn.Module):
"""
A class for creating neural network blocks containing layers:
Bilinear interpolation --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x, skpCn)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used for setting input and output channels for
the second convolutional layer.
"""
super(up, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, 3, stride=1, padding=1)
self.conv2 = nn.Conv2d(2 * outChannels, outChannels, 3, stride=1,
padding=1)
def forward(self, x, skpCn):
"""
Returns output tensor after passing input `x` to the neural network
block.
Parameters
----------
x : tensor
input to the NN block.
skpCn : tensor
skip connection input to the NN block.
Returns
-------
tensor
output of the NN block.
"""
x = F.interpolate(x, scale_factor=2, mode='bilinear')
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
x = F.leaky_relu(self.conv2(torch.cat((x, skpCn), 1)),
negative_slope=0.1)
return x
class UNet(nn.Module):
"""
A class for creating UNet architecture with skip connections.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels):
"""
Parameters
----------
inChannels : int
number of input channels for the UNet.
outChannels : int
number of output channels for the UNet.
"""
super(UNet, self).__init__()
self.conv1 = nn.Conv2d(inChannels, 32, 9, stride=1, padding=4)
self.conv2 = nn.Conv2d(32, 32, 7, stride=1, padding=3)
self.down1 = down(32, 64, 5)
self.down2 = down(64, 128, 3)
self.down3 = down(128, 256, 3)
self.down4 = down(256, 512, 3)
self.down5 = down(512, 512, 3)
self.up1 = up(512, 512)
self.up2 = up(512, 256)
self.up3 = up(256, 128)
self.up4 = up(128, 64)
self.up5 = up(64, 32)
self.conv3 = nn.Conv2d(32, outChannels, 3, stride=1, padding=1)
def forward(self, x):
"""
Returns output tensor after passing input `x` to the neural network.
Parameters
----------
x : tensor
input to the UNet.
Returns
-------
tensor
output of the UNet.
"""
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
s1 = F.leaky_relu(self.conv2(x), negative_slope=0.1)
s2 = self.down1(s1)
s3 = self.down2(s2)
s4 = self.down3(s3)
s5 = self.down4(s4)
x = self.down5(s5)
x = self.up1(x, s5)
x = self.up2(x, s4)
x = self.up3(x, s3)
x = self.up4(x, s2)
x = self.up5(x, s1)
x = F.leaky_relu(self.conv3(x), negative_slope=0.1)
return x
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'inChannels': 4, 'outChannels': 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_convolution_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 32
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_avg_pool2d_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1), None,
eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 64
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_avg_pool2d_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 64 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (32 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (33 + 2 * x0 + 64 * x1), None, eviction_policy
='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_4(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 128
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_avg_pool2d_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 32 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 32 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + 2 * x0 + 32 * x1), None, eviction_policy
='evict_last')
tmp5 = tl.load(in_ptr0 + (17 + 2 * x0 + 32 * x1), None, eviction_policy
='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_6(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 256
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_avg_pool2d_7(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 16 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 16 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (8 + 2 * x0 + 16 * x1), None, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (9 + 2 * x0 + 16 * x1), None, eviction_policy=
'evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_8(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 512
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_avg_pool2d_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), None, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), None, eviction_policy=
'evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_10(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4 % 512
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_11(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4 % 512
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused__to_copy_12(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_13(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.full([1], 1, tl.int64)
tmp10 = tmp8 + tmp9
tmp11 = triton_helpers.minimum(tmp10, tmp9)
tl.store(out_ptr0 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_14(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 - tmp9
tmp11 = triton_helpers.maximum(tmp10, tmp6)
tmp12 = 1.0
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_15(
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4 % 4
x0 = xindex % 4
x6 = xindex // 16
x2 = xindex // 16 % 512
x4 = xindex
tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr6 + x0, None, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr7 + x0, None, eviction_policy='evict_last')
tmp47 = tl.load(in_ptr8 + x1, None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 2, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr2 + (tmp8 + 2 * tmp4 + 4 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp10 = tl.load(in_ptr3 + (tmp8 + 2 * tmp4 + 4 * x6), None,
eviction_policy='evict_last')
tmp12 = tmp10 + tmp11
tmp13 = 0.1
tmp14 = tmp12 * tmp13
tmp15 = tl.where(tmp9, tmp12, tmp14)
tmp17 = tmp16 + tmp1
tmp18 = tmp16 < 0
tmp19 = tl.where(tmp18, tmp17, tmp16)
tmp20 = tl.load(in_ptr2 + (tmp8 + 2 * tmp19 + 4 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp21 = tl.load(in_ptr3 + (tmp8 + 2 * tmp19 + 4 * x6), None,
eviction_policy='evict_last')
tmp22 = tmp21 + tmp11
tmp23 = tmp22 * tmp13
tmp24 = tl.where(tmp20, tmp22, tmp23)
tmp26 = tmp25 + tmp1
tmp27 = tmp25 < 0
tmp28 = tl.where(tmp27, tmp26, tmp25)
tmp29 = tl.load(in_ptr2 + (tmp28 + 2 * tmp19 + 4 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp30 = tl.load(in_ptr3 + (tmp28 + 2 * tmp19 + 4 * x6), None,
eviction_policy='evict_last')
tmp31 = tmp30 + tmp11
tmp32 = tmp31 * tmp13
tmp33 = tl.where(tmp29, tmp31, tmp32)
tmp34 = tmp33 - tmp24
tmp36 = tmp34 * tmp35
tmp37 = tmp24 + tmp36
tmp38 = tl.load(in_ptr2 + (tmp28 + 2 * tmp4 + 4 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp39 = tl.load(in_ptr3 + (tmp28 + 2 * tmp4 + 4 * x6), None,
eviction_policy='evict_last')
tmp40 = tmp39 + tmp11
tmp41 = tmp40 * tmp13
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp42 - tmp15
tmp44 = tmp43 * tmp35
tmp45 = tmp15 + tmp44
tmp46 = tmp45 - tmp37
tmp48 = tmp46 * tmp47
tmp49 = tmp37 + tmp48
tl.store(in_out_ptr1 + x4, tmp49, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_16(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 512
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_17(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 16 % 1024
x0 = xindex % 16
x2 = xindex // 16384
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 512, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 8192 * x2), tmp4, other=0.0).to(tl
.int1)
tmp6 = tl.load(in_ptr1 + (x0 + 16 * x1 + 8192 * x2), tmp4, other=0.0)
tmp7 = tl.load(in_ptr2 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = 0.1
tmp10 = tmp8 * tmp9
tmp11 = tl.where(tmp5, tmp8, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 1024, tl.int64)
tmp17 = tl.load(in_ptr3 + (x0 + 16 * (-512 + x1) + 8192 * x2), tmp14,
other=0.0)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tl.store(out_ptr0 + x3, tmp18, None)
@triton.jit
def triton_poi_fused__to_copy_18(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_19(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.full([1], 1, tl.int64)
tmp10 = tmp8 + tmp9
tmp11 = tl.full([1], 3, tl.int64)
tmp12 = triton_helpers.minimum(tmp10, tmp11)
tl.store(out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_20(out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 - tmp9
tmp11 = triton_helpers.maximum(tmp10, tmp6)
tmp12 = 1.0
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_21(
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 8 % 8
x0 = xindex % 8
x6 = xindex // 64
x2 = xindex // 64 % 512
x4 = xindex
tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr6 + x0, None, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr7 + x0, None, eviction_policy='evict_last')
tmp47 = tl.load(in_ptr8 + x1, None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr2 + (tmp8 + 4 * tmp4 + 16 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp10 = tl.load(in_ptr3 + (tmp8 + 4 * tmp4 + 16 * x6), None,
eviction_policy='evict_last')
tmp12 = tmp10 + tmp11
tmp13 = 0.1
tmp14 = tmp12 * tmp13
tmp15 = tl.where(tmp9, tmp12, tmp14)
tmp17 = tmp16 + tmp1
tmp18 = tmp16 < 0
tmp19 = tl.where(tmp18, tmp17, tmp16)
tmp20 = tl.load(in_ptr2 + (tmp8 + 4 * tmp19 + 16 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp21 = tl.load(in_ptr3 + (tmp8 + 4 * tmp19 + 16 * x6), None,
eviction_policy='evict_last')
tmp22 = tmp21 + tmp11
tmp23 = tmp22 * tmp13
tmp24 = tl.where(tmp20, tmp22, tmp23)
tmp26 = tmp25 + tmp1
tmp27 = tmp25 < 0
tmp28 = tl.where(tmp27, tmp26, tmp25)
tmp29 = tl.load(in_ptr2 + (tmp28 + 4 * tmp19 + 16 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp30 = tl.load(in_ptr3 + (tmp28 + 4 * tmp19 + 16 * x6), None,
eviction_policy='evict_last')
tmp31 = tmp30 + tmp11
tmp32 = tmp31 * tmp13
tmp33 = tl.where(tmp29, tmp31, tmp32)
tmp34 = tmp33 - tmp24
tmp36 = tmp34 * tmp35
tmp37 = tmp24 + tmp36
tmp38 = tl.load(in_ptr2 + (tmp28 + 4 * tmp4 + 16 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp39 = tl.load(in_ptr3 + (tmp28 + 4 * tmp4 + 16 * x6), None,
eviction_policy='evict_last')
tmp40 = tmp39 + tmp11
tmp41 = tmp40 * tmp13
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp42 - tmp15
tmp44 = tmp43 * tmp35
tmp45 = tmp15 + tmp44
tmp46 = tmp45 - tmp37
tmp48 = tmp46 * tmp47
tmp49 = tmp37 + tmp48
tl.store(in_out_ptr1 + x4, tmp49, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_22(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 256
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_23(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 64 % 512
x0 = xindex % 64
x2 = xindex // 32768
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 256, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 64 * x1 + 16384 * x2), tmp4, other=0.0).to(
tl.int1)
tmp6 = tl.load(in_ptr1 + (x0 + 64 * x1 + 16384 * x2), tmp4, other=0.0)
tmp7 = tl.load(in_ptr2 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = 0.1
tmp10 = tmp8 * tmp9
tmp11 = tl.where(tmp5, tmp8, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 512, tl.int64)
tmp17 = tl.load(in_ptr3 + (x0 + 64 * (-256 + x1) + 16384 * x2), tmp14,
other=0.0)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tl.store(out_ptr0 + x3, tmp18, None)
@triton.jit
def triton_poi_fused__to_copy_24(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_25(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.full([1], 1, tl.int64)
tmp10 = tmp8 + tmp9
tmp11 = tl.full([1], 7, tl.int64)
tmp12 = triton_helpers.minimum(tmp10, tmp11)
tl.store(out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_26(out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 - tmp9
tmp11 = triton_helpers.maximum(tmp10, tmp6)
tmp12 = 1.0
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_27(
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 16 % 16
x0 = xindex % 16
x6 = xindex // 256
x2 = xindex // 256 % 256
x4 = xindex
tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr6 + x0, None, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr7 + x0, None, eviction_policy='evict_last')
tmp47 = tl.load(in_ptr8 + x1, None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 8, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr2 + (tmp8 + 8 * tmp4 + 64 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp10 = tl.load(in_ptr3 + (tmp8 + 8 * tmp4 + 64 * x6), None,
eviction_policy='evict_last')
tmp12 = tmp10 + tmp11
tmp13 = 0.1
tmp14 = tmp12 * tmp13
tmp15 = tl.where(tmp9, tmp12, tmp14)
tmp17 = tmp16 + tmp1
tmp18 = tmp16 < 0
tmp19 = tl.where(tmp18, tmp17, tmp16)
tmp20 = tl.load(in_ptr2 + (tmp8 + 8 * tmp19 + 64 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp21 = tl.load(in_ptr3 + (tmp8 + 8 * tmp19 + 64 * x6), None,
eviction_policy='evict_last')
tmp22 = tmp21 + tmp11
tmp23 = tmp22 * tmp13
tmp24 = tl.where(tmp20, tmp22, tmp23)
tmp26 = tmp25 + tmp1
tmp27 = tmp25 < 0
tmp28 = tl.where(tmp27, tmp26, tmp25)
tmp29 = tl.load(in_ptr2 + (tmp28 + 8 * tmp19 + 64 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp30 = tl.load(in_ptr3 + (tmp28 + 8 * tmp19 + 64 * x6), None,
eviction_policy='evict_last')
tmp31 = tmp30 + tmp11
tmp32 = tmp31 * tmp13
tmp33 = tl.where(tmp29, tmp31, tmp32)
tmp34 = tmp33 - tmp24
tmp36 = tmp34 * tmp35
tmp37 = tmp24 + tmp36
tmp38 = tl.load(in_ptr2 + (tmp28 + 8 * tmp4 + 64 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp39 = tl.load(in_ptr3 + (tmp28 + 8 * tmp4 + 64 * x6), None,
eviction_policy='evict_last')
tmp40 = tmp39 + tmp11
tmp41 = tmp40 * tmp13
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp42 - tmp15
tmp44 = tmp43 * tmp35
tmp45 = tmp15 + tmp44
tmp46 = tmp45 - tmp37
tmp48 = tmp46 * tmp47
tmp49 = tmp37 + tmp48
tl.store(in_out_ptr1 + x4, tmp49, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_28(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 128
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_29(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 256 % 256
x0 = xindex % 256
x2 = xindex // 65536
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 128, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 256 * x1 + 32768 * x2), tmp4, other=0.0).to(
tl.int1)
tmp6 = tl.load(in_ptr1 + (x0 + 256 * x1 + 32768 * x2), tmp4, other=0.0)
tmp7 = tl.load(in_ptr2 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = 0.1
tmp10 = tmp8 * tmp9
tmp11 = tl.where(tmp5, tmp8, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 256, tl.int64)
tmp17 = tl.load(in_ptr3 + (x0 + 256 * (-128 + x1) + 32768 * x2), tmp14,
other=0.0)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tl.store(out_ptr0 + x3, tmp18, None)
@triton.jit
def triton_poi_fused__to_copy_30(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_31(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.full([1], 1, tl.int64)
tmp10 = tmp8 + tmp9
tmp11 = tl.full([1], 15, tl.int64)
tmp12 = triton_helpers.minimum(tmp10, tmp11)
tl.store(out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_32(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 - tmp9
tmp11 = triton_helpers.maximum(tmp10, tmp6)
tmp12 = 1.0
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_33(
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 32 % 32
x0 = xindex % 32
x6 = xindex // 1024
x2 = xindex // 1024 % 128
x4 = xindex
tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr6 + x0, None, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr7 + x0, None, eviction_policy='evict_last')
tmp47 = tl.load(in_ptr8 + x1, None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 16, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr2 + (tmp8 + 16 * tmp4 + 256 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp10 = tl.load(in_ptr3 + (tmp8 + 16 * tmp4 + 256 * x6), None,
eviction_policy='evict_last')
tmp12 = tmp10 + tmp11
tmp13 = 0.1
tmp14 = tmp12 * tmp13
tmp15 = tl.where(tmp9, tmp12, tmp14)
tmp17 = tmp16 + tmp1
tmp18 = tmp16 < 0
tmp19 = tl.where(tmp18, tmp17, tmp16)
tmp20 = tl.load(in_ptr2 + (tmp8 + 16 * tmp19 + 256 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp21 = tl.load(in_ptr3 + (tmp8 + 16 * tmp19 + 256 * x6), None,
eviction_policy='evict_last')
tmp22 = tmp21 + tmp11
tmp23 = tmp22 * tmp13
tmp24 = tl.where(tmp20, tmp22, tmp23)
tmp26 = tmp25 + tmp1
tmp27 = tmp25 < 0
tmp28 = tl.where(tmp27, tmp26, tmp25)
tmp29 = tl.load(in_ptr2 + (tmp28 + 16 * tmp19 + 256 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp30 = tl.load(in_ptr3 + (tmp28 + 16 * tmp19 + 256 * x6), None,
eviction_policy='evict_last')
tmp31 = tmp30 + tmp11
tmp32 = tmp31 * tmp13
tmp33 = tl.where(tmp29, tmp31, tmp32)
tmp34 = tmp33 - tmp24
tmp36 = tmp34 * tmp35
tmp37 = tmp24 + tmp36
tmp38 = tl.load(in_ptr2 + (tmp28 + 16 * tmp4 + 256 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp39 = tl.load(in_ptr3 + (tmp28 + 16 * tmp4 + 256 * x6), None,
eviction_policy='evict_last')
tmp40 = tmp39 + tmp11
tmp41 = tmp40 * tmp13
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp42 - tmp15
tmp44 = tmp43 * tmp35
tmp45 = tmp15 + tmp44
tmp46 = tmp45 - tmp37
tmp48 = tmp46 * tmp47
tmp49 = tmp37 + tmp48
tl.store(in_out_ptr1 + x4, tmp49, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_34(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 64
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_35(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 1024 % 128
x0 = xindex % 1024
x2 = xindex // 131072
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 64, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 1024 * x1 + 65536 * x2), tmp4, other=0.0
).to(tl.int1)
tmp6 = tl.load(in_ptr1 + (x0 + 1024 * x1 + 65536 * x2), tmp4, other=0.0)
tmp7 = tl.load(in_ptr2 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = 0.1
tmp10 = tmp8 * tmp9
tmp11 = tl.where(tmp5, tmp8, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 128, tl.int64)
tmp17 = tl.load(in_ptr3 + (x0 + 1024 * (-64 + x1) + 65536 * x2), tmp14,
other=0.0)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tl.store(out_ptr0 + x3, tmp18, None)
@triton.jit
def triton_poi_fused__to_copy_36(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_37(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.full([1], 1, tl.int64)
tmp10 = tmp8 + tmp9
tmp11 = tl.full([1], 31, tl.int64)
tmp12 = triton_helpers.minimum(tmp10, tmp11)
tl.store(out_ptr0 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_38(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 = x0
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 + tmp2
tmp4 = tmp3 * tmp2
tmp5 = tmp4 - tmp2
tmp6 = 0.0
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp7.to(tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 - tmp9
tmp11 = triton_helpers.maximum(tmp10, tmp6)
tmp12 = 1.0
tmp13 = triton_helpers.minimum(tmp11, tmp12)
tl.store(out_ptr0 + x0, tmp13, xmask)
@triton.jit
def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_39(
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 64 % 64
x0 = xindex % 64
x6 = xindex // 4096
x2 = xindex // 4096 % 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr4 + x2, None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr5 + x1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr6 + x0, None, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr7 + x0, None, eviction_policy='evict_last')
tmp47 = tl.load(in_ptr8 + x1, None, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 32, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tmp8 = tl.where(tmp7, tmp6, tmp5)
tmp9 = tl.load(in_ptr2 + (tmp8 + 32 * tmp4 + 1024 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp10 = tl.load(in_ptr3 + (tmp8 + 32 * tmp4 + 1024 * x6), None,
eviction_policy='evict_last')
tmp12 = tmp10 + tmp11
tmp13 = 0.1
tmp14 = tmp12 * tmp13
tmp15 = tl.where(tmp9, tmp12, tmp14)
tmp17 = tmp16 + tmp1
tmp18 = tmp16 < 0
tmp19 = tl.where(tmp18, tmp17, tmp16)
tmp20 = tl.load(in_ptr2 + (tmp8 + 32 * tmp19 + 1024 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp21 = tl.load(in_ptr3 + (tmp8 + 32 * tmp19 + 1024 * x6), None,
eviction_policy='evict_last')
tmp22 = tmp21 + tmp11
tmp23 = tmp22 * tmp13
tmp24 = tl.where(tmp20, tmp22, tmp23)
tmp26 = tmp25 + tmp1
tmp27 = tmp25 < 0
tmp28 = tl.where(tmp27, tmp26, tmp25)
tmp29 = tl.load(in_ptr2 + (tmp28 + 32 * tmp19 + 1024 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp30 = tl.load(in_ptr3 + (tmp28 + 32 * tmp19 + 1024 * x6), None,
eviction_policy='evict_last')
tmp31 = tmp30 + tmp11
tmp32 = tmp31 * tmp13
tmp33 = tl.where(tmp29, tmp31, tmp32)
tmp34 = tmp33 - tmp24
tmp36 = tmp34 * tmp35
tmp37 = tmp24 + tmp36
tmp38 = tl.load(in_ptr2 + (tmp28 + 32 * tmp4 + 1024 * x6), None,
eviction_policy='evict_last').to(tl.int1)
tmp39 = tl.load(in_ptr3 + (tmp28 + 32 * tmp4 + 1024 * x6), None,
eviction_policy='evict_last')
tmp40 = tmp39 + tmp11
tmp41 = tmp40 * tmp13
tmp42 = tl.where(tmp38, tmp40, tmp41)
tmp43 = tmp42 - tmp15
tmp44 = tmp43 * tmp35
tmp45 = tmp15 + tmp44
tmp46 = tmp45 - tmp37
tmp48 = tmp46 * tmp47
tmp49 = tmp37 + tmp48
tl.store(in_out_ptr1 + x4, tmp49, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_40(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 32
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tl.store(out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_41(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 64
x0 = xindex % 4096
x2 = xindex // 262144
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 32, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 131072 * x2), tmp4, other=0.0
).to(tl.int1)
tmp6 = tl.load(in_ptr1 + (x0 + 4096 * x1 + 131072 * x2), tmp4, other=0.0)
tmp7 = tl.load(in_ptr2 + x1, tmp4, eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = 0.1
tmp10 = tmp8 * tmp9
tmp11 = tl.where(tmp5, tmp8, tmp10)
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp4, tmp11, tmp12)
tmp14 = tmp0 >= tmp3
tl.full([1], 64, tl.int64)
tmp17 = tl.load(in_ptr3 + (x0 + 4096 * (-32 + x1) + 131072 * x2), tmp14,
other=0.0)
tmp18 = tl.where(tmp4, tmp13, tmp17)
tl.store(out_ptr0 + x3, tmp18, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_42(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 4
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, None)
tl.store(out_ptr1 + x3, tmp7, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47) = args
args.clear()
assert_size_stride(primals_1, (32, 4, 9, 9), (324, 81, 9, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 4, 64, 64), (16384, 4096, 64, 1))
assert_size_stride(primals_4, (32, 32, 7, 7), (1568, 49, 7, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (64, 32, 5, 5), (800, 25, 5, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (64, 64, 5, 5), (1600, 25, 5, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_11, (128,), (1,))
assert_size_stride(primals_12, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_13, (128,), (1,))
assert_size_stride(primals_14, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_15, (256,), (1,))
assert_size_stride(primals_16, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_17, (256,), (1,))
assert_size_stride(primals_18, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_19, (512,), (1,))
assert_size_stride(primals_20, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_21, (512,), (1,))
assert_size_stride(primals_22, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_23, (512,), (1,))
assert_size_stride(primals_24, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_25, (512,), (1,))
assert_size_stride(primals_26, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_27, (512,), (1,))
assert_size_stride(primals_28, (512, 1024, 3, 3), (9216, 9, 3, 1))
assert_size_stride(primals_29, (512,), (1,))
assert_size_stride(primals_30, (256, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_31, (256,), (1,))
assert_size_stride(primals_32, (256, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_33, (256,), (1,))
assert_size_stride(primals_34, (128, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_35, (128,), (1,))
assert_size_stride(primals_36, (128, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_37, (128,), (1,))
assert_size_stride(primals_38, (64, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_39, (64,), (1,))
assert_size_stride(primals_40, (64, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_41, (64,), (1,))
assert_size_stride(primals_42, (32, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_43, (32,), (1,))
assert_size_stride(primals_44, (32, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_45, (32,), (1,))
assert_size_stride(primals_46, (4, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_47, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(4, 4), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf1 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.bool)
buf2 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_leaky_relu_0[grid(524288)](buf0,
primals_2, buf1, buf2, 524288, XBLOCK=1024, num_warps=4,
num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(3, 3), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf4 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.bool)
buf5 = buf0
del buf0
triton_poi_fused_convolution_leaky_relu_0[grid(524288)](buf3,
primals_5, buf4, buf5, 524288, XBLOCK=1024, num_warps=4,
num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 32, 32, 32), (32768, 1024, 32, 1),
torch.float32)
triton_poi_fused_avg_pool2d_1[grid(131072)](buf5, buf6, 131072,
XBLOCK=512, num_warps=8, num_stages=1)
buf7 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1),
padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf7, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf8 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.bool)
buf9 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.float32)
triton_poi_fused_convolution_leaky_relu_2[grid(262144)](buf7,
primals_7, buf8, buf9, 262144, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_7
buf10 = extern_kernels.convolution(buf9, primals_8, stride=(1, 1),
padding=(2, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf11 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.bool)
buf12 = buf7
del buf7
triton_poi_fused_convolution_leaky_relu_2[grid(262144)](buf10,
primals_9, buf11, buf12, 262144, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_9
buf13 = empty_strided_cuda((4, 64, 16, 16), (16384, 256, 16, 1),
torch.float32)
triton_poi_fused_avg_pool2d_3[grid(65536)](buf12, buf13, 65536,
XBLOCK=256, num_warps=4, num_stages=1)
buf14 = extern_kernels.convolution(buf13, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 128, 16, 16), (32768, 256, 16, 1))
buf15 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf16 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.float32)
triton_poi_fused_convolution_leaky_relu_4[grid(131072)](buf14,
primals_11, buf15, buf16, 131072, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_11
buf17 = extern_kernels.convolution(buf16, primals_12, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 128, 16, 16), (32768, 256, 16, 1))
buf18 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
buf19 = buf14
del buf14
triton_poi_fused_convolution_leaky_relu_4[grid(131072)](buf17,
primals_13, buf18, buf19, 131072, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_13
buf20 = empty_strided_cuda((4, 128, 8, 8), (8192, 64, 8, 1), torch.
float32)
triton_poi_fused_avg_pool2d_5[grid(32768)](buf19, buf20, 32768,
XBLOCK=128, num_warps=4, num_stages=1)
buf21 = extern_kernels.convolution(buf20, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf21, (4, 256, 8, 8), (16384, 64, 8, 1))
buf22 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.bool)
buf23 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.float32)
triton_poi_fused_convolution_leaky_relu_6[grid(65536)](buf21,
primals_15, buf22, buf23, 65536, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_15
buf24 = extern_kernels.convolution(buf23, primals_16, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf24, (4, 256, 8, 8), (16384, 64, 8, 1))
buf25 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.bool)
buf26 = buf21
del buf21
triton_poi_fused_convolution_leaky_relu_6[grid(65536)](buf24,
primals_17, buf25, buf26, 65536, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_17
buf27 = empty_strided_cuda((4, 256, 4, 4), (4096, 16, 4, 1), torch.
float32)
triton_poi_fused_avg_pool2d_7[grid(16384)](buf26, buf27, 16384,
XBLOCK=128, num_warps=4, num_stages=1)
buf28 = extern_kernels.convolution(buf27, primals_18, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf28, (4, 512, 4, 4), (8192, 16, 4, 1))
buf29 = empty_strided_cuda((4, 512, 4, 4), (8192, 16, 4, 1), torch.bool
)
buf30 = empty_strided_cuda((4, 512, 4, 4), (8192, 16, 4, 1), torch.
float32)
triton_poi_fused_convolution_leaky_relu_8[grid(32768)](buf28,
primals_19, buf29, buf30, 32768, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_19
buf31 = extern_kernels.convolution(buf30, primals_20, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf31, (4, 512, 4, 4), (8192, 16, 4, 1))
buf32 = empty_strided_cuda((4, 512, 4, 4), (8192, 16, 4, 1), torch.bool
)
buf33 = buf28
del buf28
triton_poi_fused_convolution_leaky_relu_8[grid(32768)](buf31,
primals_21, buf32, buf33, 32768, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_21
buf34 = empty_strided_cuda((4, 512, 2, 2), (2048, 4, 2, 1), torch.
float32)
triton_poi_fused_avg_pool2d_9[grid(8192)](buf33, buf34, 8192,
XBLOCK=128, num_warps=4, num_stages=1)
buf35 = extern_kernels.convolution(buf34, primals_22, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf35, (4, 512, 2, 2), (2048, 4, 2, 1))
buf36 = empty_strided_cuda((4, 512, 2, 2), (2048, 4, 2, 1), torch.bool)
buf37 = empty_strided_cuda((4, 512, 2, 2), (2048, 4, 2, 1), torch.
float32)
triton_poi_fused_convolution_leaky_relu_10[grid(8192)](buf35,
primals_23, buf36, buf37, 8192, XBLOCK=256, num_warps=4,
num_stages=1)
del buf35
del primals_23
buf38 = extern_kernels.convolution(buf37, primals_24, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf38, (4, 512, 2, 2), (2048, 4, 2, 1))
buf39 = empty_strided_cuda((4, 512, 2, 2), (2048, 4, 2, 1), torch.bool)
triton_poi_fused_convolution_leaky_relu_11[grid(8192)](buf38,
primals_25, buf39, 8192, XBLOCK=128, num_warps=4, num_stages=1)
buf40 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_12[grid(4)](buf40, 4, XBLOCK=4, num_warps
=1, num_stages=1)
buf41 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_13[grid(4)](buf41, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf42 = empty_strided_cuda((4,), (1,), torch.int64)
triton_poi_fused__to_copy_12[grid(4)](buf42, 4, XBLOCK=4, num_warps
=1, num_stages=1)
buf43 = empty_strided_cuda((4,), (1,), torch.int64)
triton_poi_fused_add_clamp_13[grid(4)](buf43, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf46 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_14[grid(4)](buf46,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf48 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_14[grid(4)](buf48,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf45 = buf31
del buf31
buf49 = buf45
del buf45
buf50 = buf49
del buf49
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_15[
grid(32768)](buf50, buf41, buf42, buf39, buf38, primals_25,
buf40, buf43, buf46, buf48, 32768, XBLOCK=128, num_warps=4,
num_stages=1)
del buf38
del primals_25
buf51 = extern_kernels.convolution(buf50, primals_26, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf51, (4, 512, 4, 4), (8192, 16, 4, 1))
buf52 = empty_strided_cuda((4, 512, 4, 4), (8192, 16, 4, 1), torch.bool
)
triton_poi_fused_convolution_leaky_relu_16[grid(32768)](buf51,
primals_27, buf52, 32768, XBLOCK=128, num_warps=4, num_stages=1)
buf53 = reinterpret_tensor(buf24, (4, 1024, 4, 4), (16384, 16, 4, 1), 0
)
del buf24
triton_poi_fused_cat_17[grid(65536)](buf52, buf51, primals_27,
buf33, buf53, 65536, XBLOCK=256, num_warps=4, num_stages=1)
del buf51
del primals_27
buf54 = extern_kernels.convolution(buf53, primals_28, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf54, (4, 512, 4, 4), (8192, 16, 4, 1))
buf55 = empty_strided_cuda((4, 512, 4, 4), (8192, 16, 4, 1), torch.bool
)
triton_poi_fused_convolution_leaky_relu_16[grid(32768)](buf54,
primals_29, buf55, 32768, XBLOCK=128, num_warps=4, num_stages=1)
buf56 = empty_strided_cuda((8, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_18[grid(8)](buf56, 8, XBLOCK=8, num_warps
=1, num_stages=1)
buf57 = empty_strided_cuda((8, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_19[grid(8)](buf57, 8, XBLOCK=8,
num_warps=1, num_stages=1)
buf58 = empty_strided_cuda((8,), (1,), torch.int64)
triton_poi_fused__to_copy_18[grid(8)](buf58, 8, XBLOCK=8, num_warps
=1, num_stages=1)
buf59 = empty_strided_cuda((8,), (1,), torch.int64)
triton_poi_fused_add_clamp_19[grid(8)](buf59, 8, XBLOCK=8,
num_warps=1, num_stages=1)
buf62 = empty_strided_cuda((8,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_20[grid(8)](buf62,
8, XBLOCK=8, num_warps=1, num_stages=1)
buf64 = empty_strided_cuda((8, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_20[grid(8)](buf64,
8, XBLOCK=8, num_warps=1, num_stages=1)
buf61 = reinterpret_tensor(buf17, (4, 512, 8, 8), (32768, 64, 8, 1), 0)
del buf17
buf65 = buf61
del buf61
buf66 = buf65
del buf65
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_21[
grid(131072)](buf66, buf57, buf58, buf55, buf54, primals_29,
buf56, buf59, buf62, buf64, 131072, XBLOCK=512, num_warps=8,
num_stages=1)
del buf54
del primals_29
buf67 = extern_kernels.convolution(buf66, primals_30, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf67, (4, 256, 8, 8), (16384, 64, 8, 1))
buf68 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.bool)
triton_poi_fused_convolution_leaky_relu_22[grid(65536)](buf67,
primals_31, buf68, 65536, XBLOCK=512, num_warps=4, num_stages=1)
buf69 = empty_strided_cuda((4, 512, 8, 8), (32768, 64, 8, 1), torch
.float32)
triton_poi_fused_cat_23[grid(131072)](buf68, buf67, primals_31,
buf26, buf69, 131072, XBLOCK=512, num_warps=8, num_stages=1)
del buf67
del primals_31
buf70 = extern_kernels.convolution(buf69, primals_32, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf70, (4, 256, 8, 8), (16384, 64, 8, 1))
buf71 = empty_strided_cuda((4, 256, 8, 8), (16384, 64, 8, 1), torch
.bool)
triton_poi_fused_convolution_leaky_relu_22[grid(65536)](buf70,
primals_33, buf71, 65536, XBLOCK=512, num_warps=4, num_stages=1)
buf72 = empty_strided_cuda((16, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_24[grid(16)](buf72, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf73 = empty_strided_cuda((16, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_25[grid(16)](buf73, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf74 = empty_strided_cuda((16,), (1,), torch.int64)
triton_poi_fused__to_copy_24[grid(16)](buf74, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf75 = empty_strided_cuda((16,), (1,), torch.int64)
triton_poi_fused_add_clamp_25[grid(16)](buf75, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf78 = empty_strided_cuda((16,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_26[grid(16)](buf78,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf80 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_26[grid(16)](buf80,
16, XBLOCK=16, num_warps=1, num_stages=1)
buf77 = reinterpret_tensor(buf10, (4, 256, 16, 16), (65536, 256, 16,
1), 0)
del buf10
buf81 = buf77
del buf77
buf82 = buf81
del buf81
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_27[
grid(262144)](buf82, buf73, buf74, buf71, buf70, primals_33,
buf72, buf75, buf78, buf80, 262144, XBLOCK=512, num_warps=8,
num_stages=1)
del primals_33
buf83 = extern_kernels.convolution(buf82, primals_34, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf83, (4, 128, 16, 16), (32768, 256, 16, 1))
buf84 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
triton_poi_fused_convolution_leaky_relu_28[grid(131072)](buf83,
primals_35, buf84, 131072, XBLOCK=1024, num_warps=4, num_stages=1)
buf85 = empty_strided_cuda((4, 256, 16, 16), (65536, 256, 16, 1),
torch.float32)
triton_poi_fused_cat_29[grid(262144)](buf84, buf83, primals_35,
buf19, buf85, 262144, XBLOCK=512, num_warps=8, num_stages=1)
del buf83
del primals_35
buf86 = extern_kernels.convolution(buf85, primals_36, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf86, (4, 128, 16, 16), (32768, 256, 16, 1))
buf87 = empty_strided_cuda((4, 128, 16, 16), (32768, 256, 16, 1),
torch.bool)
triton_poi_fused_convolution_leaky_relu_28[grid(131072)](buf86,
primals_37, buf87, 131072, XBLOCK=1024, num_warps=4, num_stages=1)
buf88 = empty_strided_cuda((32, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_30[grid(32)](buf88, 32, XBLOCK=32,
num_warps=1, num_stages=1)
buf89 = empty_strided_cuda((32, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_31[grid(32)](buf89, 32, XBLOCK=32,
num_warps=1, num_stages=1)
buf90 = empty_strided_cuda((32,), (1,), torch.int64)
triton_poi_fused__to_copy_30[grid(32)](buf90, 32, XBLOCK=32,
num_warps=1, num_stages=1)
buf91 = empty_strided_cuda((32,), (1,), torch.int64)
triton_poi_fused_add_clamp_31[grid(32)](buf91, 32, XBLOCK=32,
num_warps=1, num_stages=1)
buf94 = empty_strided_cuda((32,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_32[grid(32)](buf94,
32, XBLOCK=32, num_warps=1, num_stages=1)
buf96 = empty_strided_cuda((32, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_32[grid(32)](buf96,
32, XBLOCK=32, num_warps=1, num_stages=1)
buf93 = reinterpret_tensor(buf3, (4, 128, 32, 32), (131072, 1024,
32, 1), 0)
del buf3
buf97 = buf93
del buf93
buf98 = buf97
del buf97
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_33[
grid(524288)](buf98, buf89, buf90, buf87, buf86, primals_37,
buf88, buf91, buf94, buf96, 524288, XBLOCK=512, num_warps=8,
num_stages=1)
del buf86
del primals_37
buf99 = extern_kernels.convolution(buf98, primals_38, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf99, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf100 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.bool)
triton_poi_fused_convolution_leaky_relu_34[grid(262144)](buf99,
primals_39, buf100, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
buf101 = empty_strided_cuda((4, 128, 32, 32), (131072, 1024, 32, 1),
torch.float32)
triton_poi_fused_cat_35[grid(524288)](buf100, buf99, primals_39,
buf12, buf101, 524288, XBLOCK=512, num_warps=8, num_stages=1)
del buf99
del primals_39
buf102 = extern_kernels.convolution(buf101, primals_40, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf102, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf103 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.bool)
triton_poi_fused_convolution_leaky_relu_34[grid(262144)](buf102,
primals_41, buf103, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
buf104 = empty_strided_cuda((64, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_36[grid(64)](buf104, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf105 = empty_strided_cuda((64, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_37[grid(64)](buf105, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf106 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused__to_copy_36[grid(64)](buf106, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf107 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused_add_clamp_37[grid(64)](buf107, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf110 = empty_strided_cuda((64,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_38[grid(64)](buf110,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf112 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_38[grid(64)](buf112,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf109 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
buf113 = buf109
del buf109
buf114 = buf113
del buf113
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_39[
grid(1048576)](buf114, buf105, buf106, buf103, buf102,
primals_41, buf104, buf107, buf110, buf112, 1048576, XBLOCK=
1024, num_warps=4, num_stages=1)
del buf102
del primals_41
buf115 = extern_kernels.convolution(buf114, primals_42, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf115, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf116 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_leaky_relu_40[grid(524288)](buf115,
primals_43, buf116, 524288, XBLOCK=1024, num_warps=4, num_stages=1)
buf117 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_41[grid(1048576)](buf116, buf115, primals_43,
buf5, buf117, 1048576, XBLOCK=512, num_warps=8, num_stages=1)
del primals_43
buf118 = extern_kernels.convolution(buf117, primals_44, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf118, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf119 = empty_strided_cuda((4, 32, 64, 64), (131072, 4096, 64, 1),
torch.bool)
buf120 = buf115
del buf115
triton_poi_fused_convolution_leaky_relu_0[grid(524288)](buf118,
primals_45, buf119, buf120, 524288, XBLOCK=1024, num_warps=4,
num_stages=1)
del buf118
del primals_45
buf121 = extern_kernels.convolution(buf120, primals_46, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf121, (4, 4, 64, 64), (16384, 4096, 64, 1))
buf122 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.bool)
buf123 = reinterpret_tensor(buf70, (4, 4, 64, 64), (16384, 4096, 64,
1), 0)
del buf70
triton_poi_fused_convolution_leaky_relu_42[grid(65536)](buf121,
primals_47, buf122, buf123, 65536, XBLOCK=512, num_warps=4,
num_stages=1)
del buf121
del primals_47
return (buf123, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, primals_16, primals_18,
primals_20, primals_22, primals_24, primals_26, primals_28,
primals_30, primals_32, primals_34, primals_36, primals_38,
primals_40, primals_42, primals_44, primals_46, buf1, buf2, buf4,
buf5, buf6, buf8, buf9, buf11, buf12, buf13, buf15, buf16, buf18,
buf19, buf20, buf22, buf23, buf25, buf26, buf27, buf29, buf30,
buf32, buf33, buf34, buf36, buf37, buf39, buf40, buf41, buf42,
buf43, buf46, buf48, buf50, buf52, buf53, buf55, buf56, buf57,
buf58, buf59, buf62, buf64, buf66, buf68, buf69, buf71, buf72,
buf73, buf74, buf75, buf78, buf80, buf82, buf84, buf85, buf87,
buf88, buf89, buf90, buf91, buf94, buf96, buf98, buf100, buf101,
buf103, buf104, buf105, buf106, buf107, buf110, buf112, buf114,
buf116, buf117, buf119, buf120, buf122)
class down(nn.Module):
"""
A class for creating neural network blocks containing layers:
Average Pooling --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels, filterSize):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used as input and output channels for the
second convolutional layer.
filterSize : int
filter size for the convolution filter. input N would create
a N x N filter.
"""
super(down, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, filterSize, stride=
1, padding=int((filterSize - 1) / 2))
self.conv2 = nn.Conv2d(outChannels, outChannels, filterSize, stride
=1, padding=int((filterSize - 1) / 2))
def forward(self, x):
"""
Returns output tensor after passing input `x` to the neural network
block.
Parameters
----------
x : tensor
input to the NN block.
Returns
-------
tensor
output of the NN block.
"""
x = F.avg_pool2d(x, 2)
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
x = F.leaky_relu(self.conv2(x), negative_slope=0.1)
return x
class up(nn.Module):
"""
A class for creating neural network blocks containing layers:
Bilinear interpolation --> Convlution + Leaky ReLU --> Convolution + Leaky ReLU
This is used in the UNet Class to create a UNet like NN architecture.
...
Methods
-------
forward(x, skpCn)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels):
"""
Parameters
----------
inChannels : int
number of input channels for the first convolutional layer.
outChannels : int
number of output channels for the first convolutional layer.
This is also used for setting input and output channels for
the second convolutional layer.
"""
super(up, self).__init__()
self.conv1 = nn.Conv2d(inChannels, outChannels, 3, stride=1, padding=1)
self.conv2 = nn.Conv2d(2 * outChannels, outChannels, 3, stride=1,
padding=1)
def forward(self, x, skpCn):
"""
Returns output tensor after passing input `x` to the neural network
block.
Parameters
----------
x : tensor
input to the NN block.
skpCn : tensor
skip connection input to the NN block.
Returns
-------
tensor
output of the NN block.
"""
x = F.interpolate(x, scale_factor=2, mode='bilinear')
x = F.leaky_relu(self.conv1(x), negative_slope=0.1)
x = F.leaky_relu(self.conv2(torch.cat((x, skpCn), 1)),
negative_slope=0.1)
return x
class UNetNew(nn.Module):
"""
A class for creating UNet architecture with skip connections.
...
Methods
-------
forward(x)
Returns output tensor after passing input `x` to the neural network
block.
"""
def __init__(self, inChannels, outChannels):
"""
Parameters
----------
inChannels : int
number of input channels for the UNet.
outChannels : int
number of output channels for the UNet.
"""
super(UNetNew, self).__init__()
self.conv1 = nn.Conv2d(inChannels, 32, 9, stride=1, padding=4)
self.conv2 = nn.Conv2d(32, 32, 7, stride=1, padding=3)
self.down1 = down(32, 64, 5)
self.down2 = down(64, 128, 3)
self.down3 = down(128, 256, 3)
self.down4 = down(256, 512, 3)
self.down5 = down(512, 512, 3)
self.up1 = up(512, 512)
self.up2 = up(512, 256)
self.up3 = up(256, 128)
self.up4 = up(128, 64)
self.up5 = up(64, 32)
self.conv3 = nn.Conv2d(32, outChannels, 3, stride=1, 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_6 = self.down1.conv1.weight
primals_7 = self.down1.conv1.bias
primals_8 = self.down1.conv2.weight
primals_9 = self.down1.conv2.bias
primals_10 = self.down2.conv1.weight
primals_11 = self.down2.conv1.bias
primals_12 = self.down2.conv2.weight
primals_13 = self.down2.conv2.bias
primals_14 = self.down3.conv1.weight
primals_15 = self.down3.conv1.bias
primals_16 = self.down3.conv2.weight
primals_17 = self.down3.conv2.bias
primals_18 = self.down4.conv1.weight
primals_19 = self.down4.conv1.bias
primals_20 = self.down4.conv2.weight
primals_21 = self.down4.conv2.bias
primals_22 = self.down5.conv1.weight
primals_23 = self.down5.conv1.bias
primals_24 = self.down5.conv2.weight
primals_25 = self.down5.conv2.bias
primals_26 = self.up1.conv1.weight
primals_27 = self.up1.conv1.bias
primals_28 = self.up1.conv2.weight
primals_29 = self.up1.conv2.bias
primals_30 = self.up2.conv1.weight
primals_31 = self.up2.conv1.bias
primals_32 = self.up2.conv2.weight
primals_33 = self.up2.conv2.bias
primals_34 = self.up3.conv1.weight
primals_35 = self.up3.conv1.bias
primals_36 = self.up3.conv2.weight
primals_37 = self.up3.conv2.bias
primals_38 = self.up4.conv1.weight
primals_39 = self.up4.conv1.bias
primals_40 = self.up4.conv2.weight
primals_41 = self.up4.conv2.bias
primals_42 = self.up5.conv1.weight
primals_43 = self.up5.conv1.bias
primals_44 = self.up5.conv2.weight
primals_45 = self.up5.conv2.bias
primals_46 = self.conv3.weight
primals_47 = self.conv3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
primals_40, primals_41, primals_42, primals_43, primals_44,
primals_45, primals_46, primals_47])
return output[0]
|
avinashpaliwal/Deep-SloMo
|
UNet
| false
| 15,057
|
[
"MIT"
] | 76
|
93373aa3cb9fd384fbf905e235fe6eb4f9cac780
|
https://github.com/avinashpaliwal/Deep-SloMo/tree/93373aa3cb9fd384fbf905e235fe6eb4f9cac780
|
NormMLP
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class NormMLP(nn.Module):
def __init__(self, input_size, output_size):
super(NormMLP, self).__init__()
self.linear = nn.Linear(input_size, output_size)
self.layer_norm = nn.LayerNorm(output_size)
def forward(self, activations):
return self.layer_norm(self.linear(F.relu(activations)))
def get_inputs():
return [torch.rand([4, 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._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_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_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
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_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
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](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
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64)](buf1, buf2, buf3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_2[grid(256)](buf1, buf2, buf3,
primals_4, primals_5, buf4, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del buf3
del primals_5
return buf4, primals_4, reinterpret_tensor(buf0, (64, 4), (4, 1), 0), buf1
class NormMLPNew(nn.Module):
def __init__(self, input_size, output_size):
super(NormMLPNew, self).__init__()
self.linear = nn.Linear(input_size, output_size)
self.layer_norm = nn.LayerNorm(output_size)
def forward(self, input_0):
primals_2 = self.linear.weight
primals_3 = self.linear.bias
primals_4 = self.layer_norm.weight
primals_5 = self.layer_norm.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
cogentlabs/apl
|
NormMLP
| false
| 15,058
|
[
"MIT"
] | 50
|
78092b162e019a2df0ab5ea31d4db0b9860090d3
|
https://github.com/cogentlabs/apl/tree/78092b162e019a2df0ab5ea31d4db0b9860090d3
|
SoftTargetCrossEntropyLoss
|
import torch
def _convert_to_one_hot(targets: 'torch.Tensor', classes: 'int'
) ->torch.Tensor:
"""
This function converts target class indices to one-hot vectors,
given the number of classes.
"""
if torch.max(targets).item() >= classes:
raise ValueError('Class Index must be less than number of classes')
one_hot_targets = torch.zeros((targets.shape[0], classes), dtype=torch.
long, device=targets.device)
one_hot_targets.scatter_(1, targets.long(), 1)
return one_hot_targets
class SoftTargetCrossEntropyLoss(torch.nn.CrossEntropyLoss):
"""This loss allows the targets for the cross entropy loss to be multi-label.
Args:
reduction (str): specifies reduction to apply to the output.
normalize_targets (bool): whether the targets should be normalized to a sum of 1
based on the total count of positive targets for a given sample.
"""
def __init__(self, reduction: 'str'='mean', normalize_targets: 'bool'=True
) ->None:
super().__init__(reduction=reduction)
self.normalize_targets = normalize_targets
self._eps: 'float' = torch.finfo(torch.float32).eps
def forward(self, input: 'torch.Tensor', target: 'torch.Tensor'
) ->torch.Tensor:
target = target.detach().clone()
if target.ndim == 1:
if input.shape[0] != target.shape[0]:
raise ValueError(
'SoftTargetCrossEntropyLoss requires input and target to have same batch size!'
)
target = _convert_to_one_hot(target.view(-1, 1), input.shape[1])
target = target.float()
if self.normalize_targets:
target /= self._eps + target.sum(dim=1, keepdim=True)
return super().forward(input, target)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__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_add_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)
tmp15 = tl.load(in_ptr1 + (r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr1 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp20 = tl.load(in_ptr1 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp17 = tmp15 + tmp16
tmp19 = tmp17 + tmp18
tmp21 = tmp19 + tmp20
tmp22 = 1.1920928955078125e-07
tmp23 = tmp21 + tmp22
tmp24 = tmp14 / tmp23
tmp25 = tmp13 * tmp24
tmp26 = tl.broadcast_to(tmp25, [RBLOCK])
tmp28 = triton_helpers.promote_to_tensor(tl.sum(tmp26, 0))
tmp29 = -tmp28
tmp30 = 0.015625
tmp31 = tmp29 * tmp30
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp31, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused__log_softmax_add_div_mul_neg_sum_1[grid(1)](buf3,
buf0, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf3,
def _convert_to_one_hot(targets: 'torch.Tensor', classes: 'int'
) ->torch.Tensor:
"""
This function converts target class indices to one-hot vectors,
given the number of classes.
"""
if torch.max(targets).item() >= classes:
raise ValueError('Class Index must be less than number of classes')
one_hot_targets = torch.zeros((targets.shape[0], classes), dtype=torch.
long, device=targets.device)
one_hot_targets.scatter_(1, targets.long(), 1)
return one_hot_targets
class SoftTargetCrossEntropyLossNew(torch.nn.CrossEntropyLoss):
"""This loss allows the targets for the cross entropy loss to be multi-label.
Args:
reduction (str): specifies reduction to apply to the output.
normalize_targets (bool): whether the targets should be normalized to a sum of 1
based on the total count of positive targets for a given sample.
"""
def __init__(self, reduction: 'str'='mean', normalize_targets: 'bool'=True
) ->None:
super().__init__(reduction=reduction)
self.normalize_targets = normalize_targets
self._eps: 'float' = torch.finfo(torch.float32).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]
|
colin2328/recipes
|
SoftTargetCrossEntropyLoss
| false
| 15,059
|
[
"BSD-3-Clause"
] | 161
|
a6cd0e12c9fcb48749721a6548d0a02319d54bd1
|
https://github.com/colin2328/recipes/tree/a6cd0e12c9fcb48749721a6548d0a02319d54bd1
|
LeakyReLU
|
import torch
import numpy as np
import torch.nn as nn
from numbers import Number
def keep_variance_fn(x):
return x + 0.001
def normcdf(value, mu=0.0, stddev=1.0):
sinv = 1.0 / stddev if isinstance(stddev, Number) else stddev.reciprocal()
return 0.5 * (1.0 + torch.erf((value - mu) * sinv / np.sqrt(2.0)))
def _normal_log_pdf(value, mu, stddev):
var = stddev ** 2
log_scale = np.log(stddev) if isinstance(stddev, Number) else torch.log(
stddev)
return -(value - mu) ** 2 / (2.0 * var) - log_scale - np.log(np.sqrt(
2.0 * np.pi))
def normpdf(value, mu=0.0, stddev=1.0):
return torch.exp(_normal_log_pdf(value, mu, stddev))
class LeakyReLU(nn.Module):
def __init__(self, negative_slope=0.01, keep_variance_fn=None):
super(LeakyReLU, self).__init__()
self._keep_variance_fn = keep_variance_fn
self._negative_slope = negative_slope
def forward(self, features_mean, features_variance):
features_stddev = torch.sqrt(features_variance)
div = features_mean / features_stddev
pdf = normpdf(div)
cdf = normcdf(div)
negative_cdf = 1.0 - cdf
mu_cdf = features_mean * cdf
stddev_pdf = features_stddev * pdf
squared_mean_variance = features_mean ** 2 + features_variance
mean_stddev_pdf = features_mean * stddev_pdf
mean_r = mu_cdf + stddev_pdf
variance_r = (squared_mean_variance * cdf + mean_stddev_pdf -
mean_r ** 2)
mean_n = -features_mean * negative_cdf + stddev_pdf
variance_n = (squared_mean_variance * negative_cdf -
mean_stddev_pdf - mean_n ** 2)
covxy = -mean_r * mean_n
outputs_mean = mean_r - self._negative_slope * mean_n
outputs_variance = (variance_r + self._negative_slope * self.
_negative_slope * variance_n - 2.0 * self._negative_slope * covxy)
if self._keep_variance_fn is not None:
outputs_variance = self._keep_variance_fn(outputs_variance)
return outputs_mean, outputs_variance
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import numpy as np
import torch.nn as nn
from numbers import Number
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_erf_exp_log_mul_neg_pow_rsub_sqrt_sub_0(
in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = libdevice.sqrt(tmp1)
tmp3 = tmp0 / tmp2
tmp4 = 0.0
tmp5 = tmp3 - tmp4
tmp6 = 1.0
tmp7 = tmp5 * tmp6
tmp8 = 1.414213562373095
tmp9 = tmp7 / tmp8
tmp10 = libdevice.erf(tmp9)
tmp11 = tmp10 + tmp6
tmp12 = 0.5
tmp13 = tmp11 * tmp12
tmp14 = tmp0 * tmp13
tmp15 = tmp5 * tmp5
tmp16 = -tmp15
tmp17 = tmp16 * tmp12
tmp18 = 0.9189385332046727
tmp19 = tmp17 - tmp18
tmp20 = tl_math.exp(tmp19)
tmp21 = tmp2 * tmp20
tmp22 = tmp14 + tmp21
tmp23 = -tmp0
tmp24 = tmp6 - tmp13
tmp25 = tmp23 * tmp24
tmp26 = tmp25 + tmp21
tmp27 = 0.01
tmp28 = tmp26 * tmp27
tmp29 = tmp22 - tmp28
tmp30 = tmp0 * tmp0
tmp31 = tmp30 + tmp1
tmp32 = tmp31 * tmp13
tmp33 = tmp0 * tmp21
tmp34 = tmp32 + tmp33
tmp35 = tmp22 * tmp22
tmp36 = tmp34 - tmp35
tmp37 = tmp31 * tmp24
tmp38 = tmp37 - tmp33
tmp39 = tmp26 * tmp26
tmp40 = tmp38 - tmp39
tmp41 = -tmp22
tmp42 = tmp41 * tmp26
tmp43 = 0.0001
tmp44 = tmp40 * tmp43
tmp45 = tmp36 + tmp44
tmp46 = 0.02
tmp47 = tmp42 * tmp46
tmp48 = tmp45 - tmp47
tl.store(out_ptr0 + x0, tmp29, xmask)
tl.store(in_out_ptr0 + x0, tmp48, 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)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_add_div_erf_exp_log_mul_neg_pow_rsub_sqrt_sub_0[grid
(256)](buf4, arg1_1, arg0_1, buf0, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
return buf0, buf4
def keep_variance_fn(x):
return x + 0.001
def normcdf(value, mu=0.0, stddev=1.0):
sinv = 1.0 / stddev if isinstance(stddev, Number) else stddev.reciprocal()
return 0.5 * (1.0 + torch.erf((value - mu) * sinv / np.sqrt(2.0)))
def _normal_log_pdf(value, mu, stddev):
var = stddev ** 2
log_scale = np.log(stddev) if isinstance(stddev, Number) else torch.log(
stddev)
return -(value - mu) ** 2 / (2.0 * var) - log_scale - np.log(np.sqrt(
2.0 * np.pi))
def normpdf(value, mu=0.0, stddev=1.0):
return torch.exp(_normal_log_pdf(value, mu, stddev))
class LeakyReLUNew(nn.Module):
def __init__(self, negative_slope=0.01, keep_variance_fn=None):
super(LeakyReLUNew, self).__init__()
self._keep_variance_fn = keep_variance_fn
self._negative_slope = negative_slope
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
LeakyReLU
| false
| 15,060
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
ReLU
|
import torch
import numpy as np
import torch.nn as nn
from numbers import Number
def keep_variance_fn(x):
return x + 0.001
def normcdf(value, mu=0.0, stddev=1.0):
sinv = 1.0 / stddev if isinstance(stddev, Number) else stddev.reciprocal()
return 0.5 * (1.0 + torch.erf((value - mu) * sinv / np.sqrt(2.0)))
def _normal_log_pdf(value, mu, stddev):
var = stddev ** 2
log_scale = np.log(stddev) if isinstance(stddev, Number) else torch.log(
stddev)
return -(value - mu) ** 2 / (2.0 * var) - log_scale - np.log(np.sqrt(
2.0 * np.pi))
def normpdf(value, mu=0.0, stddev=1.0):
return torch.exp(_normal_log_pdf(value, mu, stddev))
class ReLU(nn.Module):
def __init__(self, keep_variance_fn=None):
super(ReLU, self).__init__()
self._keep_variance_fn = keep_variance_fn
def forward(self, features_mean, features_variance):
features_stddev = torch.sqrt(features_variance)
div = features_mean / features_stddev
pdf = normpdf(div)
cdf = normcdf(div)
outputs_mean = features_mean * cdf + features_stddev * pdf
outputs_variance = (features_mean ** 2 + features_variance
) * cdf + features_mean * features_stddev * pdf - outputs_mean ** 2
if self._keep_variance_fn is not None:
outputs_variance = self._keep_variance_fn(outputs_variance)
return outputs_mean, outputs_variance
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import numpy as np
import torch.nn as nn
from numbers import Number
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_erf_exp_log_mul_neg_pow_sqrt_sub_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = libdevice.sqrt(tmp1)
tmp3 = tmp0 / tmp2
tmp4 = 0.0
tmp5 = tmp3 - tmp4
tmp6 = 1.0
tmp7 = tmp5 * tmp6
tmp8 = 1.414213562373095
tmp9 = tmp7 / tmp8
tmp10 = libdevice.erf(tmp9)
tmp11 = tmp10 + tmp6
tmp12 = 0.5
tmp13 = tmp11 * tmp12
tmp14 = tmp0 * tmp13
tmp15 = tmp5 * tmp5
tmp16 = -tmp15
tmp17 = tmp16 * tmp12
tmp18 = 0.9189385332046727
tmp19 = tmp17 - tmp18
tmp20 = tl_math.exp(tmp19)
tmp21 = tmp2 * tmp20
tmp22 = tmp14 + tmp21
tmp23 = tmp0 * tmp0
tmp24 = tmp23 + tmp1
tmp25 = tmp24 * tmp13
tmp26 = tmp0 * tmp2
tmp27 = tmp26 * tmp20
tmp28 = tmp25 + tmp27
tmp29 = tmp22 * tmp22
tmp30 = tmp28 - tmp29
tl.store(out_ptr0 + x0, tmp22, xmask)
tl.store(out_ptr1 + x0, tmp30, 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)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_erf_exp_log_mul_neg_pow_sqrt_sub_0[grid(256)](
arg1_1, arg0_1, buf0, buf1, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
return buf0, buf1
def keep_variance_fn(x):
return x + 0.001
def normcdf(value, mu=0.0, stddev=1.0):
sinv = 1.0 / stddev if isinstance(stddev, Number) else stddev.reciprocal()
return 0.5 * (1.0 + torch.erf((value - mu) * sinv / np.sqrt(2.0)))
def _normal_log_pdf(value, mu, stddev):
var = stddev ** 2
log_scale = np.log(stddev) if isinstance(stddev, Number) else torch.log(
stddev)
return -(value - mu) ** 2 / (2.0 * var) - log_scale - np.log(np.sqrt(
2.0 * np.pi))
def normpdf(value, mu=0.0, stddev=1.0):
return torch.exp(_normal_log_pdf(value, mu, stddev))
class ReLUNew(nn.Module):
def __init__(self, keep_variance_fn=None):
super(ReLUNew, self).__init__()
self._keep_variance_fn = keep_variance_fn
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
ReLU
| false
| 15,061
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
SoftmaxFocalClassificationLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SoftmaxFocalClassificationLoss(nn.Module):
"""Criterion that computes Focal loss.
According to [1], the Focal loss is computed as follows:
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Arguments:
alpha (float): Weighting factor :math:`\\alpha \\in [0, 1]`.
gamma (float): Focusing parameter :math:`\\gamma >= 0`.
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: ‘none’.
Shape:
- Input: :math:`(N, C, *)` where C = number of classes.
- Target: :math:`(N, *)` where each value is
:math:`0 ≤ targets[i] ≤ C−1`.
Examples:
>>> N = 5 # num_classes
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
>>> loss = kornia.losses.FocalLoss(**kwargs)
>>> input = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = loss(input, target)
>>> output.backward()
References:
[1] https://arxiv.org/abs/1708.02002
"""
def __init__(self, alpha: 'float'=1.0, gamma: 'float'=2.0, reduction:
'str'='none') ->None:
super(SoftmaxFocalClassificationLoss, self).__init__()
self.alpha: 'float' = alpha
self.gamma: 'float' = gamma
self.reduction: 'str' = reduction
self.eps: 'float' = 1e-06
def focal_loss(self, input: 'torch.Tensor', target: 'torch.Tensor',
weights: 'torch.Tensor', alpha: 'float'=1.0, gamma: 'float'=2.0,
reduction: 'str'='none', eps: 'float'=1e-08) ->torch.Tensor:
"""Function that computes Focal loss.
See :class:`~kornia.losses.FocalLoss` for details.
"""
if not torch.is_tensor(input):
raise TypeError('Input type is not a torch.Tensor. Got {}'.
format(type(input)))
if not len(input.shape) >= 2:
raise ValueError('Invalid input shape, we expect BxCx*. Got: {}'
.format(input.shape))
if input.size(0) != target.size(0):
raise ValueError(
'Expected input batch_size ({}) to match target batch_size ({}).'
.format(input.size(0), target.size(0)))
if not input.device == target.device:
raise ValueError(
'input and target must be in the same device. Got: {} and {}'
.format(input.device, target.device))
input_soft: 'torch.Tensor' = F.softmax(input, dim=1) + eps
weight = torch.pow(-input_soft + 1.0, gamma)
focal = -alpha * weight * torch.log(input_soft)
loss_tmp = torch.sum(target * focal, dim=1, keepdims=True)
if weights is None:
return loss_tmp
return loss_tmp * weights
def forward(self, input: 'torch.Tensor', target: 'torch.Tensor',
weights: 'torch.Tensor') ->torch.Tensor:
return self.focal_loss(input, target, weights, self.alpha, self.
gamma, self.reduction, self.eps)
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
@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_add_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 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tmp9 = 1e-06
tmp10 = tmp8 + tmp9
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_log_mul_neg_pow_sum_2(in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp11 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp12 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp21 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp22 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp31 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp32 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = -tmp1
tmp3 = 1.0
tmp4 = tmp2 + tmp3
tmp5 = tmp4 * tmp4
tmp6 = -1.0
tmp7 = tmp5 * tmp6
tmp8 = tl_math.log(tmp1)
tmp9 = tmp7 * tmp8
tmp10 = tmp0 * tmp9
tmp13 = -tmp12
tmp14 = tmp13 + tmp3
tmp15 = tmp14 * tmp14
tmp16 = tmp15 * tmp6
tmp17 = tl_math.log(tmp12)
tmp18 = tmp16 * tmp17
tmp19 = tmp11 * tmp18
tmp20 = tmp10 + tmp19
tmp23 = -tmp22
tmp24 = tmp23 + tmp3
tmp25 = tmp24 * tmp24
tmp26 = tmp25 * tmp6
tmp27 = tl_math.log(tmp22)
tmp28 = tmp26 * tmp27
tmp29 = tmp21 * tmp28
tmp30 = tmp20 + tmp29
tmp33 = -tmp32
tmp34 = tmp33 + tmp3
tmp35 = tmp34 * tmp34
tmp36 = tmp35 * tmp6
tmp37 = tl_math.log(tmp32)
tmp38 = tmp36 * tmp37
tmp39 = tmp31 * tmp38
tmp40 = tmp30 + tmp39
tl.store(out_ptr0 + x2, tmp40, xmask)
@triton.jit
def triton_poi_fused_mul_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
x0 = xindex % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_add_1[grid(256)](buf0, buf1, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del buf0
buf2 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
triton_poi_fused_add_log_mul_neg_pow_sum_2[grid(64)](arg1_1, buf1,
buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg1_1
buf3 = buf1
del buf1
triton_poi_fused_mul_3[grid(256)](buf2, arg2_1, buf3, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del arg2_1
del buf2
return buf3,
class SoftmaxFocalClassificationLossNew(nn.Module):
"""Criterion that computes Focal loss.
According to [1], the Focal loss is computed as follows:
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Arguments:
alpha (float): Weighting factor :math:`\\alpha \\in [0, 1]`.
gamma (float): Focusing parameter :math:`\\gamma >= 0`.
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: ‘none’.
Shape:
- Input: :math:`(N, C, *)` where C = number of classes.
- Target: :math:`(N, *)` where each value is
:math:`0 ≤ targets[i] ≤ C−1`.
Examples:
>>> N = 5 # num_classes
>>> kwargs = {"alpha": 0.5, "gamma": 2.0, "reduction": 'mean'}
>>> loss = kornia.losses.FocalLoss(**kwargs)
>>> input = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = loss(input, target)
>>> output.backward()
References:
[1] https://arxiv.org/abs/1708.02002
"""
def __init__(self, alpha: 'float'=1.0, gamma: 'float'=2.0, reduction:
'str'='none') ->None:
super(SoftmaxFocalClassificationLossNew, self).__init__()
self.alpha: 'float' = alpha
self.gamma: 'float' = gamma
self.reduction: 'str' = reduction
self.eps: 'float' = 1e-06
def focal_loss(self, input: 'torch.Tensor', target: 'torch.Tensor',
weights: 'torch.Tensor', alpha: 'float'=1.0, gamma: 'float'=2.0,
reduction: 'str'='none', eps: 'float'=1e-08) ->torch.Tensor:
"""Function that computes Focal loss.
See :class:`~kornia.losses.FocalLoss` for details.
"""
if not torch.is_tensor(input):
raise TypeError('Input type is not a torch.Tensor. Got {}'.
format(type(input)))
if not len(input.shape) >= 2:
raise ValueError('Invalid input shape, we expect BxCx*. Got: {}'
.format(input.shape))
if input.size(0) != target.size(0):
raise ValueError(
'Expected input batch_size ({}) to match target batch_size ({}).'
.format(input.size(0), target.size(0)))
if not input.device == target.device:
raise ValueError(
'input and target must be in the same device. Got: {} and {}'
.format(input.device, target.device))
input_soft: 'torch.Tensor' = F.softmax(input, dim=1) + eps
weight = torch.pow(-input_soft + 1.0, gamma)
focal = -alpha * weight * torch.log(input_soft)
loss_tmp = torch.sum(target * focal, dim=1, keepdims=True)
if weights is None:
return loss_tmp
return loss_tmp * weights
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]
|
collector-m/BtcDet
|
SoftmaxFocalClassificationLoss
| false
| 15,062
|
[
"Apache-2.0"
] | 108
|
80bee34f2f40931600f812a6edbcb27e51cb7ec3
|
https://github.com/collector-m/BtcDet/tree/80bee34f2f40931600f812a6edbcb27e51cb7ec3
|
AvgPool2d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
def keep_variance_fn(x):
return x + 0.001
class AvgPool2d(nn.Module):
def __init__(self, keep_variance_fn=None, kernel_size=2):
super(AvgPool2d, self).__init__()
self._keep_variance_fn = keep_variance_fn
self.kernel_size = kernel_size
def forward(self, inputs_mean, inputs_variance):
outputs_mean = F.avg_pool2d(inputs_mean, self.kernel_size, stride=2,
padding=1)
outputs_variance = F.avg_pool2d(inputs_variance, self.kernel_size,
stride=2, padding=1)
outputs_variance = outputs_variance / (inputs_mean.size(2) *
inputs_mean.size(3))
if self._keep_variance_fn is not None:
outputs_variance = self._keep_variance_fn(outputs_variance)
return outputs_mean, outputs_variance / (inputs_mean.shape[2] *
inputs_mean.shape[3])
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
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 = 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=0.0)
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=0.0)
tmp18 = 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=0.0)
tmp25 = tmp24 + tmp18
tmp26 = tmp22 & tmp15
tmp27 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2), tmp26 & xmask,
eviction_policy='evict_last', other=0.0)
tmp28 = tmp27 + tmp25
tmp29 = 1 + -2 * x0 + -2 * x1 + (5 * (5 <= 1 + 2 * x0) + (1 + 2 * x0) *
(1 + 2 * x0 < 5)) * (5 * (5 <= 1 + 2 * x1) + (1 + 2 * x1) * (1 + 2 *
x1 < 5)) + -2 * x0 * (5 * (5 <= 1 + 2 * x1) + (1 + 2 * x1) * (1 + 2 *
x1 < 5)) + -2 * x1 * (5 * (5 <= 1 + 2 * x0) + (1 + 2 * x0) * (1 + 2 *
x0 < 5)) + 4 * x0 * x1 + (5 * (5 <= 1 + 2 * x0) + (1 + 2 * x0) * (1 +
2 * x0 < 5)) + (5 * (5 <= 1 + 2 * x1) + (1 + 2 * x1) * (1 + 2 * x1 < 5)
)
tmp30 = tmp28 / tmp29
tl.store(out_ptr0 + x4, tmp30, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_div_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 3 % 3
x0 = xindex % 3
x2 = xindex // 9
x3 = xindex
tmp0 = -1 + 2 * x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + 2 * x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x1 + 16 * x2), tmp10 &
xmask, eviction_policy='evict_last', other=0.0)
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=0.0)
tmp18 = 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=0.0)
tmp25 = tmp24 + tmp18
tmp26 = tmp22 & tmp15
tmp27 = tl.load(in_ptr0 + (2 * x0 + 8 * x1 + 16 * x2), tmp26 & xmask,
eviction_policy='evict_last', other=0.0)
tmp28 = tmp27 + tmp25
tmp29 = 1 + -2 * x0 + -2 * x1 + (5 * (5 <= 1 + 2 * x0) + (1 + 2 * x0) *
(1 + 2 * x0 < 5)) * (5 * (5 <= 1 + 2 * x1) + (1 + 2 * x1) * (1 + 2 *
x1 < 5)) + -2 * x0 * (5 * (5 <= 1 + 2 * x1) + (1 + 2 * x1) * (1 + 2 *
x1 < 5)) + -2 * x1 * (5 * (5 <= 1 + 2 * x0) + (1 + 2 * x0) * (1 + 2 *
x0 < 5)) + 4 * x0 * x1 + (5 * (5 <= 1 + 2 * x0) + (1 + 2 * x0) * (1 +
2 * x0 < 5)) + (5 * (5 <= 1 + 2 * x1) + (1 + 2 * x1) * (1 + 2 * x1 < 5)
)
tmp30 = tmp28 / tmp29
tmp31 = 0.0625
tmp32 = tmp30 * tmp31
tmp33 = tmp32 * tmp31
tl.store(in_out_ptr0 + x3, tmp33, 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, 3, 3), (36, 9, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_0[grid(144)](arg0_1, buf0, 144, XBLOCK=
256, num_warps=4, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
buf2 = buf1
del buf1
triton_poi_fused_avg_pool2d_div_1[grid(144)](buf2, arg1_1, 144,
XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
return buf0, buf2
def keep_variance_fn(x):
return x + 0.001
class AvgPool2dNew(nn.Module):
def __init__(self, keep_variance_fn=None, kernel_size=2):
super(AvgPool2dNew, self).__init__()
self._keep_variance_fn = keep_variance_fn
self.kernel_size = kernel_size
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
AvgPool2d
| false
| 15,063
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
Conv
|
import torch
from torch import nn
class Conv(nn.Module):
"""
Convenience class that does padding and convolution for inputs in the format
[batch_size, sequence length, hidden size]
"""
def __init__(self, input_size, output_size, kernel_size, pad_type):
"""
Parameters:
input_size: Input feature size
output_size: Output feature size
kernel_size: Kernel width
pad_type: left -> pad on the left side (to mask future data),
both -> pad on both sides
"""
super(Conv, self).__init__()
padding = (kernel_size - 1, 0) if pad_type == 'left' else (
kernel_size // 2, (kernel_size - 1) // 2)
self.pad = nn.ConstantPad1d(padding, 0)
self.conv = nn.Conv1d(input_size, output_size, kernel_size=
kernel_size, padding=0)
def forward(self, inputs):
inputs = self.pad(inputs.permute(0, 2, 1))
outputs = self.conv(inputs).permute(0, 2, 1)
return outputs
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4, 'kernel_size': 4,
'pad_type': 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_constant_pad_nd_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 7
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 = -2 + x2
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1, 1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = tl.load(in_ptr0 + (-8 + y0 + 4 * x2 + 16 * y1), tmp5 & xmask &
ymask, eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x2 + 7 * y3), tmp6, 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)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 7), (28, 7, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(16, 7)](primals_1, buf0, 16,
7, XBLOCK=8, YBLOCK=16, 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 reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), primals_2, buf0
class ConvNew(nn.Module):
"""
Convenience class that does padding and convolution for inputs in the format
[batch_size, sequence length, hidden size]
"""
def __init__(self, input_size, output_size, kernel_size, pad_type):
"""
Parameters:
input_size: Input feature size
output_size: Output feature size
kernel_size: Kernel width
pad_type: left -> pad on the left side (to mask future data),
both -> pad on both sides
"""
super(ConvNew, self).__init__()
padding = (kernel_size - 1, 0) if pad_type == 'left' else (
kernel_size // 2, (kernel_size - 1) // 2)
self.pad = nn.ConstantPad1d(padding, 0)
self.conv = nn.Conv1d(input_size, output_size, kernel_size=
kernel_size, padding=0)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_3 = self.conv.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
colincen/coach
|
Conv
| false
| 15,064
|
[
"MIT"
] | 72
|
2b1b543851cc7ba359f48dac6a5c72f1ced9b530
|
https://github.com/colincen/coach/tree/2b1b543851cc7ba359f48dac6a5c72f1ced9b530
|
FCN8VGG16
|
import torch
import numpy as np
from torch import nn
import torch.utils.model_zoo as model_zoo
def conv3x3(in_planes, out_planes, stride=1, padding=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=(3, 3), stride=(
stride, stride), padding=(padding, padding))
def get_upsampling_weight(in_channels, out_channels, kernel_size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (kernel_size + 1) // 2
if kernel_size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:kernel_size, :kernel_size]
filt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) /
factor)
weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size),
dtype=np.float64)
weight[range(in_channels), range(out_channels), :, :] = filt
return torch.from_numpy(weight).float()
class FCN8VGG16(nn.Module):
def __init__(self, n_classes):
super().__init__()
self.n_classes = n_classes
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
self.relu = nn.ReLU(inplace=True)
self.conv1_1 = conv3x3(3, 64, stride=1, padding=100)
self.conv1_2 = conv3x3(64, 64)
self.conv2_1 = conv3x3(64, 128)
self.conv2_2 = conv3x3(128, 128)
self.conv3_1 = conv3x3(128, 256)
self.conv3_2 = conv3x3(256, 256)
self.conv3_3 = conv3x3(256, 256)
self.conv4_1 = conv3x3(256, 512)
self.conv4_2 = conv3x3(512, 512)
self.conv4_3 = conv3x3(512, 512)
self.conv5_1 = conv3x3(512, 512)
self.conv5_2 = conv3x3(512, 512)
self.conv5_3 = conv3x3(512, 512)
self.fc6 = nn.Conv2d(512, 4096, kernel_size=7, stride=1, padding=0)
self.dropout_f6 = nn.Dropout()
self.fc7 = nn.Conv2d(4096, 4096, kernel_size=1, stride=1, padding=0)
self.dropout_f7 = nn.Dropout()
self.scoring_layer = nn.Conv2d(4096, self.n_classes, kernel_size=1,
stride=1, padding=0)
self.upscore2 = nn.ConvTranspose2d(self.n_classes, self.n_classes,
kernel_size=4, stride=2, bias=False)
self.upscore_pool4 = nn.ConvTranspose2d(self.n_classes, self.
n_classes, kernel_size=4, stride=2, bias=False)
self.upscore8 = nn.ConvTranspose2d(self.n_classes, self.n_classes,
kernel_size=16, stride=8, bias=False)
self.scoring_layer.weight.data.zero_()
self.scoring_layer.bias.data.zero_()
self.score_pool3 = nn.Conv2d(256, self.n_classes, kernel_size=1)
self.score_pool4 = nn.Conv2d(512, self.n_classes, kernel_size=1)
self.score_pool3.weight.data.zero_()
self.score_pool3.bias.data.zero_()
self.score_pool4.weight.data.zero_()
self.score_pool4.bias.data.zero_()
self.upscore2.weight.data.copy_(get_upsampling_weight(self.
n_classes, self.n_classes, 4))
self.upscore_pool4.weight.data.copy_(get_upsampling_weight(self.
n_classes, self.n_classes, 4))
self.upscore8.weight.data.copy_(get_upsampling_weight(self.
n_classes, self.n_classes, 16))
pth_url = 'https://download.pytorch.org/models/vgg16-397923af.pth'
state_dict = model_zoo.load_url(pth_url)
layer_names = [layer_name for layer_name in state_dict]
counter = 0
for p in self.parameters():
if counter < 26:
p.data = state_dict[layer_names[counter]]
elif counter == 26:
p.data = state_dict[layer_names[counter]].view(4096, 512, 7, 7)
elif counter == 27:
p.data = state_dict[layer_names[counter]]
elif counter == 28:
p.data = state_dict[layer_names[counter]].view(4096, 4096, 1, 1
)
elif counter == 29:
p.data = state_dict[layer_names[counter]]
counter += 1
def forward(self, x):
_n, _c, h, w = x.size()
conv1_1 = self.relu(self.conv1_1(x))
conv1_2 = self.relu(self.conv1_2(conv1_1))
pool1 = self.pool(conv1_2)
conv2_1 = self.relu(self.conv2_1(pool1))
conv2_2 = self.relu(self.conv2_2(conv2_1))
pool2 = self.pool(conv2_2)
conv3_1 = self.relu(self.conv3_1(pool2))
conv3_2 = self.relu(self.conv3_2(conv3_1))
conv3_3 = self.relu(self.conv3_3(conv3_2))
pool3 = self.pool(conv3_3)
conv4_1 = self.relu(self.conv4_1(pool3))
conv4_2 = self.relu(self.conv4_2(conv4_1))
conv4_3 = self.relu(self.conv4_3(conv4_2))
pool4 = self.pool(conv4_3)
conv5_1 = self.relu(self.conv5_1(pool4))
conv5_2 = self.relu(self.conv5_2(conv5_1))
conv5_3 = self.relu(self.conv5_3(conv5_2))
pool5 = self.pool(conv5_3)
fc6 = self.dropout_f6(self.relu(self.fc6(pool5)))
fc7 = self.dropout_f7(self.relu(self.fc7(fc6)))
scores = self.scoring_layer(fc7)
upscore2 = self.upscore2(scores)
score_pool4 = self.score_pool4(pool4)
score_pool4c = score_pool4[:, :, 5:5 + upscore2.size(2), 5:5 +
upscore2.size(3)]
upscore_pool4 = self.upscore_pool4(score_pool4c + upscore2)
score_pool3 = self.score_pool3(pool3)
score_pool3c = score_pool3[:, :, 9:9 + upscore_pool4.size(2), 9:9 +
upscore_pool4.size(3)]
output = self.upscore8(score_pool3c + upscore_pool4)
return output[:, :, 31:31 + h, 31:31 + w].contiguous()
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {'n_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import numpy as np
from torch import nn
import torch.utils.model_zoo as model_zoo
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 12
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 192
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 27 * 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) * 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_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 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_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_6(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_7(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_8(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 % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 512 * x2 + 4608 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_9(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 49
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 % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 49 * y3), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 512 * x2 + 25088 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_10(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_11(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 256
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 256 * y3), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (y0 + 4 * x2 + 1024 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_relu_12(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 17572864
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_13(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4393216
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x1 = xindex // 64 % 131
x2 = xindex // 8384
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x1 + 33536 * x2), xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 128 * x1 + 33536 * x2), xmask)
tmp3 = tl.load(in_ptr0 + (16768 + x0 + 128 * x1 + 33536 * x2), xmask)
tmp5 = tl.load(in_ptr0 + (16832 + x0 + 128 * x1 + 33536 * x2), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_14(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 8786432
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_15(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)
x2 = xindex // 8448 % 66
x1 = xindex // 128 % 66
x0 = xindex % 128
x3 = xindex // 557568
x6 = xindex
tmp0 = 2 * x2
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 131, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = 2 * x1
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (x0 + 256 * x1 + 33536 * x2 + 2196608 * x3),
tmp10, other=float('-inf'))
tmp12 = 1 + 2 * x1
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (128 + x0 + 256 * x1 + 33536 * x2 + 2196608 *
x3), tmp16, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + 2 * x2
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp22 & tmp9
tmp24 = tl.load(in_ptr0 + (16768 + x0 + 256 * x1 + 33536 * x2 + 2196608 *
x3), tmp23, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = tmp22 & tmp15
tmp27 = tl.load(in_ptr0 + (16896 + x0 + 256 * x1 + 33536 * x2 + 2196608 *
x3), tmp26, other=float('-inf'))
tmp28 = triton_helpers.maximum(tmp27, tmp25)
tmp29 = tmp17 > tmp11
tmp30 = tl.full([1], 1, tl.int8)
tmp31 = tl.full([1], 0, tl.int8)
tmp32 = tl.where(tmp29, tmp30, tmp31)
tmp33 = tmp24 > tmp18
tmp34 = tl.full([1], 2, tl.int8)
tmp35 = tl.where(tmp33, tmp34, tmp32)
tmp36 = tmp27 > tmp25
tmp37 = tl.full([1], 3, tl.int8)
tmp38 = tl.where(tmp36, tmp37, tmp35)
tl.store(out_ptr0 + x6, tmp28, None)
tl.store(out_ptr1 + x6, tmp38, None)
@triton.jit
def triton_poi_fused_convolution_relu_16(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_max_pool2d_with_indices_17(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1115136
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 256
x1 = xindex // 256 % 33
x2 = xindex // 8448
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 512 * x1 + 33792 * x2), xmask)
tmp1 = tl.load(in_ptr0 + (256 + x0 + 512 * x1 + 33792 * x2), xmask)
tmp3 = tl.load(in_ptr0 + (16896 + x0 + 512 * x1 + 33792 * x2), xmask)
tmp5 = tl.load(in_ptr0 + (17152 + x0 + 512 * x1 + 33792 * x2), xmask)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, xmask)
tl.store(out_ptr1 + x3, tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_18(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_19(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex // 8704 % 17
x1 = xindex // 512 % 17
x0 = xindex % 512
x3 = xindex // 147968
x6 = xindex
tmp0 = 2 * x2
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 33, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = 2 * x1
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (x0 + 1024 * x1 + 33792 * x2 + 557568 * x3),
tmp10, other=float('-inf'))
tmp12 = 1 + 2 * x1
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (512 + x0 + 1024 * x1 + 33792 * x2 + 557568 *
x3), tmp16, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + 2 * x2
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp22 & tmp9
tmp24 = tl.load(in_ptr0 + (16896 + x0 + 1024 * x1 + 33792 * x2 + 557568 *
x3), tmp23, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = tmp22 & tmp15
tmp27 = tl.load(in_ptr0 + (17408 + x0 + 1024 * x1 + 33792 * x2 + 557568 *
x3), tmp26, other=float('-inf'))
tmp28 = triton_helpers.maximum(tmp27, tmp25)
tmp29 = tmp17 > tmp11
tmp30 = tl.full([1], 1, tl.int8)
tmp31 = tl.full([1], 0, tl.int8)
tmp32 = tl.where(tmp29, tmp30, tmp31)
tmp33 = tmp24 > tmp18
tmp34 = tl.full([1], 2, tl.int8)
tmp35 = tl.where(tmp33, tmp34, tmp32)
tmp36 = tmp27 > tmp25
tmp37 = tl.full([1], 3, tl.int8)
tmp38 = tl.where(tmp36, tmp37, tmp35)
tl.store(out_ptr0 + x6, tmp28, None)
tl.store(out_ptr1 + x6, tmp38, None)
@triton.jit
def triton_poi_fused_convolution_relu_20(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_21(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)
x2 = xindex // 4608 % 9
x1 = xindex // 512 % 9
x0 = xindex % 512
x3 = xindex // 41472
x6 = xindex
tmp0 = 2 * x2
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 17, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = 2 * x1
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (x0 + 1024 * x1 + 17408 * x2 + 147968 * x3),
tmp10, other=float('-inf'))
tmp12 = 1 + 2 * x1
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (512 + x0 + 1024 * x1 + 17408 * x2 + 147968 *
x3), tmp16, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + 2 * x2
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp22 & tmp9
tmp24 = tl.load(in_ptr0 + (8704 + x0 + 1024 * x1 + 17408 * x2 + 147968 *
x3), tmp23, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = tmp22 & tmp15
tmp27 = tl.load(in_ptr0 + (9216 + x0 + 1024 * x1 + 17408 * x2 + 147968 *
x3), tmp26, other=float('-inf'))
tmp28 = triton_helpers.maximum(tmp27, tmp25)
tmp29 = tmp17 > tmp11
tmp30 = tl.full([1], 1, tl.int8)
tmp31 = tl.full([1], 0, tl.int8)
tmp32 = tl.where(tmp29, tmp30, tmp31)
tmp33 = tmp24 > tmp18
tmp34 = tl.full([1], 2, tl.int8)
tmp35 = tl.where(tmp33, tmp34, tmp32)
tmp36 = tmp27 > tmp25
tmp37 = tl.full([1], 3, tl.int8)
tmp38 = tl.where(tmp36, tmp37, tmp35)
tl.store(out_ptr0 + x6, tmp28, None)
tl.store(out_ptr1 + x6, tmp38, None)
@triton.jit
def triton_poi_fused_convolution_relu_22(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 % 4096
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_23(in_out_ptr0, in_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_24(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 32 % 8
x3 = xindex // 256
x4 = xindex % 32
x0 = xindex % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (360 + x4 + 68 * x2 + 1156 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr0 + x5, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x5, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_25(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 5184
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 72 % 18
x3 = xindex // 1296
x4 = xindex % 72
x0 = xindex % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (1224 + x4 + 132 * x2 + 4356 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_out_ptr0 + x5, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x5, tmp4, xmask)
@triton.jit
def triton_poi_fused_clone_26(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl
.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex % 64
x3 = xindex // 64
y0 = yindex % 4
y1 = yindex // 4
x5 = xindex
y4 = yindex
tmp0 = tl.load(in_ptr0 + (18972 + y0 + 4 * x2 + 608 * x3 + 92416 * y1),
ymask, eviction_policy='evict_last')
tl.store(out_ptr0 + (x5 + 4096 * y4), tmp0, ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40) = args
args.clear()
assert_size_stride(primals_1, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_2, (64, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_3, (64,), (1,))
assert_size_stride(primals_4, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_9, (128,), (1,))
assert_size_stride(primals_10, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_11, (256,), (1,))
assert_size_stride(primals_12, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_13, (256,), (1,))
assert_size_stride(primals_14, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_15, (256,), (1,))
assert_size_stride(primals_16, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_17, (512,), (1,))
assert_size_stride(primals_18, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_19, (512,), (1,))
assert_size_stride(primals_20, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_21, (512,), (1,))
assert_size_stride(primals_22, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_23, (512,), (1,))
assert_size_stride(primals_24, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_25, (512,), (1,))
assert_size_stride(primals_26, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_27, (512,), (1,))
assert_size_stride(primals_28, (4096, 512, 7, 7), (25088, 49, 7, 1))
assert_size_stride(primals_29, (4096,), (1,))
assert_size_stride(primals_30, (4096, 4096, 1, 1), (4096, 1, 1, 1))
assert_size_stride(primals_31, (4096,), (1,))
assert_size_stride(primals_32, (4, 4096, 1, 1), (4096, 1, 1, 1))
assert_size_stride(primals_33, (4,), (1,))
assert_size_stride(primals_34, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_35, (4, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_36, (4,), (1,))
assert_size_stride(primals_37, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_38, (4, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_39, (4,), (1,))
assert_size_stride(primals_40, (4, 4, 16, 16), (1024, 256, 16, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch
.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(12, 4096)](primals_1, buf0, 12, 4096,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 3, 3, 3), (27, 1, 9, 3), torch.float32)
triton_poi_fused_1[grid(192, 9)](primals_2, buf1, 192, 9, XBLOCK=16,
YBLOCK=64, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64, 3, 3), (576, 1, 192, 64), torch.
float32)
triton_poi_fused_2[grid(4096, 9)](primals_4, buf2, 4096, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_3[grid(8192, 9)](primals_6, buf3, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_4[grid(16384, 9)](primals_8, buf4, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf5 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_5[grid(32768, 9)](primals_10, buf5, 32768, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_10
buf6 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_6[grid(65536, 9)](primals_12, buf6, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_12
buf7 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_6[grid(65536, 9)](primals_14, buf7, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_14
buf8 = empty_strided_cuda((512, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_7[grid(131072, 9)](primals_16, buf8, 131072, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_16
buf9 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_18, buf9, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_18
buf10 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_20, buf10, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_20
buf11 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_22, buf11, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_22
buf12 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_24, buf12, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_24
buf13 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_26, buf13, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_26
buf14 = empty_strided_cuda((4096, 512, 7, 7), (25088, 1, 3584, 512),
torch.float32)
triton_poi_fused_9[grid(2097152, 49)](primals_28, buf14, 2097152,
49, XBLOCK=32, YBLOCK=64, num_warps=8, num_stages=1)
del primals_28
buf15 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_10[grid(16, 16)](primals_34, buf15, 16, 16, XBLOCK
=16, YBLOCK=16, num_warps=4, num_stages=1)
del primals_34
buf16 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_10[grid(16, 16)](primals_37, buf16, 16, 16, XBLOCK
=16, YBLOCK=16, num_warps=4, num_stages=1)
del primals_37
buf17 = empty_strided_cuda((4, 4, 16, 16), (1024, 1, 64, 4), torch.
float32)
triton_poi_fused_11[grid(16, 256)](primals_40, buf17, 16, 256,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_40
buf18 = extern_kernels.convolution(buf0, buf1, stride=(1, 1),
padding=(100, 100), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf18, (4, 64, 262, 262), (4393216, 1, 16768, 64))
buf19 = buf18
del buf18
triton_poi_fused_convolution_relu_12[grid(17572864)](buf19,
primals_3, 17572864, XBLOCK=512, num_warps=8, num_stages=1)
del primals_3
buf20 = extern_kernels.convolution(buf19, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf20, (4, 64, 262, 262), (4393216, 1, 16768, 64))
buf21 = buf20
del buf20
triton_poi_fused_convolution_relu_12[grid(17572864)](buf21,
primals_5, 17572864, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf22 = empty_strided_cuda((4, 64, 131, 131), (1098304, 1, 8384, 64
), torch.float32)
buf23 = empty_strided_cuda((4, 64, 131, 131), (1098304, 1, 8384, 64
), torch.int8)
triton_poi_fused_max_pool2d_with_indices_13[grid(4393216)](buf21,
buf22, buf23, 4393216, XBLOCK=512, num_warps=8, num_stages=1)
buf24 = extern_kernels.convolution(buf22, buf3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf24, (4, 128, 131, 131), (2196608, 1, 16768, 128))
buf25 = buf24
del buf24
triton_poi_fused_convolution_relu_14[grid(8786432)](buf25,
primals_7, 8786432, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf26 = extern_kernels.convolution(buf25, buf4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf26, (4, 128, 131, 131), (2196608, 1, 16768, 128))
buf27 = buf26
del buf26
triton_poi_fused_convolution_relu_14[grid(8786432)](buf27,
primals_9, 8786432, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf28 = empty_strided_cuda((4, 128, 66, 66), (557568, 1, 8448, 128),
torch.float32)
buf29 = empty_strided_cuda((4, 128, 66, 66), (557568, 1, 8448, 128),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_15[grid(2230272)](buf27,
buf28, buf29, 2230272, XBLOCK=512, num_warps=8, num_stages=1)
buf30 = extern_kernels.convolution(buf28, buf5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf30, (4, 256, 66, 66), (1115136, 1, 16896, 256))
buf31 = buf30
del buf30
triton_poi_fused_convolution_relu_16[grid(4460544)](buf31,
primals_11, 4460544, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_11
buf32 = extern_kernels.convolution(buf31, buf6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf32, (4, 256, 66, 66), (1115136, 1, 16896, 256))
buf33 = buf32
del buf32
triton_poi_fused_convolution_relu_16[grid(4460544)](buf33,
primals_13, 4460544, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf34 = extern_kernels.convolution(buf33, buf7, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf34, (4, 256, 66, 66), (1115136, 1, 16896, 256))
buf35 = buf34
del buf34
triton_poi_fused_convolution_relu_16[grid(4460544)](buf35,
primals_15, 4460544, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_15
buf36 = empty_strided_cuda((4, 256, 33, 33), (278784, 1, 8448, 256),
torch.float32)
buf37 = empty_strided_cuda((4, 256, 33, 33), (278784, 1, 8448, 256),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_17[grid(1115136)](buf35,
buf36, buf37, 1115136, XBLOCK=512, num_warps=8, num_stages=1)
buf38 = extern_kernels.convolution(buf36, buf8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf38, (4, 512, 33, 33), (557568, 1, 16896, 512))
buf39 = buf38
del buf38
triton_poi_fused_convolution_relu_18[grid(2230272)](buf39,
primals_17, 2230272, XBLOCK=512, num_warps=8, num_stages=1)
del primals_17
buf40 = extern_kernels.convolution(buf39, buf9, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf40, (4, 512, 33, 33), (557568, 1, 16896, 512))
buf41 = buf40
del buf40
triton_poi_fused_convolution_relu_18[grid(2230272)](buf41,
primals_19, 2230272, XBLOCK=512, num_warps=8, num_stages=1)
del primals_19
buf42 = extern_kernels.convolution(buf41, buf10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf42, (4, 512, 33, 33), (557568, 1, 16896, 512))
buf43 = buf42
del buf42
triton_poi_fused_convolution_relu_18[grid(2230272)](buf43,
primals_21, 2230272, XBLOCK=512, num_warps=8, num_stages=1)
del primals_21
buf44 = empty_strided_cuda((4, 512, 17, 17), (147968, 1, 8704, 512),
torch.float32)
buf45 = empty_strided_cuda((4, 512, 17, 17), (147968, 1, 8704, 512),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_19[grid(591872)](buf43,
buf44, buf45, 591872, XBLOCK=1024, num_warps=4, num_stages=1)
buf46 = extern_kernels.convolution(buf44, buf11, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf46, (4, 512, 17, 17), (147968, 1, 8704, 512))
buf47 = buf46
del buf46
triton_poi_fused_convolution_relu_20[grid(591872)](buf47,
primals_23, 591872, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_23
buf48 = extern_kernels.convolution(buf47, buf12, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf48, (4, 512, 17, 17), (147968, 1, 8704, 512))
buf49 = buf48
del buf48
triton_poi_fused_convolution_relu_20[grid(591872)](buf49,
primals_25, 591872, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_25
buf50 = extern_kernels.convolution(buf49, buf13, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf50, (4, 512, 17, 17), (147968, 1, 8704, 512))
buf51 = buf50
del buf50
triton_poi_fused_convolution_relu_20[grid(591872)](buf51,
primals_27, 591872, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_27
buf52 = empty_strided_cuda((4, 512, 9, 9), (41472, 1, 4608, 512),
torch.float32)
buf53 = empty_strided_cuda((4, 512, 9, 9), (41472, 1, 4608, 512),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_21[grid(165888)](buf51,
buf52, buf53, 165888, XBLOCK=512, num_warps=8, num_stages=1)
buf54 = extern_kernels.convolution(buf52, buf14, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf54, (4, 4096, 3, 3), (36864, 1, 12288, 4096))
buf55 = buf54
del buf54
triton_poi_fused_convolution_relu_22[grid(147456)](buf55,
primals_29, 147456, XBLOCK=512, num_warps=8, num_stages=1)
del primals_29
buf56 = extern_kernels.convolution(buf55, primals_30, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf56, (4, 4096, 3, 3), (36864, 1, 12288, 4096))
buf57 = buf56
del buf56
triton_poi_fused_convolution_relu_22[grid(147456)](buf57,
primals_31, 147456, XBLOCK=512, num_warps=8, num_stages=1)
del primals_31
buf58 = extern_kernels.convolution(buf57, primals_32, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf58, (4, 4, 3, 3), (36, 1, 12, 4))
buf59 = buf58
del buf58
triton_poi_fused_convolution_23[grid(144)](buf59, primals_33, 144,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_33
buf60 = extern_kernels.convolution(buf59, buf15, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf60, (4, 4, 8, 8), (256, 1, 32, 4))
buf61 = extern_kernels.convolution(buf44, primals_35, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf61, (4, 4, 17, 17), (1156, 1, 68, 4))
buf62 = buf60
del buf60
triton_poi_fused_add_24[grid(1024)](buf62, buf61, primals_36, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del buf61
del primals_36
buf63 = extern_kernels.convolution(buf62, buf16, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf63, (4, 4, 18, 18), (1296, 1, 72, 4))
buf64 = extern_kernels.convolution(buf36, primals_38, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf64, (4, 4, 33, 33), (4356, 1, 132, 4))
buf65 = buf63
del buf63
triton_poi_fused_add_25[grid(5184)](buf65, buf64, primals_39, 5184,
XBLOCK=128, num_warps=4, num_stages=1)
del buf64
del primals_39
buf66 = extern_kernels.convolution(buf65, buf17, stride=(8, 8),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf66, (4, 4, 152, 152), (92416, 1, 608, 4))
buf67 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.float32)
triton_poi_fused_clone_26[grid(16, 4096)](buf66, buf67, 16, 4096,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del buf66
return (buf67, buf0, buf1, buf2, buf3, buf4, buf5, buf6, buf7, buf8,
buf9, buf10, buf11, buf12, buf13, buf14, primals_30, primals_32,
buf15, primals_35, buf16, primals_38, buf17, buf19, buf21, buf22,
buf23, buf25, buf27, buf28, buf29, buf31, buf33, buf35, buf36,
buf37, buf39, buf41, buf43, buf44, buf45, buf47, buf49, buf51,
buf52, buf53, buf55, buf57, buf59, buf62, buf65)
def conv3x3(in_planes, out_planes, stride=1, padding=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=(3, 3), stride=(
stride, stride), padding=(padding, padding))
def get_upsampling_weight(in_channels, out_channels, kernel_size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (kernel_size + 1) // 2
if kernel_size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:kernel_size, :kernel_size]
filt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) /
factor)
weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size),
dtype=np.float64)
weight[range(in_channels), range(out_channels), :, :] = filt
return torch.from_numpy(weight).float()
class FCN8VGG16New(nn.Module):
def __init__(self, n_classes):
super().__init__()
self.n_classes = n_classes
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
self.relu = nn.ReLU(inplace=True)
self.conv1_1 = conv3x3(3, 64, stride=1, padding=100)
self.conv1_2 = conv3x3(64, 64)
self.conv2_1 = conv3x3(64, 128)
self.conv2_2 = conv3x3(128, 128)
self.conv3_1 = conv3x3(128, 256)
self.conv3_2 = conv3x3(256, 256)
self.conv3_3 = conv3x3(256, 256)
self.conv4_1 = conv3x3(256, 512)
self.conv4_2 = conv3x3(512, 512)
self.conv4_3 = conv3x3(512, 512)
self.conv5_1 = conv3x3(512, 512)
self.conv5_2 = conv3x3(512, 512)
self.conv5_3 = conv3x3(512, 512)
self.fc6 = nn.Conv2d(512, 4096, kernel_size=7, stride=1, padding=0)
self.dropout_f6 = nn.Dropout()
self.fc7 = nn.Conv2d(4096, 4096, kernel_size=1, stride=1, padding=0)
self.dropout_f7 = nn.Dropout()
self.scoring_layer = nn.Conv2d(4096, self.n_classes, kernel_size=1,
stride=1, padding=0)
self.upscore2 = nn.ConvTranspose2d(self.n_classes, self.n_classes,
kernel_size=4, stride=2, bias=False)
self.upscore_pool4 = nn.ConvTranspose2d(self.n_classes, self.
n_classes, kernel_size=4, stride=2, bias=False)
self.upscore8 = nn.ConvTranspose2d(self.n_classes, self.n_classes,
kernel_size=16, stride=8, bias=False)
self.scoring_layer.weight.data.zero_()
self.scoring_layer.bias.data.zero_()
self.score_pool3 = nn.Conv2d(256, self.n_classes, kernel_size=1)
self.score_pool4 = nn.Conv2d(512, self.n_classes, kernel_size=1)
self.score_pool3.weight.data.zero_()
self.score_pool3.bias.data.zero_()
self.score_pool4.weight.data.zero_()
self.score_pool4.bias.data.zero_()
self.upscore2.weight.data.copy_(get_upsampling_weight(self.
n_classes, self.n_classes, 4))
self.upscore_pool4.weight.data.copy_(get_upsampling_weight(self.
n_classes, self.n_classes, 4))
self.upscore8.weight.data.copy_(get_upsampling_weight(self.
n_classes, self.n_classes, 16))
pth_url = 'https://download.pytorch.org/models/vgg16-397923af.pth'
state_dict = model_zoo.load_url(pth_url)
layer_names = [layer_name for layer_name in state_dict]
counter = 0
for p in self.parameters():
if counter < 26:
p.data = state_dict[layer_names[counter]]
elif counter == 26:
p.data = state_dict[layer_names[counter]].view(4096, 512, 7, 7)
elif counter == 27:
p.data = state_dict[layer_names[counter]]
elif counter == 28:
p.data = state_dict[layer_names[counter]].view(4096, 4096, 1, 1
)
elif counter == 29:
p.data = state_dict[layer_names[counter]]
counter += 1
def forward(self, input_0):
primals_2 = self.conv1_1.weight
primals_3 = self.conv1_1.bias
primals_4 = self.conv1_2.weight
primals_5 = self.conv1_2.bias
primals_6 = self.conv2_1.weight
primals_7 = self.conv2_1.bias
primals_8 = self.conv2_2.weight
primals_9 = self.conv2_2.bias
primals_10 = self.conv3_1.weight
primals_11 = self.conv3_1.bias
primals_12 = self.conv3_2.weight
primals_13 = self.conv3_2.bias
primals_14 = self.conv3_3.weight
primals_15 = self.conv3_3.bias
primals_16 = self.conv4_1.weight
primals_17 = self.conv4_1.bias
primals_18 = self.conv4_2.weight
primals_19 = self.conv4_2.bias
primals_20 = self.conv4_3.weight
primals_21 = self.conv4_3.bias
primals_22 = self.conv5_1.weight
primals_23 = self.conv5_1.bias
primals_24 = self.conv5_2.weight
primals_25 = self.conv5_2.bias
primals_26 = self.conv5_3.weight
primals_27 = self.conv5_3.bias
primals_28 = self.fc6.weight
primals_29 = self.fc6.bias
primals_30 = self.fc7.weight
primals_31 = self.fc7.bias
primals_32 = self.scoring_layer.weight
primals_33 = self.scoring_layer.bias
primals_34 = self.upscore2.weight
primals_37 = self.upscore_pool4.weight
primals_40 = self.upscore8.weight
primals_38 = self.score_pool3.weight
primals_36 = self.score_pool3.bias
primals_35 = self.score_pool4.weight
primals_39 = self.score_pool4.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
primals_40])
return output[0]
|
alzayats/DeepFish
|
FCN8VGG16
| false
| 15,065
|
[
"MIT"
] | 48
|
4d9ebfb0474a7e9346c72e2a5411ab6f72e878e2
|
https://github.com/alzayats/DeepFish/tree/4d9ebfb0474a7e9346c72e2a5411ab6f72e878e2
|
Softmax
|
import torch
import torch.nn as nn
def keep_variance_fn(x):
return x + 0.001
class Softmax(nn.Module):
def __init__(self, dim=1, keep_variance_fn=None):
super(Softmax, self).__init__()
self.dim = dim
self._keep_variance_fn = keep_variance_fn
def forward(self, features_mean, features_variance, eps=1e-05):
"""Softmax function applied to a multivariate Gaussian distribution.
It works under the assumption that features_mean and features_variance
are the parameters of a the indepent gaussians that contribute to the
multivariate gaussian.
Mean and variance of the log-normal distribution are computed following
https://en.wikipedia.org/wiki/Log-normal_distribution."""
log_gaussian_mean = features_mean + 0.5 * features_variance
log_gaussian_variance = 2 * log_gaussian_mean
log_gaussian_mean = torch.exp(log_gaussian_mean)
log_gaussian_variance = torch.exp(log_gaussian_variance)
log_gaussian_variance = log_gaussian_variance * (torch.exp(
features_variance) - 1)
constant = torch.sum(log_gaussian_mean, dim=self.dim) + eps
constant = constant.unsqueeze(self.dim)
outputs_mean = log_gaussian_mean / constant
outputs_variance = log_gaussian_variance / constant ** 2
if self._keep_variance_fn is not None:
outputs_variance = self._keep_variance_fn(outputs_variance)
return outputs_mean, outputs_variance
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_exp_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp7 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp12 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp13 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp18 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp19 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = tmp0 + tmp3
tmp5 = tl_math.exp(tmp4)
tmp8 = tmp7 * tmp2
tmp9 = tmp6 + tmp8
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp5 + tmp10
tmp14 = tmp13 * tmp2
tmp15 = tmp12 + tmp14
tmp16 = tl_math.exp(tmp15)
tmp17 = tmp11 + tmp16
tmp20 = tmp19 * tmp2
tmp21 = tmp18 + tmp20
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp17 + tmp22
tmp24 = 1e-05
tmp25 = tmp23 + tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_div_exp_mul_pow_sub_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x3, xmask)
tmp6 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = tmp0 + tmp3
tmp5 = tl_math.exp(tmp4)
tmp7 = tmp5 / tmp6
tmp8 = 2.0
tmp9 = tmp4 * tmp8
tmp10 = tl_math.exp(tmp9)
tmp11 = tl_math.exp(tmp1)
tmp12 = 1.0
tmp13 = tmp11 - tmp12
tmp14 = tmp10 * tmp13
tmp15 = tmp6 * tmp6
tmp16 = tmp14 / tmp15
tl.store(out_ptr0 + x3, tmp7, xmask)
tl.store(out_ptr1 + x3, tmp16, 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_add_exp_mul_sum_0[grid(64)](arg1_1, arg0_1, buf0,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_exp_mul_pow_sub_1[grid(256)](arg1_1,
arg0_1, buf0, buf1, buf2, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
del buf0
return buf1, buf2
def keep_variance_fn(x):
return x + 0.001
class SoftmaxNew(nn.Module):
def __init__(self, dim=1, keep_variance_fn=None):
super(SoftmaxNew, self).__init__()
self.dim = dim
self._keep_variance_fn = keep_variance_fn
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
Softmax
| false
| 15,066
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
lovasz_hinge
|
import torch
import torch.nn.parallel
import torch.utils.data
from torchvision.transforms import functional as F
import torch.nn.functional as F
from torch.autograd import Variable
def flatten_binary_scores(scores, labels, ignore=255):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = labels != ignore
vscores = scores[valid]
vlabels = labels[valid]
return vscores, vlabels
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts.float() - gt_sorted.float().cumsum(0)
union = gts.float() + (1 - gt_sorted).float().cumsum(0)
jaccard = 1.0 - intersection / union
if p > 1:
jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
return jaccard
def isnan(x):
return x != x
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for n, v in enumerate(l, 2):
acc += v
if n == 1:
return acc
return acc / n
class lovasz_hinge(torch.nn.Module):
def __init__(self, per_img=False, ignore=255):
"""
:param weight: 1D weight vector to deal with the class-imbalance
"""
super().__init__()
self.per_image = per_img
self.ignore = ignore
def lovasz_hinge_flat(self, logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\\infty and +\\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore
"""
if len(labels) == 0:
return logits.sum() * 0.0
signs = 2.0 * labels.float() - 1.0
errors = 1.0 - logits * Variable(signs)
errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_sorted)
loss = torch.dot(F.relu(errors_sorted), Variable(grad))
return loss
def forward(self, logits, labels):
"""
Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\\infty and +\\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
ignore: void class id
"""
if self.per_image:
loss = mean(self.lovasz_hinge_flat(*flatten_binary_scores(log.
unsqueeze(0), lab.unsqueeze(0), self.ignore)) for log, lab in
zip(logits, labels))
else:
loss = self.lovasz_hinge_flat(*flatten_binary_scores(logits,
labels, self.ignore))
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn.parallel
import torch.utils.data
from torchvision.transforms import functional as F
import torch.nn.functional as F
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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_ne_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 = 255.0
tmp2 = tmp0 != tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((256,), (1,), torch.bool)
get_raw_stream(0)
triton_poi_fused_ne_0[grid(256)](arg1_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
return reinterpret_tensor(arg0_1, (256,), (1,), 0
), buf0, reinterpret_tensor(arg1_1, (256,), (1,), 0)
def flatten_binary_scores(scores, labels, ignore=255):
"""
Flattens predictions in the batch (binary case)
Remove labels equal to 'ignore'
"""
scores = scores.view(-1)
labels = labels.view(-1)
if ignore is None:
return scores, labels
valid = labels != ignore
vscores = scores[valid]
vlabels = labels[valid]
return vscores, vlabels
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts.float() - gt_sorted.float().cumsum(0)
union = gts.float() + (1 - gt_sorted).float().cumsum(0)
jaccard = 1.0 - intersection / union
if p > 1:
jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
return jaccard
def isnan(x):
return x != x
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for n, v in enumerate(l, 2):
acc += v
if n == 1:
return acc
return acc / n
class lovasz_hingeNew(torch.nn.Module):
def __init__(self, per_img=False, ignore=255):
"""
:param weight: 1D weight vector to deal with the class-imbalance
"""
super().__init__()
self.per_image = per_img
self.ignore = ignore
def lovasz_hinge_flat(self, logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\\infty and +\\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore
"""
if len(labels) == 0:
return logits.sum() * 0.0
signs = 2.0 * labels.float() - 1.0
errors = 1.0 - logits * Variable(signs)
errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_sorted)
loss = torch.dot(F.relu(errors_sorted), Variable(grad))
return loss
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
clovaai/ext_portrait_segmentation
|
lovasz_hinge
| false
| 15,067
|
[
"MIT"
] | 227
|
9bc1bada1cb7bd17a3a80a2964980f4b4befef5b
|
https://github.com/clovaai/ext_portrait_segmentation/tree/9bc1bada1cb7bd17a3a80a2964980f4b4befef5b
|
Linear
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
def keep_variance_fn(x):
return x + 0.001
class Linear(nn.Module):
def __init__(self, in_features, out_features, bias=True,
keep_variance_fn=None):
super(Linear, self).__init__()
self._keep_variance_fn = keep_variance_fn
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.Tensor(out_features, in_features))
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
def forward(self, inputs_mean, inputs_variance):
outputs_mean = F.linear(inputs_mean, self.weight, self.bias)
outputs_variance = F.linear(inputs_variance, self.weight ** 2, None)
if self._keep_variance_fn is not None:
outputs_variance = self._keep_variance_fn(outputs_variance)
return outputs_mean, outputs_variance
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_poi_fused_pow_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 = tmp0 * 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,), (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 = 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_2
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_pow_0[grid(16)](primals_1, buf1, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_4, (64, 4), (4, 1), 0),
reinterpret_tensor(buf1, (4, 4), (1, 4), 0), out=buf2)
del buf1
return reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_4, (64, 4), (4, 1), 0)
def keep_variance_fn(x):
return x + 0.001
class LinearNew(nn.Module):
def __init__(self, in_features, out_features, bias=True,
keep_variance_fn=None):
super(LinearNew, self).__init__()
self._keep_variance_fn = keep_variance_fn
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.Tensor(out_features, in_features))
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
def forward(self, input_0, input_1):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
Linear
| false
| 15,068
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
Conv2d
|
import torch
import torch.nn.functional as F
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules.utils import _pair
def keep_variance_fn(x):
return x + 0.001
class Conv2d(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, keep_variance_fn=None,
padding_mode='zeros'):
self._keep_variance_fn = keep_variance_fn
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(Conv2d, self).__init__(in_channels, out_channels, kernel_size,
stride, padding, dilation, False, _pair(0), groups, bias,
padding_mode)
def forward(self, inputs_mean, inputs_variance):
outputs_mean = F.conv2d(inputs_mean, self.weight, self.bias, self.
stride, self.padding, self.dilation, self.groups)
outputs_variance = F.conv2d(inputs_variance, self.weight ** 2, None,
self.stride, self.padding, self.dilation, self.groups)
if self._keep_variance_fn is not None:
outputs_variance = self._keep_variance_fn(outputs_variance)
return outputs_mean, outputs_variance
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules.utils import _pair
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 = 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_pow_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 = tmp0 * 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 1, 1), (4, 1, 1, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16)](buf1, primals_2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_pow_1[grid(256)](primals_1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf3 = extern_kernels.convolution(primals_4, buf2, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 1, 1), (4, 1, 1, 1))
return buf1, buf3, primals_1, primals_3, primals_4, buf2
def keep_variance_fn(x):
return x + 0.001
class Conv2dNew(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, keep_variance_fn=None,
padding_mode='zeros'):
self._keep_variance_fn = keep_variance_fn
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
super(Conv2dNew, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, dilation, False, _pair(0), groups,
bias, padding_mode)
def forward(self, input_0, input_1):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
Conv2d
| false
| 15,069
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
MaxPool2d
|
import torch
import numpy as np
import torch.nn as nn
from numbers import Number
def keep_variance_fn(x):
return x + 0.001
def normcdf(value, mu=0.0, stddev=1.0):
sinv = 1.0 / stddev if isinstance(stddev, Number) else stddev.reciprocal()
return 0.5 * (1.0 + torch.erf((value - mu) * sinv / np.sqrt(2.0)))
def _normal_log_pdf(value, mu, stddev):
var = stddev ** 2
log_scale = np.log(stddev) if isinstance(stddev, Number) else torch.log(
stddev)
return -(value - mu) ** 2 / (2.0 * var) - log_scale - np.log(np.sqrt(
2.0 * np.pi))
def normpdf(value, mu=0.0, stddev=1.0):
return torch.exp(_normal_log_pdf(value, mu, stddev))
class MaxPool2d(nn.Module):
def __init__(self, keep_variance_fn=None):
super(MaxPool2d, self).__init__()
self._keep_variance_fn = keep_variance_fn
def _max_pool_internal(self, mu_a, mu_b, var_a, var_b):
stddev = torch.sqrt(var_a + var_b)
ab = mu_a - mu_b
alpha = ab / stddev
pdf = normpdf(alpha)
cdf = normcdf(alpha)
z_mu = stddev * pdf + ab * cdf + mu_b
z_var = (mu_a + mu_b) * stddev * pdf + (mu_a ** 2 + var_a) * cdf + (
mu_b ** 2 + var_b) * (1.0 - cdf) - z_mu ** 2
if self._keep_variance_fn is not None:
z_var = self._keep_variance_fn(z_var)
return z_mu, z_var
def _max_pool_1x2(self, inputs_mean, inputs_variance):
mu_a = inputs_mean[:, :, :, 0::2]
mu_b = inputs_mean[:, :, :, 1::2]
var_a = inputs_variance[:, :, :, 0::2]
var_b = inputs_variance[:, :, :, 1::2]
outputs_mean, outputs_variance = self._max_pool_internal(mu_a, mu_b,
var_a, var_b)
return outputs_mean, outputs_variance
def _max_pool_2x1(self, inputs_mean, inputs_variance):
mu_a = inputs_mean[:, :, 0::2, :]
mu_b = inputs_mean[:, :, 1::2, :]
var_a = inputs_variance[:, :, 0::2, :]
var_b = inputs_variance[:, :, 1::2, :]
outputs_mean, outputs_variance = self._max_pool_internal(mu_a, mu_b,
var_a, var_b)
return outputs_mean, outputs_variance
def forward(self, inputs_mean, inputs_variance):
z_mean, z_variance = self._max_pool_1x2(inputs_mean, inputs_variance)
outputs_mean, outputs_variance = self._max_pool_2x1(z_mean, z_variance)
return outputs_mean, outputs_variance
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import numpy as np
import torch.nn as nn
from numbers import Number
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_erf_exp_log_mul_neg_pow_rsub_sqrt_sub_0(
in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 2 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + 2 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 2 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = libdevice.sqrt(tmp5)
tmp7 = tmp2 * tmp6
tmp8 = tmp0 - tmp1
tmp9 = tmp8 / tmp6
tmp10 = 0.0
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = -tmp12
tmp14 = 0.5
tmp15 = tmp13 * tmp14
tmp16 = 0.9189385332046727
tmp17 = tmp15 - tmp16
tmp18 = tl_math.exp(tmp17)
tmp19 = tmp7 * tmp18
tmp20 = tmp0 * tmp0
tmp21 = tmp20 + tmp3
tmp22 = 1.0
tmp23 = tmp11 * tmp22
tmp24 = 1.414213562373095
tmp25 = tmp23 / tmp24
tmp26 = libdevice.erf(tmp25)
tmp27 = tmp26 + tmp22
tmp28 = tmp27 * tmp14
tmp29 = tmp21 * tmp28
tmp30 = tmp19 + tmp29
tmp31 = tmp6 * tmp18
tmp32 = tmp8 * tmp28
tmp33 = tmp31 + tmp32
tmp34 = tmp33 + tmp1
tmp35 = tmp34 * tmp34
tmp36 = tmp1 * tmp1
tmp37 = tmp36 + tmp4
tmp38 = tmp22 - tmp28
tmp39 = tmp37 * tmp38
tmp40 = tmp30 + tmp39
tmp41 = tmp40 - tmp35
tl.store(in_out_ptr0 + x0, tmp41, xmask)
@triton.jit
def triton_poi_fused_add_div_erf_exp_log_mul_neg_pow_rsub_sqrt_sub_1(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, out_ptr2, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr1 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr1 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp30 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy
='evict_last')
tmp33 = tl.load(in_ptr1 + (2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp34 = tl.load(in_ptr1 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy
='evict_last')
tmp54 = tl.load(in_ptr2 + (x0 + 4 * x1), xmask)
tmp55 = tl.load(in_ptr2 + (2 + x0 + 4 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp3 = libdevice.sqrt(tmp2)
tmp6 = tmp4 - tmp5
tmp7 = tmp6 / tmp3
tmp8 = 0.0
tmp9 = tmp7 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = -tmp10
tmp12 = 0.5
tmp13 = tmp11 * tmp12
tmp14 = 0.9189385332046727
tmp15 = tmp13 - tmp14
tmp16 = tl_math.exp(tmp15)
tmp17 = tmp3 * tmp16
tmp18 = 1.0
tmp19 = tmp9 * tmp18
tmp20 = 1.414213562373095
tmp21 = tmp19 / tmp20
tmp22 = libdevice.erf(tmp21)
tmp23 = tmp22 + tmp18
tmp24 = tmp23 * tmp12
tmp25 = tmp6 * tmp24
tmp26 = tmp17 + tmp25
tmp27 = tmp26 + tmp5
tmp28 = tmp27 * tmp27
tmp31 = tmp29 + tmp30
tmp32 = libdevice.sqrt(tmp31)
tmp35 = tmp33 - tmp34
tmp36 = tmp35 / tmp32
tmp37 = tmp36 - tmp8
tmp38 = tmp37 * tmp37
tmp39 = -tmp38
tmp40 = tmp39 * tmp12
tmp41 = tmp40 - tmp14
tmp42 = tl_math.exp(tmp41)
tmp43 = tmp32 * tmp42
tmp44 = tmp37 * tmp18
tmp45 = tmp44 / tmp20
tmp46 = libdevice.erf(tmp45)
tmp47 = tmp46 + tmp18
tmp48 = tmp47 * tmp12
tmp49 = tmp35 * tmp48
tmp50 = tmp43 + tmp49
tmp51 = tmp50 + tmp34
tmp52 = tmp51 + tmp27
tmp53 = tmp51 - tmp27
tmp56 = tmp54 + tmp55
tmp57 = libdevice.sqrt(tmp56)
tmp58 = tmp53 / tmp57
tmp59 = tmp58 - tmp8
tmp60 = tmp59 * tmp59
tmp61 = -tmp60
tmp62 = tmp61 * tmp12
tmp63 = tmp62 - tmp14
tmp64 = tl_math.exp(tmp63)
tmp65 = tmp57 * tmp64
tmp66 = tmp59 * tmp18
tmp67 = tmp66 / tmp20
tmp68 = libdevice.erf(tmp67)
tmp69 = tmp68 + tmp18
tmp70 = tmp69 * tmp12
tmp71 = tmp53 * tmp70
tmp72 = tmp65 + tmp71
tmp73 = tmp72 + tmp27
tmp74 = tmp51 * tmp51
tmp75 = tmp52 * tmp57
tmp76 = tmp75 * tmp64
tmp77 = tmp74 + tmp54
tmp78 = tmp77 * tmp70
tmp79 = tmp76 + tmp78
tmp80 = tmp28 + tmp55
tmp81 = tmp18 - tmp70
tmp82 = tmp80 * tmp81
tmp83 = tmp79 + tmp82
tmp84 = tmp73 * tmp73
tmp85 = tmp83 - tmp84
tl.store(out_ptr2 + x2, tmp73, xmask)
tl.store(in_out_ptr0 + x2, tmp85, 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)
buf1 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.float32)
buf3 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_add_div_erf_exp_log_mul_neg_pow_rsub_sqrt_sub_0[grid
(128)](buf3, arg0_1, arg1_1, 128, XBLOCK=128, num_warps=4,
num_stages=1)
buf0 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
buf8 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
buf6 = buf0
del buf0
buf9 = buf6
del buf6
triton_poi_fused_add_div_erf_exp_log_mul_neg_pow_rsub_sqrt_sub_1[grid
(64)](buf9, arg1_1, arg0_1, buf3, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del buf3
return buf8, buf9
def keep_variance_fn(x):
return x + 0.001
def normcdf(value, mu=0.0, stddev=1.0):
sinv = 1.0 / stddev if isinstance(stddev, Number) else stddev.reciprocal()
return 0.5 * (1.0 + torch.erf((value - mu) * sinv / np.sqrt(2.0)))
def _normal_log_pdf(value, mu, stddev):
var = stddev ** 2
log_scale = np.log(stddev) if isinstance(stddev, Number) else torch.log(
stddev)
return -(value - mu) ** 2 / (2.0 * var) - log_scale - np.log(np.sqrt(
2.0 * np.pi))
def normpdf(value, mu=0.0, stddev=1.0):
return torch.exp(_normal_log_pdf(value, mu, stddev))
class MaxPool2dNew(nn.Module):
def __init__(self, keep_variance_fn=None):
super(MaxPool2dNew, self).__init__()
self._keep_variance_fn = keep_variance_fn
def _max_pool_internal(self, mu_a, mu_b, var_a, var_b):
stddev = torch.sqrt(var_a + var_b)
ab = mu_a - mu_b
alpha = ab / stddev
pdf = normpdf(alpha)
cdf = normcdf(alpha)
z_mu = stddev * pdf + ab * cdf + mu_b
z_var = (mu_a + mu_b) * stddev * pdf + (mu_a ** 2 + var_a) * cdf + (
mu_b ** 2 + var_b) * (1.0 - cdf) - z_mu ** 2
if self._keep_variance_fn is not None:
z_var = self._keep_variance_fn(z_var)
return z_mu, z_var
def _max_pool_1x2(self, inputs_mean, inputs_variance):
mu_a = inputs_mean[:, :, :, 0::2]
mu_b = inputs_mean[:, :, :, 1::2]
var_a = inputs_variance[:, :, :, 0::2]
var_b = inputs_variance[:, :, :, 1::2]
outputs_mean, outputs_variance = self._max_pool_internal(mu_a, mu_b,
var_a, var_b)
return outputs_mean, outputs_variance
def _max_pool_2x1(self, inputs_mean, inputs_variance):
mu_a = inputs_mean[:, :, 0::2, :]
mu_b = inputs_mean[:, :, 1::2, :]
var_a = inputs_variance[:, :, 0::2, :]
var_b = inputs_variance[:, :, 1::2, :]
outputs_mean, outputs_variance = self._max_pool_internal(mu_a, mu_b,
var_a, var_b)
return outputs_mean, outputs_variance
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0], output[1]
|
collector-m/LiDAR-MOS
|
MaxPool2d
| false
| 15,070
|
[
"MIT"
] | 268
|
7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
https://github.com/collector-m/LiDAR-MOS/tree/7ccbb63b4ee7c40195b35dd0dddd71473fae25b1
|
TransformerEncoderLayer
|
import torch
import torch.utils.data
import torch.nn.functional as F
import torch.nn as nn
from torch.nn.init import xavier_uniform_
from torch.nn.init import constant_
from torch.nn.init import xavier_normal_
def _get_activation_fn(activation):
if activation == 'relu':
return F.relu
elif activation == 'gelu':
return F.gelu
raise RuntimeError('activation should be relu/gelu, not {}'.format(
activation))
class MultiheadAttention(nn.Module):
__annotations__ = {'bias_k': torch._jit_internal.Optional[torch.Tensor],
'bias_v': torch._jit_internal.Optional[torch.Tensor]}
__constants__ = ['q_proj_weight', 'k_proj_weight', 'v_proj_weight',
'in_proj_weight']
def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True,
add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None):
super(MultiheadAttention, self).__init__()
self.embed_dim = embed_dim
self.kdim = kdim if kdim is not None else embed_dim
self.vdim = vdim if vdim is not None else embed_dim
self._qkv_same_embed_dim = (self.kdim == embed_dim and self.vdim ==
embed_dim)
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
if self._qkv_same_embed_dim is False:
self.q_proj_weight = nn.Parameter(torch.Tensor(embed_dim,
embed_dim))
self.k_proj_weight = nn.Parameter(torch.Tensor(embed_dim, self.
kdim))
self.v_proj_weight = nn.Parameter(torch.Tensor(embed_dim, self.
vdim))
self.register_parameter('in_proj_weight', None)
else:
self.in_proj_weight = nn.Parameter(torch.empty(3 * embed_dim,
embed_dim))
self.register_parameter('q_proj_weight', None)
self.register_parameter('k_proj_weight', None)
self.register_parameter('v_proj_weight', None)
if bias:
self.in_proj_bias = nn.Parameter(torch.empty(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = nn.Parameter(torch.empty(1, 1, embed_dim))
self.bias_v = nn.Parameter(torch.empty(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self._reset_parameters()
def _reset_parameters(self):
if self._qkv_same_embed_dim:
xavier_uniform_(self.in_proj_weight)
else:
xavier_uniform_(self.q_proj_weight)
xavier_uniform_(self.k_proj_weight)
xavier_uniform_(self.v_proj_weight)
if self.in_proj_bias is not None:
constant_(self.in_proj_bias, 0.0)
constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
xavier_normal_(self.bias_k)
if self.bias_v is not None:
xavier_normal_(self.bias_v)
def __setstate__(self, state):
if '_qkv_same_embed_dim' not in state:
state['_qkv_same_embed_dim'] = True
super(MultiheadAttention, self).__setstate__(state)
def forward(self, query, key, value, key_padding_mask=None,
need_weights=True, attn_mask=None):
if not self._qkv_same_embed_dim:
return F.multi_head_attention_forward(query, key, value, self.
embed_dim, self.num_heads, self.in_proj_weight, self.
in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training, key_padding_mask=key_padding_mask,
need_weights=need_weights, attn_mask=attn_mask,
use_separate_proj_weight=True, q_proj_weight=self.
q_proj_weight, k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight)
else:
return F.multi_head_attention_forward(query, key, value, self.
embed_dim, self.num_heads, self.in_proj_weight, self.
in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training, key_padding_mask=key_padding_mask,
need_weights=need_weights, attn_mask=attn_mask)
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu'):
super(TransformerEncoderLayer, self).__init__()
self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
def __setstate__(self, state):
if 'activation' not in state:
state['activation'] = F.relu
super(TransformerEncoderLayer, self).__setstate__(state)
def forward(self, src, src_mask=None, src_key_padding_mask=None):
src2 = self.self_attn(src, src, src, attn_mask=src_mask,
key_padding_mask=src_key_padding_mask)[0]
src = src + self.dropout1(src2)
src = self.norm1(src)
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
src = src + self.dropout2(src2)
src = self.norm2(src)
return src
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'nhead': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.utils.data
import torch.nn.functional as F
import torch.nn as nn
from torch.nn.init import xavier_uniform_
from torch.nn.init import constant_
from torch.nn.init import xavier_normal_
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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_relu_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 2048
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_add_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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (12, 4), (4, 1))
assert_size_stride(primals_2, (12,), (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,), (1,))
assert_size_stride(primals_8, (2048, 4), (4, 1))
assert_size_stride(primals_9, (2048,), (1,))
assert_size_stride(primals_10, (4, 2048), (2048, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (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_5, reinterpret_tensor(primals_1, (4, 4),
(1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(reinterpret_tensor(primals_2, (4,), (1,), 4),
primals_5, reinterpret_tensor(primals_1, (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_2, (4,), (1,), 8),
primals_5, reinterpret_tensor(primals_1, (4, 4), (1, 4), 32),
alpha=1, beta=1, out=buf2)
del primals_1
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_2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf1, (4, 1, 4), (1, 1,
4), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf5
buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 1), (1, 4,
1), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_3[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_4, reinterpret_tensor(buf8, (4, 4), (4,
1), 0), reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf9)
del primals_4
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_5, 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_5, 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, 2048), (2048, 1), torch.float32)
extern_kernels.mm(buf12, reinterpret_tensor(primals_8, (4, 2048), (
1, 4), 0), out=buf13)
buf14 = buf13
del buf13
triton_poi_fused_relu_6[grid(8192)](buf14, primals_9, 8192, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf14, reinterpret_tensor(primals_10, (2048, 4),
(1, 2048), 0), out=buf15)
buf16 = buf15
del buf15
triton_poi_fused_add_7[grid(16)](buf16, buf12, primals_11, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_11
buf17 = buf11
del buf11
buf18 = buf10
del buf10
triton_poi_fused_native_layer_norm_8[grid(4)](buf16, buf17, buf18,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf19 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_9[grid(16)](buf16, buf17, buf18,
primals_12, primals_13, buf19, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf17
del buf18
del primals_13
return (buf19, primals_5, primals_6, primals_12, buf6,
reinterpret_tensor(buf8, (4, 4), (4, 1), 0), buf9, buf12, buf14,
buf16, primals_10, primals_8, primals_3, 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))
def _get_activation_fn(activation):
if activation == 'relu':
return F.relu
elif activation == 'gelu':
return F.gelu
raise RuntimeError('activation should be relu/gelu, not {}'.format(
activation))
class MultiheadAttention(nn.Module):
__annotations__ = {'bias_k': torch._jit_internal.Optional[torch.Tensor],
'bias_v': torch._jit_internal.Optional[torch.Tensor]}
__constants__ = ['q_proj_weight', 'k_proj_weight', 'v_proj_weight',
'in_proj_weight']
def __init__(self, embed_dim, num_heads, dropout=0.0, bias=True,
add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None):
super(MultiheadAttention, self).__init__()
self.embed_dim = embed_dim
self.kdim = kdim if kdim is not None else embed_dim
self.vdim = vdim if vdim is not None else embed_dim
self._qkv_same_embed_dim = (self.kdim == embed_dim and self.vdim ==
embed_dim)
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, 'embed_dim must be divisible by num_heads'
if self._qkv_same_embed_dim is False:
self.q_proj_weight = nn.Parameter(torch.Tensor(embed_dim,
embed_dim))
self.k_proj_weight = nn.Parameter(torch.Tensor(embed_dim, self.
kdim))
self.v_proj_weight = nn.Parameter(torch.Tensor(embed_dim, self.
vdim))
self.register_parameter('in_proj_weight', None)
else:
self.in_proj_weight = nn.Parameter(torch.empty(3 * embed_dim,
embed_dim))
self.register_parameter('q_proj_weight', None)
self.register_parameter('k_proj_weight', None)
self.register_parameter('v_proj_weight', None)
if bias:
self.in_proj_bias = nn.Parameter(torch.empty(3 * embed_dim))
else:
self.register_parameter('in_proj_bias', None)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if add_bias_kv:
self.bias_k = nn.Parameter(torch.empty(1, 1, embed_dim))
self.bias_v = nn.Parameter(torch.empty(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self._reset_parameters()
def _reset_parameters(self):
if self._qkv_same_embed_dim:
xavier_uniform_(self.in_proj_weight)
else:
xavier_uniform_(self.q_proj_weight)
xavier_uniform_(self.k_proj_weight)
xavier_uniform_(self.v_proj_weight)
if self.in_proj_bias is not None:
constant_(self.in_proj_bias, 0.0)
constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
xavier_normal_(self.bias_k)
if self.bias_v is not None:
xavier_normal_(self.bias_v)
def __setstate__(self, state):
if '_qkv_same_embed_dim' not in state:
state['_qkv_same_embed_dim'] = True
super(MultiheadAttention, self).__setstate__(state)
def forward(self, query, key, value, key_padding_mask=None,
need_weights=True, attn_mask=None):
if not self._qkv_same_embed_dim:
return F.multi_head_attention_forward(query, key, value, self.
embed_dim, self.num_heads, self.in_proj_weight, self.
in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training, key_padding_mask=key_padding_mask,
need_weights=need_weights, attn_mask=attn_mask,
use_separate_proj_weight=True, q_proj_weight=self.
q_proj_weight, k_proj_weight=self.k_proj_weight,
v_proj_weight=self.v_proj_weight)
else:
return F.multi_head_attention_forward(query, key, value, self.
embed_dim, self.num_heads, self.in_proj_weight, self.
in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn,
self.dropout, self.out_proj.weight, self.out_proj.bias,
training=self.training, key_padding_mask=key_padding_mask,
need_weights=need_weights, attn_mask=attn_mask)
class TransformerEncoderLayerNew(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
activation='relu'):
super(TransformerEncoderLayerNew, self).__init__()
self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout)
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
def __setstate__(self, state):
if 'activation' not in state:
state['activation'] = F.relu
super(TransformerEncoderLayerNew, self).__setstate__(state)
def forward(self, input_0):
primals_1 = self.self_attn.in_proj_weight
primals_2 = self.self_attn.in_proj_bias
primals_3 = self.self_attn.out_proj.weight
primals_4 = self.self_attn.out_proj.bias
primals_8 = self.linear1.weight
primals_9 = self.linear1.bias
primals_10 = self.linear2.weight
primals_6 = self.linear2.bias
primals_7 = self.norm1.weight
primals_11 = self.norm1.bias
primals_12 = self.norm2.weight
primals_13 = self.norm2.bias
primals_5 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
codeboy5/cvpr20-scatter-text-recognizer
|
TransformerEncoderLayer
| false
| 15,071
|
[
"Apache-2.0"
] | 63
|
4bd6cfbd4d7f64ce11864514f6b6b0646267c285
|
https://github.com/codeboy5/cvpr20-scatter-text-recognizer/tree/4bd6cfbd4d7f64ce11864514f6b6b0646267c285
|
_MLP_B
|
import torch
import torch.nn as nn
class _MLP_B(nn.Module):
"""MLP that only use age gender MMSE"""
def __init__(self, in_size, drop_rate, fil_num):
super(_MLP_B, self).__init__()
self.fc1 = nn.Linear(in_size, fil_num)
self.fc2 = nn.Linear(fil_num, 2)
self.do1 = nn.Dropout(drop_rate)
self.do2 = nn.Dropout(drop_rate)
self.ac1 = nn.LeakyReLU()
def forward(self, X):
out = self.do1(X)
out = self.fc1(out)
out = self.ac1(out)
out = self.do2(out)
out = self.fc2(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_size': 4, 'drop_rate': 0.5, 'fil_num': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 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, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (2, 4), (4, 1))
assert_size_stride(primals_5, (2,), (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((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_3, buf1,
buf2, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf0
del primals_3
buf3 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 2), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4, 2), (32, 8, 2, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf1, reinterpret_tensor(buf2, (64, 4), (4, 1), 0), primals_4
class _MLP_BNew(nn.Module):
"""MLP that only use age gender MMSE"""
def __init__(self, in_size, drop_rate, fil_num):
super(_MLP_BNew, self).__init__()
self.fc1 = nn.Linear(in_size, fil_num)
self.fc2 = nn.Linear(fil_num, 2)
self.do1 = nn.Dropout(drop_rate)
self.do2 = nn.Dropout(drop_rate)
self.ac1 = nn.LeakyReLU()
def forward(self, input_0):
primals_2 = self.fc1.weight
primals_3 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
colorfulbrain/brain2020
|
_MLP_B
| false
| 15,072
|
[
"MIT"
] | 91
|
1dde5d34fd2ba1f38bcc38f2c973d167c8c3a168
|
https://github.com/colorfulbrain/brain2020/tree/1dde5d34fd2ba1f38bcc38f2c973d167c8c3a168
|
Context2AnswerAttention
|
import torch
import torch.nn as nn
import torch.multiprocessing
import torch.utils.data
import torch.nn.modules.loss
class Context2AnswerAttention(nn.Module):
def __init__(self, dim, hidden_size):
super(Context2AnswerAttention, self).__init__()
self.linear_sim = nn.Linear(dim, hidden_size, bias=False)
def forward(self, context, answers, out_answers, mask_answers=None):
"""
Parameters
:context, (B, L, dim)
:answers, (B, N, dim)
:mask, (L, N)
Returns
:ques_emb, (L, dim)
"""
context_fc = torch.relu(self.linear_sim(context))
questions_fc = torch.relu(self.linear_sim(answers))
attention = torch.matmul(context_fc, questions_fc.transpose(-1, -2))
if mask_answers is not None:
attention = attention.masked_fill(~mask_answers.unsqueeze(1).
bool(), -Constants.INF)
prob = torch.softmax(attention, dim=-1)
emb = torch.matmul(prob, out_answers)
return emb
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 [[], {'dim': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.multiprocessing
import torch.utils.data
import torch.nn.modules.loss
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 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 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf1)
del primals_1
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf9 = 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)](buf2, buf9,
256, XBLOCK=256, num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3, buf8,
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(buf2, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1), 0)
del buf5
extern_kernels.bmm(reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(primals_4, (16, 4, 4), (16, 4, 1), 0),
out=buf7)
del buf6
return reinterpret_tensor(buf7, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf4, reinterpret_tensor(primals_4, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf2, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1), 0), buf8, buf9
class Context2AnswerAttentionNew(nn.Module):
def __init__(self, dim, hidden_size):
super(Context2AnswerAttentionNew, self).__init__()
self.linear_sim = nn.Linear(dim, hidden_size, bias=False)
def forward(self, input_0, input_1, input_2):
primals_1 = self.linear_sim.weight
primals_2 = input_0
primals_3 = input_1
primals_4 = input_2
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
cminusQAQ/graph4nlp
|
Context2AnswerAttention
| false
| 15,073
|
[
"Apache-2.0"
] | 1,269
|
d980e897131f1b9d3766750c06316d94749904fa
|
https://github.com/cminusQAQ/graph4nlp/tree/d980e897131f1b9d3766750c06316d94749904fa
|
HardMish
|
import torch
from torch import nn
class HardMish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x / 2 * torch.clamp(x + 2, min=0, max=2)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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_add_clamp_div_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.5
tmp2 = tmp0 * tmp1
tmp3 = 2.0
tmp4 = tmp0 + tmp3
tmp5 = 0.0
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp7 = triton_helpers.minimum(tmp6, tmp3)
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_clamp_div_mul_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class HardMishNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
cooked-sashimi/Yet-Another-YOLOv4-Pytorch
|
HardMish
| false
| 15,074
|
[
"MIT"
] | 133
|
c884ef8849987a75b0e17eba1b739c22d3782e90
|
https://github.com/cooked-sashimi/Yet-Another-YOLOv4-Pytorch/tree/c884ef8849987a75b0e17eba1b739c22d3782e90
|
_MLP_C
|
import torch
import torch.nn as nn
class _MLP_C(nn.Module):
"""MLP that use DPMs from fcn and age, gender and MMSE"""
def __init__(self, in_size, drop_rate, fil_num):
super(_MLP_C, self).__init__()
self.fc1 = nn.Linear(in_size, fil_num)
self.fc2 = nn.Linear(fil_num, 2)
self.do1 = nn.Dropout(drop_rate)
self.do2 = nn.Dropout(drop_rate)
self.ac1 = nn.LeakyReLU()
def forward(self, X1, X2):
X = torch.cat((X1, X2), 1)
out = self.do1(X)
out = self.fc1(out)
out = self.ac1(out)
out = self.do2(out)
out = self.fc2(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_size': 4, 'drop_rate': 0.5, 'fil_num': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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
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_leaky_relu_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
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 % 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, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (2, 4), (4, 1))
assert_size_stride(primals_6, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](primals_1, primals_2, buf0, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = empty_strided_cuda((128, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (128, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.bool)
buf3 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
triton_poi_fused_leaky_relu_1[grid(512)](buf1, primals_4, buf2,
buf3, 512, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_4
buf4 = empty_strided_cuda((128, 2), (2, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf3, (128, 4),
(4, 1), 0), reinterpret_tensor(primals_5, (4, 2), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_6
return reinterpret_tensor(buf4, (4, 8, 4, 2), (64, 8, 2, 1), 0
), reinterpret_tensor(buf0, (128, 4), (4, 1), 0
), buf2, reinterpret_tensor(buf3, (128, 4), (4, 1), 0), primals_5
class _MLP_CNew(nn.Module):
"""MLP that use DPMs from fcn and age, gender and MMSE"""
def __init__(self, in_size, drop_rate, fil_num):
super(_MLP_CNew, self).__init__()
self.fc1 = nn.Linear(in_size, fil_num)
self.fc2 = nn.Linear(fil_num, 2)
self.do1 = nn.Dropout(drop_rate)
self.do2 = nn.Dropout(drop_rate)
self.ac1 = nn.LeakyReLU()
def forward(self, input_0, input_1):
primals_3 = self.fc1.weight
primals_4 = self.fc1.bias
primals_5 = self.fc2.weight
primals_6 = self.fc2.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
colorfulbrain/brain2020
|
_MLP_C
| false
| 15,075
|
[
"MIT"
] | 91
|
1dde5d34fd2ba1f38bcc38f2c973d167c8c3a168
|
https://github.com/colorfulbrain/brain2020/tree/1dde5d34fd2ba1f38bcc38f2c973d167c8c3a168
|
DarknetMish
|
import torch
import torch.nn.functional as F
from torch import nn
class darknet_mish(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, input):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
ctx.save_for_backward(input)
e = torch.exp(input)
n = e * e + 2 * e
mask = input <= -0.6
input[mask] = (input * (n / (n + 2)))[mask]
input[~mask] = (input - 2 * (input / (n + 2)))[~mask]
return input
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
input, = ctx.saved_tensors
sp = F.softplus(input)
grad_sp = -torch.expm1(sp)
tsp = F.tanh(sp)
grad_tsp = (1 - tsp * tsp) * grad_sp
grad = input * grad_tsp + tsp
return grad
class DarknetMish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return darknet_mish.apply(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.functional as F
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_exp_le_mul_0(in_ptr0, out_ptr0, out_ptr1,
out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl_math.exp(tmp0)
tmp2 = tmp1 * tmp1
tmp3 = 2.0
tmp4 = tmp1 * tmp3
tmp5 = tmp2 + tmp4
tmp6 = tmp5 + tmp3
tmp7 = tmp5 / tmp6
tmp8 = tmp0 * tmp7
tmp9 = -0.6
tmp10 = tmp0 <= tmp9
tl.store(out_ptr0 + x0, tmp5, xmask)
tl.store(out_ptr1 + x0, tmp8, xmask)
tl.store(out_ptr2 + x0, tmp10, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
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)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_add_div_exp_le_mul_0[grid(256)](arg0_1, buf0, buf1,
buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf1, buf2, buf0
class darknet_mish(torch.autograd.Function):
"""
We can implement our own custom autograd Functions by subclassing
torch.autograd.Function and implementing the forward and backward passes
which operate on Tensors.
"""
@staticmethod
def forward(ctx, input):
"""
In the forward pass we receive a Tensor containing the input and return
a Tensor containing the output. ctx is a context object that can be used
to stash information for backward computation. You can cache arbitrary
objects for use in the backward pass using the ctx.save_for_backward method.
"""
ctx.save_for_backward(input)
e = torch.exp(input)
n = e * e + 2 * e
mask = input <= -0.6
input[mask] = (input * (n / (n + 2)))[mask]
input[~mask] = (input - 2 * (input / (n + 2)))[~mask]
return input
@staticmethod
def backward(ctx, grad_output):
"""
In the backward pass we receive a Tensor containing the gradient of the loss
with respect to the output, and we need to compute the gradient of the loss
with respect to the input.
"""
input, = ctx.saved_tensors
sp = F.softplus(input)
grad_sp = -torch.expm1(sp)
tsp = F.tanh(sp)
grad_tsp = (1 - tsp * tsp) * grad_sp
grad = input * grad_tsp + tsp
return grad
class DarknetMishNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
cooked-sashimi/Yet-Another-YOLOv4-Pytorch
|
DarknetMish
| false
| 15,076
|
[
"MIT"
] | 133
|
c884ef8849987a75b0e17eba1b739c22d3782e90
|
https://github.com/cooked-sashimi/Yet-Another-YOLOv4-Pytorch/tree/c884ef8849987a75b0e17eba1b739c22d3782e90
|
Tanh2
|
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.parallel
import torch.optim
class Tanh2(nn.Module):
def __init__(self):
super(Tanh2, self).__init__()
self.tanh = nn.Tanh()
def forward(self, x):
return (self.tanh(x) + 1) / 2
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.utils.data
import torch.nn as nn
import torch.nn.parallel
import torch.optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_tanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = libdevice.tanh(tmp0)
tmp2 = 1.0
tmp3 = tmp1 + tmp2
tmp4 = 0.5
tmp5 = tmp3 * tmp4
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_tanh_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class Tanh2New(nn.Module):
def __init__(self):
super(Tanh2New, self).__init__()
self.tanh = nn.Tanh()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
csyxwei/FFWM
|
Tanh2
| false
| 15,077
|
[
"MIT"
] | 83
|
d42c578cabe1b81c6b1bb0c3cb707b190fca3c68
|
https://github.com/csyxwei/FFWM/tree/d42c578cabe1b81c6b1bb0c3cb707b190fca3c68
|
SAM
|
import torch
from torch import nn
class SAM(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels=1, kernel_size=1)
def forward(self, x):
spatial_features = self.conv(x)
attention = torch.sigmoid(spatial_features)
return attention.expand_as(x) * x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch 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 = 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_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 1, 4, 4), (16, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(64)](buf1, primals_2, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_mul_1[grid(256)](buf1, primals_3, buf2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
return buf2, primals_1, primals_3, buf1
class SAMNew(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels=1, kernel_size=1)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
cooked-sashimi/Yet-Another-YOLOv4-Pytorch
|
SAM
| false
| 15,078
|
[
"MIT"
] | 133
|
c884ef8849987a75b0e17eba1b739c22d3782e90
|
https://github.com/cooked-sashimi/Yet-Another-YOLOv4-Pytorch/tree/c884ef8849987a75b0e17eba1b739c22d3782e90
|
GlobalAttentionGeneral
|
import torch
import torch.nn as nn
import torch.nn.parallel
def conv1x1(in_planes, out_planes, bias=False):
"""1x1 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1,
padding=0, bias=bias)
class GlobalAttentionGeneral(nn.Module):
def __init__(self, idf, cdf):
super(GlobalAttentionGeneral, self).__init__()
self.conv_context = conv1x1(cdf, idf)
self.sm = nn.Softmax(dim=1)
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 = context.unsqueeze(3)
sourceT = self.conv_context(sourceT).squeeze(3)
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 = self.sm(attn)
attn = attn.view(batch_size, queryL, sourceL)
attn = torch.transpose(attn, 1, 2).contiguous()
weightedContext = torch.bmm(sourceT, attn)
weightedContext = weightedContext.view(batch_size, -1, ih, iw)
attn = attn.view(batch_size, -1, ih, iw)
return weightedContext, attn
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__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, 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)
tmp1 = tl.load(in_ptr0 + (4 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + (x2 + 16 * y3), tmp8, xmask & ymask)
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), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_2, (4,
4, 4, 1), (16, 4, 1, 1), 0), primals_3, 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, 1), (16, 4, 1, 1))
buf1 = empty_strided_cuda((4, 16, 4), (64, 1, 16), torch.float32)
buf6 = 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,
buf6, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf2 = empty_strided_cuda((4, 16, 4), (64, 4, 1), torch.float32)
extern_kernels.bmm(buf1, reinterpret_tensor(buf0, (4, 4, 4), (16, 4,
1), 0), out=buf2)
buf3 = reinterpret_tensor(buf1, (64, 4), (4, 1), 0)
del buf1
triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_clone_2[grid(16, 16)](buf3, buf4, 16, 16, XBLOCK=
16, YBLOCK=16, num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 16), (64, 16, 1), 0)
del buf3
extern_kernels.bmm(reinterpret_tensor(buf0, (4, 4, 4), (16, 4, 1),
0), buf4, out=buf5)
return reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_3, reinterpret_tensor(primals_2, (4, 4, 4, 1), (16, 4, 1,
1), 0), buf2, reinterpret_tensor(buf0, (4, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf4, (4, 16, 4), (64, 1, 16), 0), buf6
def conv1x1(in_planes, out_planes, bias=False):
"""1x1 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1,
padding=0, bias=bias)
class GlobalAttentionGeneralNew(nn.Module):
def __init__(self, idf, cdf):
super(GlobalAttentionGeneralNew, self).__init__()
self.conv_context = conv1x1(cdf, idf)
self.sm = nn.Softmax(dim=1)
self.mask = None
def applyMask(self, mask):
self.mask = mask
def forward(self, input_0, input_1):
primals_3 = self.conv_context.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0], output[1]
|
comtalyst/multi-gan-material-defects
|
GlobalAttentionGeneral
| false
| 15,079
|
[
"MIT"
] | 112
|
aa1c9d4b918b5b5ad7f5fe03fdceec91a66e1007
|
https://github.com/comtalyst/multi-gan-material-defects/tree/aa1c9d4b918b5b5ad7f5fe03fdceec91a66e1007
|
Attention
|
import torch
from torch import nn
class Attention(nn.Module):
def __init__(self, in_channels):
super(Attention, self).__init__()
self.out_channels = int(in_channels / 2)
self.conv1 = nn.Conv2d(in_channels, self.out_channels, kernel_size=
3, padding=1, stride=1)
self.relu1 = nn.ReLU()
self.conv2 = nn.Conv2d(self.out_channels, self.out_channels,
kernel_size=3, padding=1, stride=1)
self.relu2 = nn.ReLU()
self.conv3 = nn.Conv2d(self.out_channels, 4, kernel_size=1, padding
=0, stride=1)
self.sigmod = nn.Sigmoid()
def forward(self, x):
out = self.conv1(x)
out = self.relu1(out)
out = self.conv2(out)
out = self.relu2(out)
out = self.conv3(out)
out = self.sigmod(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 2
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
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_sigmoid_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x3, 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, (2, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (2,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (2, 2, 3, 3), (18, 9, 3, 1))
assert_size_stride(primals_5, (2,), (1,))
assert_size_stride(primals_6, (4, 2, 1, 1), (2, 1, 1, 1))
assert_size_stride(primals_7, (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, 2, 4, 4), (32, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(128)](buf1, primals_2, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 2, 4, 4), (32, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(128)](buf3, primals_5, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_sigmoid_1[grid(256)](buf5, primals_7,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
return buf5, primals_1, primals_3, primals_4, primals_6, buf1, buf3, buf5
class AttentionNew(nn.Module):
def __init__(self, in_channels):
super(AttentionNew, self).__init__()
self.out_channels = int(in_channels / 2)
self.conv1 = nn.Conv2d(in_channels, self.out_channels, kernel_size=
3, padding=1, stride=1)
self.relu1 = nn.ReLU()
self.conv2 = nn.Conv2d(self.out_channels, self.out_channels,
kernel_size=3, padding=1, stride=1)
self.relu2 = nn.ReLU()
self.conv3 = nn.Conv2d(self.out_channels, 4, kernel_size=1, padding
=0, stride=1)
self.sigmod = 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_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
createnewdemo/SPANet
|
Attention
| false
| 15,080
|
[
"BSD-3-Clause"
] | 177
|
86cfb05d1778cf30142ef30692e995a5b7b59bb8
|
https://github.com/createnewdemo/SPANet/tree/86cfb05d1778cf30142ef30692e995a5b7b59bb8
|
Bottleneck
|
import torch
from torch import nn
from collections import OrderedDict
class Bottleneck(nn.Module):
def __init__(self, in_channels, out_channels):
super(Bottleneck, self).__init__()
m = OrderedDict()
m['conv1'] = nn.Conv2d(in_channels, out_channels, kernel_size=1,
bias=False)
m['relu1'] = nn.ReLU(True)
m['conv2'] = nn.Conv2d(out_channels, out_channels, kernel_size=3,
stride=1, padding=2, bias=False, dilation=2)
m['relu2'] = nn.ReLU(True)
m['conv3'] = nn.Conv2d(out_channels, out_channels, kernel_size=1,
bias=False)
self.group1 = nn.Sequential(m)
self.relu = nn.Sequential(nn.ReLU(True))
def forward(self, x):
out = self.group1(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
from collections import OrderedDict
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@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)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 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_2, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](buf1, 256, XBLOCK=128, num_warps
=4, num_stages=1)
buf2 = extern_kernels.convolution(buf1, primals_3, stride=(1, 1),
padding=(2, 2), dilation=(2, 2), 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))
return buf4, primals_1, primals_2, primals_3, primals_4, buf1, buf3
class BottleneckNew(nn.Module):
def __init__(self, in_channels, out_channels):
super(BottleneckNew, self).__init__()
m = OrderedDict()
m['conv1'] = nn.Conv2d(in_channels, out_channels, kernel_size=1,
bias=False)
m['relu1'] = nn.ReLU(True)
m['conv2'] = nn.Conv2d(out_channels, out_channels, kernel_size=3,
stride=1, padding=2, bias=False, dilation=2)
m['relu2'] = nn.ReLU(True)
m['conv3'] = nn.Conv2d(out_channels, out_channels, kernel_size=1,
bias=False)
self.group1 = nn.Sequential(m)
self.relu = nn.Sequential(nn.ReLU(True))
def forward(self, input_0):
primals_1 = self.group1.conv1.weight
primals_3 = self.group1.conv2.weight
primals_4 = self.group1.conv3.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
createnewdemo/SPANet
|
Bottleneck
| false
| 15,081
|
[
"BSD-3-Clause"
] | 177
|
86cfb05d1778cf30142ef30692e995a5b7b59bb8
|
https://github.com/createnewdemo/SPANet/tree/86cfb05d1778cf30142ef30692e995a5b7b59bb8
|
FeatureExtractFF
|
import torch
import torch.utils.data
import torch.nn as nn
class FeatureExtractFF(nn.Module):
def __init__(self, input_dim, hidden_sizes=(15,), activation_fn=nn.ReLU,
**activation_args):
super(FeatureExtractFF, self).__init__()
self._in = input_dim
self._hidden_sizes = hidden_sizes
self._activation_fn = activation_fn
self._activation_args = activation_args
self.feature = nn.Sequential()
hin = self._in
for i, h in enumerate(self._hidden_sizes):
self.feature.add_module(f'f_fc{i}', nn.Linear(hin, h))
self.feature.add_module(f'f_{activation_fn.__name__}{i}',
activation_fn(**activation_args))
hin = h
self._out_features = hin
def forward(self, input_data):
return self.feature(input_data)
def extra_repr(self):
return f'FC: {self.hidden_sizes}x{self._activation_fn.__name__}'
def hidden_layer(self, index=0):
return self.feature[index * 2]
def output_size(self):
return self._out_features
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 960
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 15
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (15, 4), (4, 1))
assert_size_stride(primals_2, (15,), (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, 15), (15, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 15), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 15), (240, 60, 15, 1), 0)
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 15), (240, 60, 15, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(960)](buf1,
primals_2, buf2, 960, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf2
class FeatureExtractFFNew(nn.Module):
def __init__(self, input_dim, hidden_sizes=(15,), activation_fn=nn.ReLU,
**activation_args):
super(FeatureExtractFFNew, self).__init__()
self._in = input_dim
self._hidden_sizes = hidden_sizes
self._activation_fn = activation_fn
self._activation_args = activation_args
self.feature = nn.Sequential()
hin = self._in
for i, h in enumerate(self._hidden_sizes):
self.feature.add_module(f'f_fc{i}', nn.Linear(hin, h))
self.feature.add_module(f'f_{activation_fn.__name__}{i}',
activation_fn(**activation_args))
hin = h
self._out_features = hin
def extra_repr(self):
return f'FC: {self.hidden_sizes}x{self._activation_fn.__name__}'
def hidden_layer(self, index=0):
return self.feature[index * 2]
def output_size(self):
return self._out_features
def forward(self, input_0):
primals_1 = self.feature.f_fc0.weight
primals_2 = self.feature.f_fc0.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
criteo-research/pytorch-ada
|
FeatureExtractFF
| false
| 15,082
|
[
"Apache-2.0"
] | 68
|
4b8861ce1c12fc8a4391eb14a811459e3e8a074a
|
https://github.com/criteo-research/pytorch-ada/tree/4b8861ce1c12fc8a4391eb14a811459e3e8a074a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.