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
|
|---|---|---|---|---|---|---|---|---|---|---|
CriticNet
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CriticNet(nn.Module):
"""Critic (Value estimator) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64,
fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super().__init__()
None
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, 1)
def forward(self, state):
"""Build a network that maps state -> expected Q values."""
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
v = self.fc3(x)
return v.squeeze()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'seed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, None)
tl.store(out_ptr0 + x2, tmp6, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (64, 4), (4, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (64, 64), (64, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (1, 64), (64, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf0
buf7 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1,
primals_2, buf7, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0),
reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0)
del buf2
buf6 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool
)
triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf3,
primals_5, buf6, 4096, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 64),
(64, 1), 0), reinterpret_tensor(primals_6, (64, 1), (1, 64), 0),
alpha=1, beta=1, out=buf5)
del primals_7
return reinterpret_tensor(buf5, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(
buf3, (64, 64), (64, 1), 0), primals_6, buf6, primals_4, buf7
class CriticNetNew(nn.Module):
"""Critic (Value estimator) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=64,
fc2_units=64):
"""Initialize parameters and build model.
Params
======
state_size (int): Dimension of each state
action_size (int): Dimension of each action
seed (int): Random seed
fc1_units (int): Number of nodes in first hidden layer
fc2_units (int): Number of nodes in second hidden layer
"""
super().__init__()
None
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, 1)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
danthe42/drlnd_p2
|
CriticNet
| false
| 1,789
|
[
"MIT"
] | 0
|
693813feb7c99f3e01da583e5b67e4f8904639c4
|
https://github.com/danthe42/drlnd_p2/tree/693813feb7c99f3e01da583e5b67e4f8904639c4
|
SetConv
|
import torch
from torch.nn import functional as F
import torch.nn as nn
class SetConv(nn.Module):
def __init__(self, sample_feats, predicate_feats, join_feats, hid_units):
super(SetConv, self).__init__()
self.sample_mlp1 = nn.Linear(sample_feats, hid_units)
self.sample_mlp2 = nn.Linear(hid_units, hid_units)
self.predicate_mlp1 = nn.Linear(predicate_feats, hid_units)
self.predicate_mlp2 = nn.Linear(hid_units, hid_units)
self.join_mlp1 = nn.Linear(join_feats, hid_units)
self.join_mlp2 = nn.Linear(hid_units, hid_units)
self.out_mlp1 = nn.Linear(hid_units * 3, hid_units)
self.out_mlp2 = nn.Linear(hid_units, 1)
def forward(self, samples, predicates, joins, sample_mask,
predicate_mask, join_mask):
hid_sample = F.relu(self.sample_mlp1(samples))
hid_sample = F.relu(self.sample_mlp2(hid_sample))
hid_sample = hid_sample * sample_mask
hid_sample = torch.sum(hid_sample, dim=1, keepdim=False)
sample_norm = sample_mask.sum(1, keepdim=False)
hid_sample = hid_sample / sample_norm
hid_predicate = F.relu(self.predicate_mlp1(predicates))
hid_predicate = F.relu(self.predicate_mlp2(hid_predicate))
hid_predicate = hid_predicate * predicate_mask
hid_predicate = torch.sum(hid_predicate, dim=1, keepdim=False)
predicate_norm = predicate_mask.sum(1, keepdim=False)
hid_predicate = hid_predicate / predicate_norm
hid_join = F.relu(self.join_mlp1(joins))
hid_join = F.relu(self.join_mlp2(hid_join))
hid_join = hid_join * join_mask
hid_join = torch.sum(hid_join, dim=1, keepdim=False)
join_norm = join_mask.sum(1, keepdim=False)
hid_join = hid_join / join_norm
hid = torch.cat((hid_sample, hid_predicate, hid_join), 1)
hid = F.relu(self.out_mlp1(hid))
out = torch.sigmoid(self.out_mlp2(hid))
return out
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4])]
def get_init_inputs():
return [[], {'sample_feats': 4, 'predicate_feats': 4, 'join_feats': 4,
'hid_units': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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 = 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_mul_relu_sum_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp10 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp13 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp16 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask)
tmp19 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp22 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = tmp4 * tmp5
tmp8 = tmp7 + tmp1
tmp9 = triton_helpers.maximum(tmp3, tmp8)
tmp11 = tmp9 * tmp10
tmp12 = tmp6 + tmp11
tmp14 = tmp13 + tmp1
tmp15 = triton_helpers.maximum(tmp3, tmp14)
tmp17 = tmp15 * tmp16
tmp18 = tmp12 + tmp17
tmp20 = tmp19 + tmp1
tmp21 = triton_helpers.maximum(tmp3, tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tmp18 + tmp23
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + (16 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tl.load(in_ptr1 + (4 + 16 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.load(in_ptr1 + (8 + 16 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tmp8 + tmp9
tmp11 = tl.load(in_ptr1 + (12 + 16 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp12 = tmp10 + tmp11
tmp13 = tmp5 / tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp4, tmp13, tmp14)
tmp16 = tmp0 >= tmp3
tmp17 = tl.full([1], 8, tl.int64)
tmp18 = tmp0 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tl.load(in_ptr2 + (4 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = tl.load(in_ptr3 + (16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp22 = tl.load(in_ptr3 + (4 + 16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp23 = tmp21 + tmp22
tmp24 = tl.load(in_ptr3 + (8 + 16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp25 = tmp23 + tmp24
tmp26 = tl.load(in_ptr3 + (12 + 16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp27 = tmp25 + tmp26
tmp28 = tmp20 / tmp27
tmp29 = tl.full(tmp28.shape, 0.0, tmp28.dtype)
tmp30 = tl.where(tmp19, tmp28, tmp29)
tmp31 = tmp0 >= tmp17
tl.full([1], 12, tl.int64)
tmp34 = tl.load(in_ptr4 + (4 * x1 + (-8 + x0)), tmp31 & xmask,
eviction_policy='evict_last', other=0.0)
tmp35 = tl.load(in_ptr5 + (16 * x1 + (-8 + x0)), tmp31 & xmask,
eviction_policy='evict_last', other=0.0)
tmp36 = tl.load(in_ptr5 + (4 + 16 * x1 + (-8 + x0)), tmp31 & xmask,
eviction_policy='evict_last', other=0.0)
tmp37 = tmp35 + tmp36
tmp38 = tl.load(in_ptr5 + (8 + 16 * x1 + (-8 + x0)), tmp31 & xmask,
eviction_policy='evict_last', other=0.0)
tmp39 = tmp37 + tmp38
tmp40 = tl.load(in_ptr5 + (12 + 16 * x1 + (-8 + x0)), tmp31 & xmask,
eviction_policy='evict_last', other=0.0)
tmp41 = tmp39 + tmp40
tmp42 = tmp34 / tmp41
tmp43 = tl.full(tmp42.shape, 0.0, tmp42.dtype)
tmp44 = tl.where(tmp31, tmp42, tmp43)
tmp45 = tl.where(tmp19, tmp30, tmp44)
tmp46 = tl.where(tmp4, tmp15, tmp45)
tl.store(out_ptr0 + x2, tmp46, xmask)
@triton.jit
def triton_poi_fused_relu_3(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_sigmoid_4(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)
@triton.jit
def triton_poi_fused_relu_threshold_backward_5(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
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (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), (16, 4, 1))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_16, (4, 4), (4, 1))
assert_size_stride(primals_17, (4,), (1,))
assert_size_stride(primals_18, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_19, (4, 12), (12, 1))
assert_size_stride(primals_20, (4,), (1,))
assert_size_stride(primals_21, (1, 4), (4, 1))
assert_size_stride(primals_22, (1,), (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_3, (16, 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), (16, 4, 1), 0)
del buf0
buf22 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf1,
primals_2, buf22, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf2, primals_5,
primals_6, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf4)
del primals_7
buf5 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
buf20 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf5,
primals_8, buf20, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_8
buf6 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf6)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf6, primals_11,
primals_12, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf8 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_15, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), out=buf8)
del primals_13
buf9 = reinterpret_tensor(buf8, (4, 4, 4), (16, 4, 1), 0)
del buf8
buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf9,
primals_14, buf18, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_14
buf10 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_16, (4, 4), (1, 4), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf10, primals_17,
primals_18, buf11, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
triton_poi_fused_cat_2[grid(48)](buf3, primals_6, buf7, primals_12,
buf11, primals_18, buf12, 48, XBLOCK=64, num_warps=1, num_stages=1)
del buf11
del buf3
buf13 = buf7
del buf7
extern_kernels.mm(buf12, reinterpret_tensor(primals_19, (12, 4), (1,
12), 0), out=buf13)
buf14 = buf13
del buf13
triton_poi_fused_relu_3[grid(16)](buf14, primals_20, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_20
buf15 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf14, reinterpret_tensor(primals_21, (4, 1), (1,
4), 0), out=buf15)
buf16 = buf15
del buf15
triton_poi_fused_sigmoid_4[grid(4)](buf16, primals_22, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_22
buf17 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf10,
primals_17, buf17, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf10
del primals_17
buf19 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf6,
primals_11, buf19, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf6
del primals_11
buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf2,
primals_5, buf21, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf2
del primals_5
return (buf16, primals_6, primals_12, primals_18, reinterpret_tensor(
primals_3, (16, 4), (4, 1), 0), reinterpret_tensor(buf1, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0),
reinterpret_tensor(buf5, (16, 4), (4, 1), 0), reinterpret_tensor(
primals_15, (16, 4), (4, 1), 0), reinterpret_tensor(buf9, (16, 4),
(4, 1), 0), buf12, buf14, buf16, primals_21, primals_19, buf17,
primals_16, buf18, buf19, primals_10, buf20, buf21, primals_4, buf22)
class SetConvNew(nn.Module):
def __init__(self, sample_feats, predicate_feats, join_feats, hid_units):
super(SetConvNew, self).__init__()
self.sample_mlp1 = nn.Linear(sample_feats, hid_units)
self.sample_mlp2 = nn.Linear(hid_units, hid_units)
self.predicate_mlp1 = nn.Linear(predicate_feats, hid_units)
self.predicate_mlp2 = nn.Linear(hid_units, hid_units)
self.join_mlp1 = nn.Linear(join_feats, hid_units)
self.join_mlp2 = nn.Linear(hid_units, hid_units)
self.out_mlp1 = nn.Linear(hid_units * 3, hid_units)
self.out_mlp2 = nn.Linear(hid_units, 1)
def forward(self, input_0, input_1, input_2, input_3, input_4, input_5):
primals_1 = self.sample_mlp1.weight
primals_2 = self.sample_mlp1.bias
primals_4 = self.sample_mlp2.weight
primals_5 = self.sample_mlp2.bias
primals_7 = self.predicate_mlp1.weight
primals_8 = self.predicate_mlp1.bias
primals_10 = self.predicate_mlp2.weight
primals_11 = self.predicate_mlp2.bias
primals_13 = self.join_mlp1.weight
primals_14 = self.join_mlp1.bias
primals_16 = self.join_mlp2.weight
primals_17 = self.join_mlp2.bias
primals_19 = self.out_mlp1.weight
primals_20 = self.out_mlp1.bias
primals_21 = self.out_mlp2.weight
primals_22 = self.out_mlp2.bias
primals_3 = input_0
primals_6 = input_1
primals_9 = input_2
primals_12 = input_3
primals_15 = input_4
primals_18 = input_5
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22])
return output[0]
|
danield137/deep_query_optimzation
|
SetConv
| false
| 1,790
|
[
"MIT"
] | 0
|
01a25c966338007f15d14dea1b37e388e47bcfe3
|
https://github.com/danield137/deep_query_optimzation/tree/01a25c966338007f15d14dea1b37e388e47bcfe3
|
SetConv
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SetConv(nn.Module):
def __init__(self, sample_feats, predicate_feats, predicate_uri_feats,
join_feats, hid_units):
super(SetConv, self).__init__()
self.sample_mlp1 = nn.Linear(sample_feats, hid_units)
self.sample_mlp2 = nn.Linear(hid_units, hid_units)
self.predicate_mlp1 = nn.Linear(predicate_feats, hid_units)
self.predicate_mlp2 = nn.Linear(hid_units, hid_units)
self.predicate_uri_mlp1 = nn.Linear(predicate_uri_feats, hid_units)
self.predicate_uri_mlp2 = nn.Linear(hid_units, hid_units)
self.join_mlp1 = nn.Linear(join_feats, hid_units)
self.join_mlp2 = nn.Linear(hid_units, hid_units)
self.out_mlp1 = nn.Linear(hid_units * 4, hid_units)
self.out_mlp2 = nn.Linear(hid_units, 1)
def forward(self, samples, predicates, predicates_uris, joins,
sample_mask, predicate_mask, predicate_uri_mask, join_mask):
hid_sample = F.relu(self.sample_mlp1(samples))
hid_sample = F.relu(self.sample_mlp2(hid_sample))
hid_sample = hid_sample * sample_mask
hid_sample = torch.sum(hid_sample, dim=1, keepdim=False)
sample_norm = sample_mask.sum(1, keepdim=False)
hid_sample = hid_sample / sample_norm
hid_predicate = F.relu(self.predicate_mlp1(predicates))
hid_predicate = F.relu(self.predicate_mlp2(hid_predicate))
hid_predicate = hid_predicate * predicate_mask
hid_predicate = torch.sum(hid_predicate, dim=1, keepdim=False)
predicate_norm = predicate_mask.sum(1, keepdim=False)
hid_predicate = hid_predicate / predicate_norm
hid_predicate_uri = F.relu(self.predicate_uri_mlp1(predicates_uris))
hid_predicate_uri = F.relu(self.predicate_uri_mlp2(hid_predicate_uri))
hid_predicate_uri = hid_predicate_uri * predicate_uri_mask
hid_predicate_uri = torch.sum(hid_predicate_uri, dim=1, keepdim=False)
predicate_uri_norm = predicate_uri_mask.sum(1, keepdim=False)
hid_predicate_uri = hid_predicate_uri / predicate_uri_norm
hid_join = F.relu(self.join_mlp1(joins))
hid_join = F.relu(self.join_mlp2(hid_join))
hid_join = hid_join * join_mask
hid_join = torch.sum(hid_join, dim=1, keepdim=False)
join_norm = join_mask.sum(1, keepdim=False)
hid_join = hid_join / join_norm
hid = torch.cat((hid_sample, hid_predicate, hid_predicate_uri,
hid_join), 1)
hid = F.relu(self.out_mlp1(hid))
out = torch.sigmoid(self.out_mlp2(hid))
return out
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'sample_feats': 4, 'predicate_feats': 4,
'predicate_uri_feats': 4, 'join_feats': 4, 'hid_units': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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 = 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_mul_relu_sum_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + (x0 + 16 * x1), xmask)
tmp7 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp10 = tl.load(in_ptr2 + (4 + x0 + 16 * x1), xmask)
tmp13 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp16 = tl.load(in_ptr2 + (8 + x0 + 16 * x1), xmask)
tmp19 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp22 = tl.load(in_ptr2 + (12 + x0 + 16 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = tmp4 * tmp5
tmp8 = tmp7 + tmp1
tmp9 = triton_helpers.maximum(tmp3, tmp8)
tmp11 = tmp9 * tmp10
tmp12 = tmp6 + tmp11
tmp14 = tmp13 + tmp1
tmp15 = triton_helpers.maximum(tmp3, tmp14)
tmp17 = tmp15 * tmp16
tmp18 = tmp12 + tmp17
tmp20 = tmp19 + tmp1
tmp21 = triton_helpers.maximum(tmp3, tmp20)
tmp23 = tmp21 * tmp22
tmp24 = tmp18 + tmp23
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, in_ptr6, in_ptr7, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + (16 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tl.load(in_ptr1 + (4 + 16 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp8 = tmp6 + tmp7
tmp9 = tl.load(in_ptr1 + (8 + 16 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tmp8 + tmp9
tmp11 = tl.load(in_ptr1 + (12 + 16 * x1 + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp12 = tmp10 + tmp11
tmp13 = tmp5 / tmp12
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp4, tmp13, tmp14)
tmp16 = tmp0 >= tmp3
tmp17 = tl.full([1], 8, tl.int64)
tmp18 = tmp0 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tl.load(in_ptr2 + (4 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp21 = tl.load(in_ptr3 + (16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp22 = tl.load(in_ptr3 + (4 + 16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp23 = tmp21 + tmp22
tmp24 = tl.load(in_ptr3 + (8 + 16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp25 = tmp23 + tmp24
tmp26 = tl.load(in_ptr3 + (12 + 16 * x1 + (-4 + x0)), tmp19 & xmask,
eviction_policy='evict_last', other=0.0)
tmp27 = tmp25 + tmp26
tmp28 = tmp20 / tmp27
tmp29 = tl.full(tmp28.shape, 0.0, tmp28.dtype)
tmp30 = tl.where(tmp19, tmp28, tmp29)
tmp31 = tmp0 >= tmp17
tmp32 = tl.full([1], 12, tl.int64)
tmp33 = tmp0 < tmp32
tmp34 = tmp31 & tmp33
tmp35 = tl.load(in_ptr4 + (4 * x1 + (-8 + x0)), tmp34 & xmask,
eviction_policy='evict_last', other=0.0)
tmp36 = tl.load(in_ptr5 + (16 * x1 + (-8 + x0)), tmp34 & xmask,
eviction_policy='evict_last', other=0.0)
tmp37 = tl.load(in_ptr5 + (4 + 16 * x1 + (-8 + x0)), tmp34 & xmask,
eviction_policy='evict_last', other=0.0)
tmp38 = tmp36 + tmp37
tmp39 = tl.load(in_ptr5 + (8 + 16 * x1 + (-8 + x0)), tmp34 & xmask,
eviction_policy='evict_last', other=0.0)
tmp40 = tmp38 + tmp39
tmp41 = tl.load(in_ptr5 + (12 + 16 * x1 + (-8 + x0)), tmp34 & xmask,
eviction_policy='evict_last', other=0.0)
tmp42 = tmp40 + tmp41
tmp43 = tmp35 / tmp42
tmp44 = tl.full(tmp43.shape, 0.0, tmp43.dtype)
tmp45 = tl.where(tmp34, tmp43, tmp44)
tmp46 = tmp0 >= tmp32
tl.full([1], 16, tl.int64)
tmp49 = tl.load(in_ptr6 + (4 * x1 + (-12 + x0)), tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp50 = tl.load(in_ptr7 + (16 * x1 + (-12 + x0)), tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp51 = tl.load(in_ptr7 + (4 + 16 * x1 + (-12 + x0)), tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp52 = tmp50 + tmp51
tmp53 = tl.load(in_ptr7 + (8 + 16 * x1 + (-12 + x0)), tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp54 = tmp52 + tmp53
tmp55 = tl.load(in_ptr7 + (12 + 16 * x1 + (-12 + x0)), tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp56 = tmp54 + tmp55
tmp57 = tmp49 / tmp56
tmp58 = tl.full(tmp57.shape, 0.0, tmp57.dtype)
tmp59 = tl.where(tmp46, tmp57, tmp58)
tmp60 = tl.where(tmp34, tmp45, tmp59)
tmp61 = tl.where(tmp19, tmp30, tmp60)
tmp62 = tl.where(tmp4, tmp15, tmp61)
tl.store(out_ptr0 + x2, tmp62, xmask)
@triton.jit
def triton_poi_fused_relu_3(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_sigmoid_4(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)
@triton.jit
def triton_poi_fused_relu_threshold_backward_5(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
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, 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
) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (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), (16, 4, 1))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_16, (4, 4), (4, 1))
assert_size_stride(primals_17, (4,), (1,))
assert_size_stride(primals_18, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_19, (4, 4), (4, 1))
assert_size_stride(primals_20, (4,), (1,))
assert_size_stride(primals_21, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_22, (4, 4), (4, 1))
assert_size_stride(primals_23, (4,), (1,))
assert_size_stride(primals_24, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_25, (4, 16), (16, 1))
assert_size_stride(primals_26, (4,), (1,))
assert_size_stride(primals_27, (1, 4), (4, 1))
assert_size_stride(primals_28, (1,), (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_3, (16, 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), (16, 4, 1), 0)
del buf0
buf28 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf1,
primals_2, buf28, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf2, primals_5,
primals_6, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf4)
del primals_7
buf5 = reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0)
del buf4
buf26 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf5,
primals_8, buf26, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_8
buf6 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf6)
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf6, primals_11,
primals_12, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf8 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_15, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), out=buf8)
del primals_13
buf9 = reinterpret_tensor(buf8, (4, 4, 4), (16, 4, 1), 0)
del buf8
buf24 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf9,
primals_14, buf24, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_14
buf10 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_16, (4, 4), (1, 4), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf10, primals_17,
primals_18, buf11, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf12 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_21, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_19, (4, 4), (1, 4), 0), out=buf12)
del primals_19
buf13 = reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0)
del buf12
buf22 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(64)](buf13,
primals_20, buf22, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_20
buf14 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf13, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_22, (4, 4), (1, 4), 0), out=buf14)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_relu_sum_1[grid(16)](buf14, primals_23,
primals_24, buf15, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf16 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_poi_fused_cat_2[grid(64)](buf3, primals_6, buf7, primals_12,
buf11, primals_18, buf15, primals_24, buf16, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf11
del buf15
del buf3
buf17 = buf7
del buf7
extern_kernels.mm(buf16, reinterpret_tensor(primals_25, (16, 4), (1,
16), 0), out=buf17)
buf18 = buf17
del buf17
triton_poi_fused_relu_3[grid(16)](buf18, primals_26, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_26
buf19 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf18, reinterpret_tensor(primals_27, (4, 1), (1,
4), 0), out=buf19)
buf20 = buf19
del buf19
triton_poi_fused_sigmoid_4[grid(4)](buf20, primals_28, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_28
buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf14,
primals_23, buf21, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf14
del primals_23
buf23 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf10,
primals_17, buf23, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf10
del primals_17
buf25 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf6,
primals_11, buf25, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf6
del primals_11
buf27 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf2,
primals_5, buf27, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf2
del primals_5
return (buf20, primals_6, primals_12, primals_18, primals_24,
reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(buf1, (16, 4), (4, 1), 0), reinterpret_tensor(
primals_9, (16, 4), (4, 1), 0), reinterpret_tensor(buf5, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_15, (16, 4), (4, 1), 0),
reinterpret_tensor(buf9, (16, 4), (4, 1), 0), reinterpret_tensor(
primals_21, (16, 4), (4, 1), 0), reinterpret_tensor(buf13, (16, 4),
(4, 1), 0), buf16, buf18, buf20, primals_27, primals_25, buf21,
primals_22, buf22, buf23, primals_16, buf24, buf25, primals_10,
buf26, buf27, primals_4, buf28)
class SetConvNew(nn.Module):
def __init__(self, sample_feats, predicate_feats, predicate_uri_feats,
join_feats, hid_units):
super(SetConvNew, self).__init__()
self.sample_mlp1 = nn.Linear(sample_feats, hid_units)
self.sample_mlp2 = nn.Linear(hid_units, hid_units)
self.predicate_mlp1 = nn.Linear(predicate_feats, hid_units)
self.predicate_mlp2 = nn.Linear(hid_units, hid_units)
self.predicate_uri_mlp1 = nn.Linear(predicate_uri_feats, hid_units)
self.predicate_uri_mlp2 = nn.Linear(hid_units, hid_units)
self.join_mlp1 = nn.Linear(join_feats, hid_units)
self.join_mlp2 = nn.Linear(hid_units, hid_units)
self.out_mlp1 = nn.Linear(hid_units * 4, hid_units)
self.out_mlp2 = nn.Linear(hid_units, 1)
def forward(self, input_0, input_1, input_2, input_3, input_4, input_5,
input_6, input_7):
primals_1 = self.sample_mlp1.weight
primals_2 = self.sample_mlp1.bias
primals_4 = self.sample_mlp2.weight
primals_5 = self.sample_mlp2.bias
primals_7 = self.predicate_mlp1.weight
primals_8 = self.predicate_mlp1.bias
primals_10 = self.predicate_mlp2.weight
primals_11 = self.predicate_mlp2.bias
primals_13 = self.predicate_uri_mlp1.weight
primals_14 = self.predicate_uri_mlp1.bias
primals_16 = self.predicate_uri_mlp2.weight
primals_17 = self.predicate_uri_mlp2.bias
primals_19 = self.join_mlp1.weight
primals_20 = self.join_mlp1.bias
primals_22 = self.join_mlp2.weight
primals_23 = self.join_mlp2.bias
primals_25 = self.out_mlp1.weight
primals_26 = self.out_mlp1.bias
primals_27 = self.out_mlp2.weight
primals_28 = self.out_mlp2.bias
primals_3 = input_0
primals_6 = input_1
primals_9 = input_2
primals_12 = input_3
primals_15 = input_4
primals_18 = input_5
primals_21 = input_6
primals_24 = input_7
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
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])
return output[0]
|
dacasals/learnedcardinalities
|
SetConv
| false
| 1,791
|
[
"MIT"
] | 0
|
ee9741ce1a7b55ed18c33fbd6047484e50068037
|
https://github.com/dacasals/learnedcardinalities/tree/ee9741ce1a7b55ed18c33fbd6047484e50068037
|
SoftArgmax2D
|
import torch
import torch.nn as nn
from typing import Optional
def create_meshgrid(x: 'torch.Tensor', normalized_coordinates: 'Optional[bool]'
) ->torch.Tensor:
assert len(x.shape) == 4, x.shape
_, _, height, width = x.shape
_device, _dtype = x.device, x.dtype
if normalized_coordinates:
xs = torch.linspace(-1.0, 1.0, width, device=_device, dtype=_dtype)
ys = torch.linspace(-1.0, 1.0, height, device=_device, dtype=_dtype)
else:
xs = torch.linspace(0, width - 1, width, device=_device, dtype=_dtype)
ys = torch.linspace(0, height - 1, height, device=_device, dtype=_dtype
)
return torch.meshgrid(ys, xs)
class SoftArgmax2D(nn.Module):
"""Creates a module that computes the Spatial Soft-Argmax 2D
of a given input heatmap.
Returns the index of the maximum 2d coordinates of the give map.
The output order is x-coord and y-coord.
Arguments:
normalized_coordinates (Optional[bool]): wether to return the
coordinates normalized in the range of [-1, 1]. Otherwise,
it will return the coordinates in the range of the input shape.
Default is True.
Shape:
- Input: :math:`(B, N, H, W)`
- Output: :math:`(B, N, 2)`
Examples::
>>> input = torch.rand(1, 4, 2, 3)
>>> m = tgm.losses.SpatialSoftArgmax2d()
>>> coords = m(input) # 1x4x2
>>> x_coord, y_coord = torch.chunk(coords, dim=-1, chunks=2)
"""
def __init__(self, normalized_coordinates: 'Optional[bool]'=True) ->None:
super(SoftArgmax2D, self).__init__()
self.normalized_coordinates: 'Optional[bool]' = normalized_coordinates
self.eps: 'float' = 1e-06
def forward(self, input: 'torch.Tensor') ->torch.Tensor:
if not torch.is_tensor(input):
raise TypeError('Input input type is not a torch.Tensor. Got {}'
.format(type(input)))
if not len(input.shape) == 4:
raise ValueError('Invalid input shape, we expect BxCxHxW. Got: {}'
.format(input.shape))
batch_size, channels, _height, _width = input.shape
x: 'torch.Tensor' = input.view(batch_size, channels, -1)
exp_x = torch.exp(x - torch.max(x, dim=-1, keepdim=True)[0])
exp_x_sum = 1.0 / (exp_x.sum(dim=-1, keepdim=True) + self.eps)
pos_y, pos_x = create_meshgrid(input, self.normalized_coordinates)
pos_x = pos_x.reshape(-1)
pos_y = pos_y.reshape(-1)
expected_y: 'torch.Tensor' = torch.sum(pos_y * exp_x * exp_x_sum,
dim=-1, keepdim=True)
expected_x: 'torch.Tensor' = torch.sum(pos_x * exp_x * exp_x_sum,
dim=-1, keepdim=True)
output: 'torch.Tensor' = torch.cat([expected_x, expected_y], dim=-1)
return output.view(batch_size, channels, 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._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
from typing import Optional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0(in_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])
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 = r1 % 4
tmp12 = tmp11.to(tl.float32)
tmp13 = 2.0
tmp14 = tmp12 < tmp13
tmp15 = 0.6666666666666666
tmp16 = tmp12 * tmp15
tmp17 = -1.0
tmp18 = tmp16 + tmp17
tmp19 = 3 + -1 * (r1 % 4)
tmp20 = tmp19.to(tl.float32)
tmp21 = tmp20 * tmp15
tmp22 = 1.0
tmp23 = tmp22 - tmp21
tmp24 = tl.where(tmp14, tmp18, tmp23)
tmp25 = tmp24 * tmp6
tmp26 = 1e-06
tmp27 = tmp10 + tmp26
tmp28 = tl.full([1, 1], 1, tl.int32)
tmp29 = tmp28 / tmp27
tmp30 = tmp29 * tmp22
tmp31 = tmp25 * tmp30
tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
tmp34 = tl.where(xmask, tmp32, 0)
tmp35 = tl.sum(tmp34, 1)[:, None]
tmp36 = r1 // 4
tmp37 = tmp36.to(tl.float32)
tmp38 = tmp37 < tmp13
tmp39 = tmp37 * tmp15
tmp40 = tmp39 + tmp17
tmp41 = 3 + -1 * (r1 // 4)
tmp42 = tmp41.to(tl.float32)
tmp43 = tmp42 * tmp15
tmp44 = tmp22 - tmp43
tmp45 = tl.where(tmp38, tmp40, tmp44)
tmp46 = tmp45 * tmp6
tmp47 = tmp46 * tmp30
tmp48 = tl.broadcast_to(tmp47, [XBLOCK, RBLOCK])
tmp50 = tl.where(xmask, tmp48, 0)
tmp51 = tl.sum(tmp50, 1)[:, None]
tl.store(out_ptr2 + 2 * x0, tmp35, xmask)
tl.store(out_ptr3 + 2 * x0, tmp51, 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)
buf5 = empty_strided_cuda((4, 4, 2), (8, 2, 1), torch.float32)
buf3 = reinterpret_tensor(buf5, (4, 4, 1), (8, 2, 1), 0)
buf4 = reinterpret_tensor(buf5, (4, 4, 1), (8, 2, 1), 1)
get_raw_stream(0)
triton_per_fused_add_exp_max_mul_reciprocal_sub_sum_0[grid(16)](arg0_1,
buf3, buf4, 16, 16, XBLOCK=8, num_warps=2, num_stages=1)
del arg0_1
return buf5,
def create_meshgrid(x: 'torch.Tensor', normalized_coordinates: 'Optional[bool]'
) ->torch.Tensor:
assert len(x.shape) == 4, x.shape
_, _, height, width = x.shape
_device, _dtype = x.device, x.dtype
if normalized_coordinates:
xs = torch.linspace(-1.0, 1.0, width, device=_device, dtype=_dtype)
ys = torch.linspace(-1.0, 1.0, height, device=_device, dtype=_dtype)
else:
xs = torch.linspace(0, width - 1, width, device=_device, dtype=_dtype)
ys = torch.linspace(0, height - 1, height, device=_device, dtype=_dtype
)
return torch.meshgrid(ys, xs)
class SoftArgmax2DNew(nn.Module):
"""Creates a module that computes the Spatial Soft-Argmax 2D
of a given input heatmap.
Returns the index of the maximum 2d coordinates of the give map.
The output order is x-coord and y-coord.
Arguments:
normalized_coordinates (Optional[bool]): wether to return the
coordinates normalized in the range of [-1, 1]. Otherwise,
it will return the coordinates in the range of the input shape.
Default is True.
Shape:
- Input: :math:`(B, N, H, W)`
- Output: :math:`(B, N, 2)`
Examples::
>>> input = torch.rand(1, 4, 2, 3)
>>> m = tgm.losses.SpatialSoftArgmax2d()
>>> coords = m(input) # 1x4x2
>>> x_coord, y_coord = torch.chunk(coords, dim=-1, chunks=2)
"""
def __init__(self, normalized_coordinates: 'Optional[bool]'=True) ->None:
super(SoftArgmax2DNew, self).__init__()
self.normalized_coordinates: 'Optional[bool]' = normalized_coordinates
self.eps: 'float' = 1e-06
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
danyayay/ynet_adaptive
|
SoftArgmax2D
| false
| 1,792
|
[
"MIT"
] | 0
|
f1daea6f3d5ec8a7349c2ee72bf742df83786103
|
https://github.com/danyayay/ynet_adaptive/tree/f1daea6f3d5ec8a7349c2ee72bf742df83786103
|
FilterNorm
|
import torch
import torch.nn as nn
from torch.nn.init import calculate_gain
class FilterNorm(nn.Module):
def __init__(self, in_channels, kernel_size, filter_type, nonlinearity=
'linear', running_std=False, running_mean=False):
assert filter_type in ('spatial', 'channel')
assert in_channels >= 1
super(FilterNorm, self).__init__()
self.in_channels = in_channels
self.filter_type = filter_type
self.runing_std = running_std
self.runing_mean = running_mean
std = calculate_gain(nonlinearity) / kernel_size
if running_std:
self.std = nn.Parameter(torch.randn(in_channels * kernel_size **
2) * std, requires_grad=True)
else:
self.std = std
if running_mean:
self.mean = nn.Parameter(torch.randn(in_channels * kernel_size **
2), requires_grad=True)
def forward(self, x):
if self.filter_type == 'spatial':
b, _, h, w = x.size()
x = x.reshape(b, self.in_channels, -1, h, w)
x = x - x.mean(dim=2).reshape(b, self.in_channels, 1, h, w)
x = x / (x.std(dim=2).reshape(b, self.in_channels, 1, h, w) + 1e-10
)
x = x.reshape(b, _, h, w)
if self.runing_std:
x = x * self.std[None, :, None, None]
else:
x = x * self.std
if self.runing_mean:
x = x + self.mean[None, :, None, None]
elif self.filter_type == 'channel':
b = x.size(0)
c = self.in_channels
x = x.reshape(b, c, -1)
x = x - x.mean(dim=2).reshape(b, c, 1)
x = x / (x.std(dim=2).reshape(b, c, 1) + 1e-10)
x = x.reshape(b, -1)
if self.runing_std:
x = x * self.std[None, :]
else:
x = x * self.std
if self.runing_mean:
x = x + self.mean[None, :]
else:
raise RuntimeError('Unsupported filter type {}'.format(self.
filter_type))
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'kernel_size': 4, 'filter_type': 'spatial'}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn.init import calculate_gain
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 = 1.0
tmp2 = tmp0 / tmp1
tmp3 = tmp0 - tmp2
tmp4 = tmp3 / tmp1
tmp5 = tmp3 - tmp4
tmp6 = tmp5 * tmp5
tmp7 = 0.0
tmp8 = tmp6 / tmp7
tmp9 = libdevice.sqrt(tmp8)
tmp10 = 1e-10
tmp11 = tmp9 + tmp10
tmp12 = tmp3 / tmp11
tmp13 = 0.25
tmp14 = tmp12 * tmp13
tl.store(out_ptr0 + x0, tmp14, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class FilterNormNew(nn.Module):
def __init__(self, in_channels, kernel_size, filter_type, nonlinearity=
'linear', running_std=False, running_mean=False):
assert filter_type in ('spatial', 'channel')
assert in_channels >= 1
super(FilterNormNew, self).__init__()
self.in_channels = in_channels
self.filter_type = filter_type
self.runing_std = running_std
self.runing_mean = running_mean
std = calculate_gain(nonlinearity) / kernel_size
if running_std:
self.std = nn.Parameter(torch.randn(in_channels * kernel_size **
2) * std, requires_grad=True)
else:
self.std = std
if running_mean:
self.mean = nn.Parameter(torch.randn(in_channels * kernel_size **
2), requires_grad=True)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
danyayay/ynet_adaptive
|
FilterNorm
| false
| 1,793
|
[
"MIT"
] | 0
|
f1daea6f3d5ec8a7349c2ee72bf742df83786103
|
https://github.com/danyayay/ynet_adaptive/tree/f1daea6f3d5ec8a7349c2ee72bf742df83786103
|
TorchFocalLoss
|
import torch
import torch.nn.functional as F
from torch import nn
class TorchFocalLoss(nn.Module):
"""Implementation of Focal Loss[1]_ modified from Catalyst [2]_ .
Arguments
---------
gamma : :class:`int` or :class:`float`
Focusing parameter. See [1]_ .
alpha : :class:`int` or :class:`float`
Normalization factor. See [1]_ .
References
----------
.. [1] https://arxiv.org/pdf/1708.02002.pdf
.. [2] https://catalyst-team.github.io/catalyst/
"""
def __init__(self, gamma=2, alpha=0.75):
super().__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, outputs, targets):
"""Calculate the loss function between `outputs` and `targets`.
Arguments
---------
outputs : :class:`torch.Tensor`
The output tensor from a model.
targets : :class:`torch.Tensor`
The training target.
Returns
-------
loss : :class:`torch.Variable`
The loss value.
"""
if targets.size() != outputs.size():
raise ValueError(
f'Targets and inputs must be same size. Got ({targets.size()}) and ({outputs.size()})'
)
max_val = (-outputs).clamp(min=0)
log_ = ((-max_val).exp() + (-outputs - max_val).exp()).log()
loss = outputs - outputs * targets + max_val + log_
invprobs = F.logsigmoid(-outputs * (targets * 2.0 - 1.0))
loss = self.alpha * (invprobs * self.gamma).exp() * loss
return loss.sum(dim=-1).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 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_add_clamp_exp_log_log_sigmoid_forward_mul_neg_sub_0(
in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp1 = -tmp0
tmp3 = 2.0
tmp4 = tmp2 * tmp3
tmp5 = 1.0
tmp6 = tmp4 - tmp5
tmp7 = tmp1 * tmp6
tmp8 = 0.0
tmp9 = triton_helpers.minimum(tmp8, tmp7)
tmp10 = tl_math.abs(tmp7)
tmp11 = -tmp10
tmp12 = tl_math.exp(tmp11)
tmp13 = libdevice.log1p(tmp12)
tmp14 = tmp9 - tmp13
tmp15 = tmp14 * tmp3
tmp16 = tl_math.exp(tmp15)
tmp17 = 0.75
tmp18 = tmp16 * tmp17
tmp19 = tmp0 * tmp2
tmp20 = tmp0 - tmp19
tmp21 = triton_helpers.maximum(tmp1, tmp8)
tmp22 = tmp20 + tmp21
tmp23 = -tmp21
tmp24 = tl_math.exp(tmp23)
tmp25 = tmp1 - tmp21
tmp26 = tl_math.exp(tmp25)
tmp27 = tmp24 + tmp26
tmp28 = tl_math.log(tmp27)
tmp29 = tmp22 + tmp28
tmp30 = tmp18 * tmp29
tl.store(out_ptr0 + x0, tmp30, xmask)
@triton.jit
def triton_per_fused_mean_sum_1(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.sum(tmp7, 1)[:, None]
tmp10 = 64.0
tmp11 = tmp9 / tmp10
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp11, 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_add_clamp_exp_log_log_sigmoid_forward_mul_neg_sub_0[
grid(256)](arg1_1, arg0_1, buf0, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused_mean_sum_1[grid(1)](buf2, buf0, 1, 64, XBLOCK=1,
num_warps=2, num_stages=1)
del buf0
return buf2,
class TorchFocalLossNew(nn.Module):
"""Implementation of Focal Loss[1]_ modified from Catalyst [2]_ .
Arguments
---------
gamma : :class:`int` or :class:`float`
Focusing parameter. See [1]_ .
alpha : :class:`int` or :class:`float`
Normalization factor. See [1]_ .
References
----------
.. [1] https://arxiv.org/pdf/1708.02002.pdf
.. [2] https://catalyst-team.github.io/catalyst/
"""
def __init__(self, gamma=2, alpha=0.75):
super().__init__()
self.gamma = gamma
self.alpha = alpha
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dannyjeck-matroid/solaris
|
TorchFocalLoss
| false
| 1,794
|
[
"Apache-2.0"
] | 0
|
463d220c1fe14f811cbbbf528a7353022538006e
|
https://github.com/dannyjeck-matroid/solaris/tree/463d220c1fe14f811cbbbf528a7353022538006e
|
Cauchy
|
import torch
import torch.nn as nn
import torch.utils.model_zoo
class Cauchy(nn.Module):
def __init__(self):
super(Cauchy, self).__init__()
self.c = 1.0
def forward(self, X, Y):
r = torch.add(X, -Y)
ra = torch.abs(r)
error = 0.5 * self.c ** 2 * torch.log(1 + (ra / self.c) ** 2)
loss = torch.sum(error)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.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_per_fused_abs_add_div_log_mul_neg_pow_sum_0(in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = -tmp1
tmp3 = tmp0 + tmp2
tmp4 = tl_math.abs(tmp3)
tmp5 = 1.0
tmp6 = tmp4 * tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp7 + tmp5
tmp9 = tl_math.log(tmp8)
tmp10 = 0.5
tmp11 = tmp9 * tmp10
tmp12 = tl.broadcast_to(tmp11, [RBLOCK])
tmp14 = triton_helpers.promote_to_tensor(tl.sum(tmp12, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_abs_add_div_log_mul_neg_pow_sum_0[grid(1)](arg1_1,
arg0_1, buf0, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class CauchyNew(nn.Module):
def __init__(self):
super(CauchyNew, self).__init__()
self.c = 1.0
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
davefiorino/EDSR-PyTorch
|
Cauchy
| false
| 1,795
|
[
"MIT"
] | 0
|
97ad32a09a71816a36c45d92cdb2ea7ab42ba685
|
https://github.com/davefiorino/EDSR-PyTorch/tree/97ad32a09a71816a36c45d92cdb2ea7ab42ba685
|
Fair
|
import torch
import torch.nn as nn
import torch.utils.model_zoo
class Fair(nn.Module):
def __init__(self):
super(Fair, self).__init__()
self.c = 1.0
def forward(self, X, Y):
r = torch.add(X, -Y)
ra = torch.abs(r)
error = self.c ** 2 * (ra / self.c - torch.log(1 + ra / self.c))
loss = torch.sum(error)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.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_per_fused_abs_add_div_log_mul_neg_sub_sum_0(in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = -tmp1
tmp3 = tmp0 + tmp2
tmp4 = tl_math.abs(tmp3)
tmp5 = 1.0
tmp6 = tmp4 * tmp5
tmp7 = tmp6 + tmp5
tmp8 = tl_math.log(tmp7)
tmp9 = tmp6 - tmp8
tmp10 = tmp9 * tmp5
tmp11 = tl.broadcast_to(tmp10, [RBLOCK])
tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_abs_add_div_log_mul_neg_sub_sum_0[grid(1)](arg1_1,
arg0_1, buf0, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class FairNew(nn.Module):
def __init__(self):
super(FairNew, self).__init__()
self.c = 1.0
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
davefiorino/EDSR-PyTorch
|
Fair
| false
| 1,796
|
[
"MIT"
] | 0
|
97ad32a09a71816a36c45d92cdb2ea7ab42ba685
|
https://github.com/davefiorino/EDSR-PyTorch/tree/97ad32a09a71816a36c45d92cdb2ea7ab42ba685
|
Charbonnier
|
import torch
import torch.nn as nn
import torch.utils.model_zoo
class Charbonnier(nn.Module):
def __init__(self):
super(Charbonnier, self).__init__()
self.eps = 1e-06
def forward(self, X, Y):
diff = torch.add(X, -Y)
error = torch.sqrt(diff * diff + self.eps)
loss = torch.sum(error)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.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_per_fused_add_mul_neg_sqrt_sum_0(in_ptr0, in_ptr1, out_ptr0,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = -tmp1
tmp3 = tmp0 + tmp2
tmp4 = tmp3 * tmp3
tmp5 = 1e-06
tmp6 = tmp4 + tmp5
tmp7 = libdevice.sqrt(tmp6)
tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp10, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_add_mul_neg_sqrt_sum_0[grid(1)](arg1_1, arg0_1,
buf0, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class CharbonnierNew(nn.Module):
def __init__(self):
super(CharbonnierNew, self).__init__()
self.eps = 1e-06
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
davefiorino/EDSR-PyTorch
|
Charbonnier
| false
| 1,797
|
[
"MIT"
] | 0
|
97ad32a09a71816a36c45d92cdb2ea7ab42ba685
|
https://github.com/davefiorino/EDSR-PyTorch/tree/97ad32a09a71816a36c45d92cdb2ea7ab42ba685
|
Classifier
|
import torch
import torch.distributed
import torch
import torch.nn as nn
class Classifier(nn.Module):
def __init__(self, hidden_size):
super(Classifier, self).__init__()
self.linear1 = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x, mask_cls):
h = self.linear1(x).squeeze(-1)
sent_scores = self.sigmoid(h) * mask_cls.float()
return sent_scores
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.distributed
import torch
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_sigmoid_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 % 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr1 + x2, xmask)
tmp1 = tl.sigmoid(tmp0)
tmp3 = tmp1 * tmp2
tl.store(out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1, 4), (4, 1))
assert_size_stride(primals_2, (1,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 1), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_1
del primals_2
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_sigmoid_0[grid(256)](buf1, primals_4, buf2,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf2, primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1
class ClassifierNew(nn.Module):
def __init__(self, hidden_size):
super(ClassifierNew, self).__init__()
self.linear1 = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0, input_1):
primals_1 = self.linear1.weight
primals_2 = self.linear1.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
dat821168/PreSumm
|
Classifier
| false
| 1,798
|
[
"MIT"
] | 0
|
3c84fc97f50a193a865ccef2300adf5683397539
|
https://github.com/dat821168/PreSumm/tree/3c84fc97f50a193a865ccef2300adf5683397539
|
CustomBatchNormManualModule
|
import torch
import torch.nn as nn
class CustomBatchNormManualFunction(torch.autograd.Function):
"""
This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs.
Using torch.autograd.Function allows you to write a custom backward function.
The function will be called from the nn.Module CustomBatchNormManualModule
Inside forward the tensors are (automatically) not recorded for automatic differentiation since the backward
pass is done via the backward method.
The forward pass is not called directly but via the apply() method. This makes sure that the context objects
are dealt with correctly. Example:
my_bn_fct = CustomBatchNormManualFunction()
normalized = fct.apply(input, gamma, beta, eps)
"""
@staticmethod
def forward(ctx, input, gamma, beta, eps=1e-05):
"""
Compute the batch normalization
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
input: input tensor of shape (n_batch, n_neurons)
gamma: variance scaling tensor, applied per neuron, shpae (n_neurons)
beta: mean bias tensor, applied per neuron, shpae (n_neurons)
eps: small float added to the variance for stability
Returns:
out: batch-normalized tensor
TODO:
Implement the forward pass of batch normalization
Store constant non-tensor objects via ctx.constant=myconstant
Store tensors which you need in the backward pass via ctx.save_for_backward(tensor1, tensor2, ...)
Intermediate results can be decided to be either recomputed in the backward pass or to be stored
for the backward pass. Do not store tensors which are unnecessary for the backward pass to save memory!
For the case that you make use of torch.var be aware that the flag unbiased=False should be set.
"""
x = input
mu = x.mean(dim=0)
std = x.std(dim=0, unbiased=False)
var = torch.sqrt(std * std + eps)
x_centered = x - mu
x_hat = x_centered / var
out = gamma * x_hat + beta
ctx.save_for_backward(x, mu, std, var, gamma)
return out
@staticmethod
def backward(ctx, grad_output):
"""
Compute backward pass of the batch normalization.
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
Returns:
out: tuple containing gradients for all input arguments
TODO:
Retrieve saved tensors and constants via ctx.saved_tensors and ctx.constant
Compute gradients for inputs where ctx.needs_input_grad[idx] is True. Set gradients for other
inputs to None. This should be decided dynamically.
"""
x, mu, _std, var, gamma = ctx.saved_tensors
grad_input, grad_gamma, grad_beta = None, None, None
x_hat = (x - mu) / var
if ctx.needs_input_grad[2]:
grad_beta = grad_output.sum(0)
if ctx.needs_input_grad[1]:
grad_gamma = (grad_output * x_hat).sum(0)
if ctx.needs_input_grad[0]:
c1 = grad_output.mean(dim=0)
c2 = (grad_output * x_hat).mean(dim=0)
grad_input = gamma / var * (grad_output - c1 - x_hat * c2)
return grad_input, grad_gamma, grad_beta, None
class CustomBatchNormManualModule(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
In self.forward the functional version CustomBatchNormManualFunction.forward is called.
The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormManualModule object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormManualModule, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.gammas = torch.nn.Parameter(torch.ones(n_neurons))
self.betas = torch.nn.Parameter(torch.zeros(n_neurons))
def forward(self, input):
"""
Compute the batch normalization via CustomBatchNormManualFunction
Args:
input: input tensor of shape (n_batch, n_neurons)
Returns:
out: batch-normalized tensor
TODO:
Check for the correctness of the shape of the input tensor.
Instantiate a CustomBatchNormManualFunction.
Call it via its .apply() method.
"""
shape = input.size()
if len(shape) == 1:
input.view(1, -1)
shape = input.size()
if len(shape) > 2:
raise ValueError('Expected 1-D or 2-D tensor (got {})'.format(
str(shape)))
elif input.shape[1] != self.n_neurons:
raise ValueError('Expected _ x {} tensor (got {} x {})'.format(
str(self.n_neurons), str(shape[0]), str(shape[1])))
fct = CustomBatchNormManualFunction()
out = fct.apply(input, self.gammas, self.betas, self.eps)
return out
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'n_neurons': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mean_mul_sqrt_std_sub_0(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
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp31 = 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 = tmp2 - tmp10
tmp13 = tmp12 * tmp12
tmp14 = tmp3 - tmp10
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp10
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp7 - tmp10
tmp21 = tmp20 * tmp20
tmp22 = tmp19 + tmp21
tmp23 = tmp22 / tmp9
tmp24 = libdevice.sqrt(tmp23)
tmp25 = tmp24 * tmp24
tmp26 = 1e-05
tmp27 = tmp25 + tmp26
tmp28 = libdevice.sqrt(tmp27)
tmp29 = tmp11 / tmp28
tmp30 = tmp0 * tmp29
tmp32 = tmp30 + tmp31
tl.store(in_out_ptr0 + x2, tmp32, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_div_mean_mul_sqrt_std_sub_0[grid(16)](buf1,
primals_2, primals_1, primals_3, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_2
del primals_3
return buf1, primals_1
class CustomBatchNormManualFunction(torch.autograd.Function):
"""
This torch.autograd.Function implements a functional custom version of the batch norm operation for MLPs.
Using torch.autograd.Function allows you to write a custom backward function.
The function will be called from the nn.Module CustomBatchNormManualModule
Inside forward the tensors are (automatically) not recorded for automatic differentiation since the backward
pass is done via the backward method.
The forward pass is not called directly but via the apply() method. This makes sure that the context objects
are dealt with correctly. Example:
my_bn_fct = CustomBatchNormManualFunction()
normalized = fct.apply(input, gamma, beta, eps)
"""
@staticmethod
def forward(ctx, input, gamma, beta, eps=1e-05):
"""
Compute the batch normalization
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
input: input tensor of shape (n_batch, n_neurons)
gamma: variance scaling tensor, applied per neuron, shpae (n_neurons)
beta: mean bias tensor, applied per neuron, shpae (n_neurons)
eps: small float added to the variance for stability
Returns:
out: batch-normalized tensor
TODO:
Implement the forward pass of batch normalization
Store constant non-tensor objects via ctx.constant=myconstant
Store tensors which you need in the backward pass via ctx.save_for_backward(tensor1, tensor2, ...)
Intermediate results can be decided to be either recomputed in the backward pass or to be stored
for the backward pass. Do not store tensors which are unnecessary for the backward pass to save memory!
For the case that you make use of torch.var be aware that the flag unbiased=False should be set.
"""
x = input
mu = x.mean(dim=0)
std = x.std(dim=0, unbiased=False)
var = torch.sqrt(std * std + eps)
x_centered = x - mu
x_hat = x_centered / var
out = gamma * x_hat + beta
ctx.save_for_backward(x, mu, std, var, gamma)
return out
@staticmethod
def backward(ctx, grad_output):
"""
Compute backward pass of the batch normalization.
Args:
ctx: context object handling storing and retrival of tensors and constants and specifying
whether tensors need gradients in backward pass
Returns:
out: tuple containing gradients for all input arguments
TODO:
Retrieve saved tensors and constants via ctx.saved_tensors and ctx.constant
Compute gradients for inputs where ctx.needs_input_grad[idx] is True. Set gradients for other
inputs to None. This should be decided dynamically.
"""
x, mu, _std, var, gamma = ctx.saved_tensors
grad_input, grad_gamma, grad_beta = None, None, None
x_hat = (x - mu) / var
if ctx.needs_input_grad[2]:
grad_beta = grad_output.sum(0)
if ctx.needs_input_grad[1]:
grad_gamma = (grad_output * x_hat).sum(0)
if ctx.needs_input_grad[0]:
c1 = grad_output.mean(dim=0)
c2 = (grad_output * x_hat).mean(dim=0)
grad_input = gamma / var * (grad_output - c1 - x_hat * c2)
return grad_input, grad_gamma, grad_beta, None
class CustomBatchNormManualModuleNew(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
In self.forward the functional version CustomBatchNormManualFunction.forward is called.
The automatic differentiation of PyTorch calls the backward method of this function in the backward pass.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormManualModule object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormManualModuleNew, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.gammas = torch.nn.Parameter(torch.ones(n_neurons))
self.betas = torch.nn.Parameter(torch.zeros(n_neurons))
def forward(self, input_0):
primals_2 = self.gammas
primals_3 = self.betas
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
davide-belli/deep-learning-labs
|
CustomBatchNormManualModule
| false
| 1,799
|
[
"MIT"
] | 0
|
1acd37a527711dccdc00c1935724cc5de7c10955
|
https://github.com/davide-belli/deep-learning-labs/tree/1acd37a527711dccdc00c1935724cc5de7c10955
|
Discriminator
|
import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.linear1 = nn.Linear(784, 512)
self.lrelu2 = nn.LeakyReLU(0.2)
self.linear2 = nn.Linear(512, 256)
self.lrelu3 = nn.LeakyReLU(0.2)
self.linear3 = nn.Linear(256, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, img):
out = self.linear1(img.view(img.shape[0], 784))
out = self.linear2(self.lrelu2(out))
out = self.linear3(self.lrelu3(out))
out = self.sigmoid(out)
return out
def get_inputs():
return [torch.rand([4, 784])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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):
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_1(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_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 784), (784, 1))
assert_size_stride(primals_2, (512, 784), (784, 1))
assert_size_stride(primals_3, (512,), (1,))
assert_size_stride(primals_4, (256, 512), (512, 1))
assert_size_stride(primals_5, (256,), (1,))
assert_size_stride(primals_6, (1, 256), (256, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (784,
512), (1, 784), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 512), (512, 1), torch.bool)
buf2 = empty_strided_cuda((4, 512), (512, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(2048)](buf0, primals_3, buf1,
buf2, 2048, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_3
buf3 = empty_strided_cuda((4, 256), (256, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (512, 256), (
1, 512), 0), out=buf3)
buf4 = empty_strided_cuda((4, 256), (256, 1), torch.bool)
buf5 = empty_strided_cuda((4, 256), (256, 1), torch.float32)
triton_poi_fused_leaky_relu_1[grid(1024)](buf3, primals_5, buf4,
buf5, 1024, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
del primals_5
buf6 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf5, reinterpret_tensor(primals_6, (256, 1), (1,
256), 0), out=buf6)
buf7 = buf6
del buf6
triton_poi_fused_sigmoid_2[grid(4)](buf7, primals_7, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_7
return buf7, primals_1, buf1, buf2, buf4, buf5, buf7, primals_6, primals_4
class DiscriminatorNew(nn.Module):
def __init__(self):
super(DiscriminatorNew, self).__init__()
self.linear1 = nn.Linear(784, 512)
self.lrelu2 = nn.LeakyReLU(0.2)
self.linear2 = nn.Linear(512, 256)
self.lrelu3 = nn.LeakyReLU(0.2)
self.linear3 = nn.Linear(256, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input_0):
primals_2 = self.linear1.weight
primals_3 = self.linear1.bias
primals_4 = self.linear2.weight
primals_5 = self.linear2.bias
primals_6 = self.linear3.weight
primals_7 = self.linear3.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
davide-belli/deep-learning-labs
|
Discriminator
| false
| 1,800
|
[
"MIT"
] | 0
|
1acd37a527711dccdc00c1935724cc5de7c10955
|
https://github.com/davide-belli/deep-learning-labs/tree/1acd37a527711dccdc00c1935724cc5de7c10955
|
ConcatPool2d
|
import torch
import torch.nn as nn
class ConcatPool2d(nn.Module):
"""Layer that concats `AvgPool2d` and `MaxPool2d`"""
def __init__(self, ks, stride=None, padding=0):
super().__init__()
self.ap = nn.AvgPool2d(ks, stride, padding)
self.mp = nn.MaxPool2d(ks, stride, padding)
def forward(self, x):
return torch.cat([self.mp(x), self.ap(x)], 1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'ks': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_avg_pool2d_max_pool2d_with_indices_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
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + 16 * x2, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp7 = tl.load(in_ptr0 + (4 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (5 + 16 * x2), xmask, eviction_policy='evict_last'
)
tmp11 = tl.load(in_ptr0 + (6 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr0 + (7 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp15 = tl.load(in_ptr0 + (8 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp17 = tl.load(in_ptr0 + (9 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (10 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (11 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (12 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp25 = tl.load(in_ptr0 + (13 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (14 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp29 = tl.load(in_ptr0 + (15 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp10 = triton_helpers.maximum(tmp9, tmp8)
tmp12 = triton_helpers.maximum(tmp11, tmp10)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp16 = triton_helpers.maximum(tmp15, tmp14)
tmp18 = triton_helpers.maximum(tmp17, tmp16)
tmp20 = triton_helpers.maximum(tmp19, tmp18)
tmp22 = triton_helpers.maximum(tmp21, tmp20)
tmp24 = triton_helpers.maximum(tmp23, tmp22)
tmp26 = triton_helpers.maximum(tmp25, tmp24)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp30 = triton_helpers.maximum(tmp29, tmp28)
tmp31 = tmp1 + tmp0
tmp32 = tmp3 + tmp31
tmp33 = tmp5 + tmp32
tmp34 = tmp7 + tmp33
tmp35 = tmp9 + tmp34
tmp36 = tmp11 + tmp35
tmp37 = tmp13 + tmp36
tmp38 = tmp15 + tmp37
tmp39 = tmp17 + tmp38
tmp40 = tmp19 + tmp39
tmp41 = tmp21 + tmp40
tmp42 = tmp23 + tmp41
tmp43 = tmp25 + tmp42
tmp44 = tmp27 + tmp43
tmp45 = tmp29 + tmp44
tmp46 = 0.0625
tmp47 = tmp45 * tmp46
tl.store(out_ptr0 + (x0 + 8 * x1), tmp30, xmask)
tl.store(out_ptr1 + (x0 + 8 * x1), tmp47, 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)
buf2 = empty_strided_cuda((4, 8, 1, 1), (8, 1, 1, 1), torch.float32)
buf0 = reinterpret_tensor(buf2, (4, 4, 1, 1), (8, 1, 1, 1), 0)
buf1 = reinterpret_tensor(buf2, (4, 4, 1, 1), (8, 1, 1, 1), 4)
get_raw_stream(0)
triton_poi_fused_avg_pool2d_max_pool2d_with_indices_0[grid(16)](arg0_1,
buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
return buf2,
class ConcatPool2dNew(nn.Module):
"""Layer that concats `AvgPool2d` and `MaxPool2d`"""
def __init__(self, ks, stride=None, padding=0):
super().__init__()
self.ap = nn.AvgPool2d(ks, stride, padding)
self.mp = nn.MaxPool2d(ks, stride, padding)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
davidleonfdez/face2anime
|
ConcatPool2d
| false
| 1,801
|
[
"MIT"
] | 0
|
896bf85a7aa28322cc9e9e586685db8cbbf39d89
|
https://github.com/davidleonfdez/face2anime/tree/896bf85a7aa28322cc9e9e586685db8cbbf39d89
|
CustomBatchNormAutograd
|
import torch
import torch.nn as nn
class CustomBatchNormAutograd(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
The operations called in self.forward track the history if the input tensors have the
flag requires_grad set to True. The backward pass does not need to be implemented, it
is dealt with by the automatic differentiation provided by PyTorch.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormAutograd object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormAutograd, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.gammas = torch.nn.Parameter(torch.ones(n_neurons))
self.betas = torch.nn.Parameter(torch.zeros(n_neurons))
def forward(self, input):
"""
Compute the batch normalization
Args:
input: input tensor of shape (n_batch, n_neurons)
Returns:
out: batch-normalized tensor
TODO:
Check for the correctness of the shape of the input tensor.
Implement batch normalization forward pass as given in the assignment.
For the case that you make use of torch.var be aware that the flag unbiased=False should be set.
"""
shape = input.size()
if len(shape) == 1:
input.view(1, -1)
shape = input.size()
if len(shape) > 2:
raise ValueError('Expected 1-D or 2-D tensor (got {})'.format(
str(shape)))
elif input.shape[1] != self.n_neurons:
raise ValueError('Expected _ x {} tensor (got {} x {})'.format(
str(self.n_neurons), str(shape[0]), str(shape[1])))
x = input
mu = x.mean(dim=0)
std = x.std(dim=0)
x_hat = (x - mu) / torch.sqrt(std * std + self.eps)
out = self.gammas * x_hat + self.betas
return out
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'n_neurons': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mean_mul_sqrt_std_sub_0(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
x0 = xindex % 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (12 + x0), xmask, eviction_policy='evict_last')
tmp32 = 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 = tmp2 - tmp10
tmp13 = tmp12 * tmp12
tmp14 = tmp3 - tmp10
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp10
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp7 - tmp10
tmp21 = tmp20 * tmp20
tmp22 = tmp19 + tmp21
tmp23 = 3.0
tmp24 = tmp22 / tmp23
tmp25 = libdevice.sqrt(tmp24)
tmp26 = tmp25 * tmp25
tmp27 = 1e-05
tmp28 = tmp26 + tmp27
tmp29 = libdevice.sqrt(tmp28)
tmp30 = tmp11 / tmp29
tmp31 = tmp0 * tmp30
tmp33 = tmp31 + tmp32
tl.store(in_out_ptr0 + x2, tmp33, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_add_div_mean_mul_sqrt_std_sub_0[grid(16)](buf1,
primals_2, primals_1, primals_3, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_2
del primals_3
return buf1, primals_1
class CustomBatchNormAutogradNew(nn.Module):
"""
This nn.module implements a custom version of the batch norm operation for MLPs.
The operations called in self.forward track the history if the input tensors have the
flag requires_grad set to True. The backward pass does not need to be implemented, it
is dealt with by the automatic differentiation provided by PyTorch.
"""
def __init__(self, n_neurons, eps=1e-05):
"""
Initializes CustomBatchNormAutograd object.
Args:
n_neurons: int specifying the number of neurons
eps: small float to be added to the variance for stability
TODO:
Save parameters for the number of neurons and eps.
Initialize parameters gamma and beta via nn.Parameter
"""
super(CustomBatchNormAutogradNew, self).__init__()
self.n_neurons = n_neurons
self.eps = eps
self.gammas = torch.nn.Parameter(torch.ones(n_neurons))
self.betas = torch.nn.Parameter(torch.zeros(n_neurons))
def forward(self, input_0):
primals_2 = self.gammas
primals_3 = self.betas
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
davide-belli/deep-learning-labs
|
CustomBatchNormAutograd
| false
| 1,802
|
[
"MIT"
] | 0
|
1acd37a527711dccdc00c1935724cc5de7c10955
|
https://github.com/davide-belli/deep-learning-labs/tree/1acd37a527711dccdc00c1935724cc5de7c10955
|
PixelWise
|
import torch
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.init
class PixelWise(torch.nn.Module):
""" Implemented - https://arxiv.org/pdf/1710.10196.pdf """
def __init__(self, eps=1e-08):
super(PixelWise, self).__init__()
self.eps = eps
def forward(self, tensor):
return tensor.div(tensor.pow(2).mean(1, True).add(self.eps).pow(0.5))
def __repr__(self):
return 'pixelwise'
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.utils.data.distributed
import torch.nn.init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_mean_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
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = 4.0
tmp13 = tmp11 / tmp12
tmp14 = 1e-08
tmp15 = tmp13 + tmp14
tmp16 = libdevice.sqrt(tmp15)
tmp17 = tmp0 / tmp16
tl.store(out_ptr0 + x3, tmp17, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_mean_pow_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class PixelWiseNew(torch.nn.Module):
""" Implemented - https://arxiv.org/pdf/1710.10196.pdf """
def __init__(self, eps=1e-08):
super(PixelWiseNew, self).__init__()
self.eps = eps
def __repr__(self):
return 'pixelwise'
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
davidwagnerkc/TensorMONK
|
PixelWise
| false
| 1,803
|
[
"MIT"
] | 0
|
3607836d3d6bfd0994e044536b2a51bc84b35f31
|
https://github.com/davidwagnerkc/TensorMONK/tree/3607836d3d6bfd0994e044536b2a51bc84b35f31
|
PositionwiseFeedForward
|
import math
import torch
import torch.distributed
import torch
import torch.nn as 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
import torch.distributed
import torch
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_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=128, 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]
|
dat821168/PreSumm
|
PositionwiseFeedForward
| false
| 1,804
|
[
"MIT"
] | 0
|
3c84fc97f50a193a865ccef2300adf5683397539
|
https://github.com/dat821168/PreSumm/tree/3c84fc97f50a193a865ccef2300adf5683397539
|
MiniBatchStdDev
|
import torch
import torch.nn as nn
class MiniBatchStdDev(nn.Module):
"""Layer that appends to every element of a batch a new ftr map containing the std of its group."""
def __init__(self, group_sz=4, unbiased_std=False):
super().__init__()
self.group_sz = group_sz
self.unbiased_std = unbiased_std
def forward(self, x):
bs, n_ch, h, w = x.shape
x_groups = x.view(-1, self.group_sz, n_ch, h, w)
stds_by_chw = x_groups.std(dim=1, unbiased=self.unbiased_std)
mean_std = stds_by_chw.mean(dim=[1, 2, 3], keepdim=True)
new_ftr_map = mean_std.unsqueeze(-1).repeat(1, self.group_sz, 1, h, w
).view(bs, 1, h, w)
return torch.cat([x, new_ftr_map], axis=1)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_cat_mean_std_0(in_ptr0, out_ptr1, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
r1 = rindex % 16
r2 = rindex // 16
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr0 + (64 + r0), None)
tmp3 = tl.load(in_ptr0 + (128 + r0), None)
tmp5 = tl.load(in_ptr0 + (192 + r0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = libdevice.sqrt(tmp20)
tmp22 = tl.broadcast_to(tmp21, [XBLOCK, RBLOCK])
tmp24 = tl.sum(tmp22, 1)[:, None]
tmp25 = 64.0
tmp26 = tmp24 / tmp25
tl.store(out_ptr1 + tl.broadcast_to(r1 + 80 * r2, [XBLOCK, RBLOCK]),
tmp26, None)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tl.store(out_ptr0 + (x0 + 80 * x1), 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)
buf3 = empty_strided_cuda((4, 5, 4, 4), (80, 16, 4, 1), torch.float32)
buf2 = reinterpret_tensor(buf3, (4, 1, 4, 4), (80, 16, 4, 1), 64)
get_raw_stream(0)
triton_per_fused_cat_mean_std_0[grid(1)](arg0_1, buf2, 1, 64,
XBLOCK=1, num_warps=2, num_stages=1)
buf1 = reinterpret_tensor(buf3, (4, 4, 4, 4), (80, 16, 4, 1), 0)
triton_poi_fused_cat_1[grid(256)](arg0_1, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf3,
class MiniBatchStdDevNew(nn.Module):
"""Layer that appends to every element of a batch a new ftr map containing the std of its group."""
def __init__(self, group_sz=4, unbiased_std=False):
super().__init__()
self.group_sz = group_sz
self.unbiased_std = unbiased_std
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
davidleonfdez/face2anime
|
MiniBatchStdDev
| false
| 1,805
|
[
"MIT"
] | 0
|
896bf85a7aa28322cc9e9e586685db8cbbf39d89
|
https://github.com/davidleonfdez/face2anime/tree/896bf85a7aa28322cc9e9e586685db8cbbf39d89
|
MultiheadAttention
|
import math
import torch
import torch as th
import torch.nn as nn
class QKVMultiheadAttention(nn.Module):
def __init__(self, n_heads: 'int', n_ctx: 'int'):
super().__init__()
self.n_heads = n_heads
self.n_ctx = n_ctx
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.n_heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.n_heads, -1)
q, k, v = th.split(qkv, attn_ch, dim=-1)
weight = th.einsum('bthc,bshc->bhts', q * scale, k * scale)
wdtype = weight.dtype
weight = th.softmax(weight.float(), dim=-1).type(wdtype)
return th.einsum('bhts,bshc->bthc', weight, v).reshape(bs, n_ctx, -1)
class MultiheadAttention(nn.Module):
def __init__(self, n_ctx, width, heads):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3)
self.c_proj = nn.Linear(width, width)
self.attention = QKVMultiheadAttention(heads, n_ctx)
def forward(self, x):
x = self.c_qkv(x)
x = self.attention(x)
x = self.c_proj(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_ctx': 4, 'width': 4, 'heads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch as th
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 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 + (1 + 3 * x2), xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (1 + 3 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_1(in_ptr0, in_ptr1, in_ptr2, 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
x4 = xindex
x0 = xindex % 4
x3 = xindex // 16
tmp0 = tl.load(in_ptr0 + 3 * x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 3 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + (x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr2 + (4 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr2 + (8 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr2 + (12 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp4 * tmp7
tmp9 = triton_helpers.maximum(tmp6, tmp8)
tmp11 = tmp4 * tmp10
tmp12 = triton_helpers.maximum(tmp9, tmp11)
tmp14 = tmp4 * tmp13
tmp15 = triton_helpers.maximum(tmp12, tmp14)
tmp16 = tmp6 - tmp15
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp8 - tmp15
tmp19 = tl_math.exp(tmp18)
tmp20 = tmp17 + tmp19
tmp21 = tmp11 - tmp15
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp20 + tmp22
tmp24 = tmp14 - tmp15
tmp25 = tl_math.exp(tmp24)
tmp26 = tmp23 + tmp25
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp15, xmask)
tl.store(out_ptr2 + x4, tmp26, xmask)
@triton.jit
def triton_poi_fused__softmax_2(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
x4 = xindex // 4
x0 = xindex % 4
x1 = xindex // 4 % 4
x3 = xindex // 64
x2 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x1 + 4 * x0 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp2 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp7 = tmp5 / tmp6
tl.store(out_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), tmp7, xmask)
@triton.jit
def triton_poi_fused_clone_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
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (2 + 3 * x1 + 12 * x0 + 48 * x2), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (2 + 3 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
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_5(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
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = 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), (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((16, 12), (12, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 12), (1, 4), 0), out=buf0)
del primals_1
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(64)](buf0, primals_2, buf2, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 1, 4, 64), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 1, 4, 64), torch.float32)
triton_poi_fused__softmax_mul_1[grid(64)](buf0, primals_2, buf2,
buf1, buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(256)](buf1, buf2, buf3, buf4, buf5,
256, XBLOCK=256, num_warps=4, num_stages=1)
buf6 = reinterpret_tensor(buf4, (4, 4, 4, 1, 1), (16, 4, 1, 1, 1), 0)
del buf4
triton_poi_fused_clone_3[grid(64)](buf0, primals_2, buf6, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf0
del primals_2
buf7 = reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 1), 0)
del buf3
extern_kernels.bmm(reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 0), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf7, buf8, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0)
del buf7
extern_kernels.mm(reinterpret_tensor(buf8, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf9)
buf10 = reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1), 0)
del buf9
triton_poi_fused_add_5[grid(64)](buf10, primals_5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
return buf10, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), reinterpret_tensor(buf1, (4, 4, 4, 1, 1), (16, 1, 4, 1, 1), 0
), reinterpret_tensor(buf2, (4, 4, 1, 4, 1), (16, 1, 1, 4, 1), 0
), buf5, reinterpret_tensor(buf8, (16, 4), (4, 1), 0
), primals_4, reinterpret_tensor(buf6, (16, 1, 4), (4, 1, 1), 0)
class QKVMultiheadAttention(nn.Module):
def __init__(self, n_heads: 'int', n_ctx: 'int'):
super().__init__()
self.n_heads = n_heads
self.n_ctx = n_ctx
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.n_heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.n_heads, -1)
q, k, v = th.split(qkv, attn_ch, dim=-1)
weight = th.einsum('bthc,bshc->bhts', q * scale, k * scale)
wdtype = weight.dtype
weight = th.softmax(weight.float(), dim=-1).type(wdtype)
return th.einsum('bhts,bshc->bthc', weight, v).reshape(bs, n_ctx, -1)
class MultiheadAttentionNew(nn.Module):
def __init__(self, n_ctx, width, heads):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3)
self.c_proj = nn.Linear(width, width)
self.attention = QKVMultiheadAttention(heads, n_ctx)
def forward(self, input_0):
primals_1 = self.c_qkv.weight
primals_2 = self.c_qkv.bias
primals_4 = self.c_proj.weight
primals_5 = self.c_proj.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
dashstander/glide-text2im
|
MultiheadAttention
| false
| 1,806
|
[
"MIT"
] | 0
|
58f03a871ee0567e27fccc40df98203e675a9b8e
|
https://github.com/dashstander/glide-text2im/tree/58f03a871ee0567e27fccc40df98203e675a9b8e
|
Q_Index
|
import torch
import torch.nn as nn
class Q_Index(nn.Module):
"""
Quality measurement between perturbated (image with applied noise) and denoised target image.
This module works only for images with a single color channel (grayscale)
"""
def __init__(self):
super().__init__()
def forward(self, input, target):
batch_size = input.shape[0]
input = input.view(batch_size, -1)
target = target.view(batch_size, -1)
input_mean = input.mean(dim=-1)
target_mean = target.mean(dim=-1)
input_var = input.var(dim=-1)
target_var = target.var(dim=-1)
mean_inp_times_tar = torch.mean(input * target, dim=-1)
covariance = mean_inp_times_tar - input_mean * target_mean
Q = 4.0 * covariance * input_mean * target_mean / ((input_var +
target_var) * (input_mean ** 2 + target_mean ** 2))
Q = Q.mean()
return Q
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_mean_mul_var_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, out_ptr3, out_ptr4, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
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.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
tmp7 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp12 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp14 = tl.where(xmask, tmp12, 0)
tmp15 = tl.sum(tmp14, 1)[:, None]
tmp16 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp17 = tmp16.to(tl.float32)
tmp18 = tmp15 / tmp17
tmp19 = tmp7 - tmp18
tmp20 = tmp19 * tmp19
tmp21 = tl.broadcast_to(tmp20, [XBLOCK, RBLOCK])
tmp23 = tl.where(xmask, tmp21, 0)
tmp24 = tl.sum(tmp23, 1)[:, None]
tmp25 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp27 = tl.where(xmask, tmp25, 0)
tmp28 = tl.sum(tmp27, 1)[:, None]
tmp30 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK])
tmp32 = tl.where(xmask, tmp30, 0)
tmp33 = tl.sum(tmp32, 1)[:, None]
tmp34 = tmp33 / tmp17
tmp35 = tmp25 - tmp34
tmp36 = tmp35 * tmp35
tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
tmp39 = tl.where(xmask, tmp37, 0)
tmp40 = tl.sum(tmp39, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp10, xmask)
tl.store(out_ptr2 + x0, tmp24, xmask)
tl.store(out_ptr3 + x0, tmp28, xmask)
tl.store(out_ptr4 + x0, tmp40, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_pow_sub_var_1(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp5 = tl.load(in_ptr2 + r0, None)
tmp13 = tl.load(in_ptr3 + r0, None)
tmp16 = tl.load(in_ptr4 + r0, None)
tmp1 = 64.0
tmp2 = tmp0 / tmp1
tmp4 = tmp3 / tmp1
tmp6 = tmp5 / tmp1
tmp7 = tmp4 * tmp6
tmp8 = tmp2 - tmp7
tmp9 = 4.0
tmp10 = tmp8 * tmp9
tmp11 = tmp10 * tmp4
tmp12 = tmp11 * tmp6
tmp14 = 63.0
tmp15 = tmp13 / tmp14
tmp17 = tmp16 / tmp14
tmp18 = tmp15 + tmp17
tmp19 = tmp4 * tmp4
tmp20 = tmp6 * tmp6
tmp21 = tmp19 + tmp20
tmp22 = tmp18 * tmp21
tmp23 = tmp12 / tmp22
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp26 = tl.sum(tmp24, 1)[:, None]
tmp27 = tmp26 / tmp9
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp27, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf4 = empty_strided_cuda((4,), (1,), torch.float32)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
buf7 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_mean_mul_var_0[grid(4)](arg0_1, arg1_1, buf0, buf1,
buf4, buf2, buf7, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf9 = empty_strided_cuda((), (), torch.float32)
buf10 = buf9
del buf9
triton_per_fused_add_div_mean_mul_pow_sub_var_1[grid(1)](buf10,
buf0, buf1, buf2, buf4, buf7, 1, 4, XBLOCK=1, num_warps=2,
num_stages=1)
del buf0
del buf1
del buf2
del buf4
del buf7
return buf10,
class Q_IndexNew(nn.Module):
"""
Quality measurement between perturbated (image with applied noise) and denoised target image.
This module works only for images with a single color channel (grayscale)
"""
def __init__(self):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dawnofthedebayan/MedAI_Project
|
Q_Index
| false
| 1,807
|
[
"Apache-2.0"
] | 0
|
a7f2597c96569662f1ca9d21ffd0eb41c77211c1
|
https://github.com/dawnofthedebayan/MedAI_Project/tree/a7f2597c96569662f1ca9d21ffd0eb41c77211c1
|
myNet
|
import torch
import torch.nn as nn
class myNet(nn.Module):
def __init__(self, in_features, num_classes=10):
super(myNet, self).__init__()
self.fc1 = nn.Linear(in_features, 1000)
self.fc2 = nn.Linear(1000, 100)
self.fc3 = nn.Linear(100, num_classes)
self.relu = nn.ReLU()
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
out = self.relu(out)
out = self.fc3(out)
return out
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 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 = 64000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 1000
x2 = xindex % 4000
x3 = xindex // 4000
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 4096 * x3), tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 6400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x4 = xindex
x0 = xindex % 100
x2 = xindex % 1600
x3 = xindex // 1600
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr0 + (x2 + 1664 * x3), tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (1000, 4), (4, 1))
assert_size_stride(primals_2, (1000,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (100, 1000), (1000, 1))
assert_size_stride(primals_5, (100,), (1,))
assert_size_stride(primals_6, (10, 100), (100, 1))
assert_size_stride(primals_7, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 1000), (1000, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 1000), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 1000), (16000, 4000, 1000,
1), 0)
del buf0
buf6 = empty_strided_cuda((4, 4, 4, 1000), (16384, 4096, 1000, 1),
torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(64000)](buf1,
primals_2, buf6, 64000, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 100), (100, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 1000), (1000, 1), 0
), reinterpret_tensor(primals_4, (1000, 100), (1, 1000), 0),
out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 100), (1600, 400, 100, 1), 0)
del buf2
buf5 = empty_strided_cuda((4, 4, 4, 100), (1664, 400, 100, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(6400)](buf3,
primals_5, buf5, 6400, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 100),
(100, 1), 0), reinterpret_tensor(primals_6, (100, 10), (1, 100),
0), alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 10), (160, 40, 10, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 1000), (1000, 1), 0
), reinterpret_tensor(buf3, (64, 100), (100, 1), 0
), primals_6, buf5, primals_4, buf6
class myNetNew(nn.Module):
def __init__(self, in_features, num_classes=10):
super(myNetNew, self).__init__()
self.fc1 = nn.Linear(in_features, 1000)
self.fc2 = nn.Linear(1000, 100)
self.fc3 = nn.Linear(100, num_classes)
self.relu = nn.ReLU()
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
daxiongpro/pytorch-tutorial
|
myNet
| false
| 1,808
|
[
"MIT"
] | 0
|
abafc32f7ee1092024085f703e4ced51ce358a1b
|
https://github.com/daxiongpro/pytorch-tutorial/tree/abafc32f7ee1092024085f703e4ced51ce358a1b
|
ConvolutionTranspose
|
import torch
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.init
import torch.nn as nn
import torch.nn.functional as F
def Normalizations(tensor_size=None, normalization=None, available=False,
**kwargs):
"""Does normalization on 4D tensor.
Args:
tensor_size: shape of tensor in BCHW
(None/any integer >0, channels, height, width)
normalization: None/batch/group/instance/layer/pixelwise
available: if True, returns all available normalization methods
groups: for group (GroupNorm), when not provided groups is the center
value of all possible - ex: for a tensor_size[1] = 128, groups is
set to 16 as the possible groups are [1, 2, 4, 8, 16, 32, 64, 128]
affine: for group and instance normalization, default False
elementwise_affine: for layer normalization. default True
"""
list_available = ['batch', 'group', 'instance', 'layer', 'pixelwise']
if available:
return list_available
normalization = normalization.lower()
assert normalization in list_available, 'Normalization must be None/' + '/'.join(
list_available)
if normalization == 'batch':
return torch.nn.BatchNorm2d(tensor_size[1])
elif normalization == 'group':
affine = kwargs['affine'] if 'affine' in kwargs.keys() else False
if 'groups' in kwargs.keys():
return torch.nn.GroupNorm(kwargs['groups'], tensor_size[1],
affine=affine)
else:
possible = [(tensor_size[1] // i) for i in range(tensor_size[1],
0, -1) if tensor_size[1] % i == 0]
groups = possible[len(possible) // 2]
return torch.nn.GroupNorm(groups, tensor_size[1], affine=affine)
elif normalization == 'instance':
affine = kwargs['affine'] if 'affine' in kwargs.keys() else False
return torch.nn.InstanceNorm2d(tensor_size[1], affine=affine)
elif normalization == 'layer':
elementwise_affine = kwargs['elementwise_affine'
] if 'elementwise_affine' in kwargs.keys() else True
return torch.nn.LayerNorm(tensor_size[1:], elementwise_affine=
elementwise_affine)
elif normalization == 'pixelwise':
return PixelWise()
class Activations(nn.Module):
""" All the usual activations along with maxout, relu + maxout and swish.
MaxOut (maxo) - https://arxiv.org/pdf/1302.4389.pdf
Swish - https://arxiv.org/pdf/1710.05941v1.pdf
Args:
activation: relu/relu6/lklu/elu/prelu/tanh/sigm/maxo/rmxo/swish
channels: parameter for prelu, default is 1
"""
def __init__(self, activation='relu', channels=1):
super(Activations, self).__init__()
if activation is not None:
activation = activation.lower()
self.activation = activation
self.function = None
if activation in self.available():
self.function = getattr(self, '_' + activation)
if activation == 'prelu':
self.weight = nn.Parameter(torch.rand(channels))
else:
self.activation = ''
def forward(self, tensor):
if self.function is None:
return tensor
return self.function(tensor)
def _relu(self, tensor):
return F.relu(tensor)
def _relu6(self, tensor):
return F.relu6(tensor)
def _lklu(self, tensor):
return F.leaky_relu(tensor)
def _elu(self, tensor):
return F.elu(tensor)
def _prelu(self, tensor):
return F.prelu(tensor, self.weight)
def _tanh(self, tensor):
return torch.tanh(tensor)
def _sigm(self, tensor):
return torch.sigmoid(tensor)
def _maxo(self, tensor):
assert tensor.size(1) % 2 == 0, 'MaxOut: tensor.size(1) must be even'
return torch.max(*tensor.split(tensor.size(1) // 2, 1))
def _rmxo(self, tensor):
return self._maxo(F.relu(tensor))
def _swish(self, tensor):
return tensor * torch.sigmoid(tensor)
def __repr__(self):
return self.activation
@staticmethod
def available():
return ['relu', 'relu6', 'lklu', 'elu', 'prelu', 'tanh', 'sigm',
'maxo', 'rmxo', 'swish']
class PixelWise(torch.nn.Module):
""" Implemented - https://arxiv.org/pdf/1710.10196.pdf """
def __init__(self, eps=1e-08):
super(PixelWise, self).__init__()
self.eps = eps
def forward(self, tensor):
return tensor.div(tensor.pow(2).mean(1, True).add(self.eps).pow(0.5))
def __repr__(self):
return 'pixelwise'
class ConvolutionTranspose(nn.Module):
"""
Parameters/Inputs
tensor_size = (None/any integer >0, channels, height, width)
filter_size = list(length=2)/tuple(length=2)/integer
out_channels = return tensor.size(1)
strides = list(length=2)/tuple(length=2)/integer
pad = True/False
activation = "relu"/"relu6"/"lklu"/"tanh"/"sigm"/"maxo"/"rmxo"/"swish"
dropout = 0.-1.
normalization = None/"batch"/"group"/"instance"/"layer"/"pixelwise"
pre_nm = True/False
groups = 1, ... out_channels
weight_nm = True/False -- https://arxiv.org/pdf/1602.07868.pdf
equalized = True/False -- https://arxiv.org/pdf/1710.10196.pdf
"""
def __init__(self, tensor_size, filter_size, out_channels, strides=(1,
1), pad=True, activation='relu', dropout=0.0, normalization=None,
pre_nm=False, groups=1, weight_nm=False, equalized=False, **kwargs):
super(ConvolutionTranspose, self).__init__()
assert len(tensor_size) == 4 and type(tensor_size) in [list, tuple
], 'ConvolutionTranspose -- tensor_size must be of length 4 (tuple or list)'
assert type(filter_size) in [int, list, tuple
], 'Convolution -- filter_size must be int/tuple/list'
if isinstance(filter_size, int):
filter_size = filter_size, filter_size
if isinstance(filter_size, list):
filter_size = tuple(filter_size)
assert len(filter_size
) == 2, 'ConvolutionTranspose -- filter_size length must be 2'
assert type(strides) in [int, list, tuple
], 'ConvolutionTranspose -- strides must be int/tuple/list'
if isinstance(strides, int):
strides = strides, strides
if isinstance(strides, list):
strides = tuple(strides)
assert len(strides
) == 2, 'ConvolutionTranspose -- strides length must be 2'
assert isinstance(pad, bool
), 'ConvolutionTranspose -- pad must be boolean'
assert isinstance(dropout, float
), 'ConvolutionTranspose -- dropout must be float'
assert normalization in [None, 'batch', 'group', 'instance',
'layer', 'pixelwise'
], "Convolution's normalization must be None/batch/group/instance/layer/pixelwise"
assert isinstance(equalized, bool
), 'Convolution -- equalized must be boolean'
self.equalized = equalized
if activation is not None:
activation = activation.lower()
dilation = kwargs['dilation'] if 'dilation' in kwargs.keys() else (1, 1
)
padding = (filter_size[0] // 2, filter_size[1] // 2) if pad else (0, 0)
if dropout > 0.0:
self.dropout = nn.Dropout2d(dropout)
pre_expansion, pst_expansion = 1, 1
if activation in ('maxo', 'rmxo'):
if pre_nm:
pre_expansion = 2
if not pre_nm:
pst_expansion = 2
if pre_nm:
if normalization is not None:
self.Normalization = Normalizations(tensor_size,
normalization, **kwargs)
if activation in ['relu', 'relu6', 'lklu', 'tanh', 'sigm',
'maxo', 'rmxo', 'swish']:
self.Activation = Activations(activation)
if weight_nm:
self.ConvolutionTranspose = nn.utils.weight_norm(nn.
ConvTranspose2d(tensor_size[1] // pre_expansion,
out_channels * pst_expansion, filter_size, strides, padding,
bias=False, dilation=dilation, groups=groups), name='weight')
else:
self.ConvolutionTranspose = nn.ConvTranspose2d(tensor_size[1] //
pre_expansion, out_channels * pst_expansion, filter_size,
strides, padding, bias=False, groups=groups)
nn.init.kaiming_normal_(self.ConvolutionTranspose.weight, nn.
init.calculate_gain('conv2d'))
if equalized:
import numpy as np
gain = kwargs['gain'] if 'gain' in kwargs.keys() else np.sqrt(2
)
fan_in = tensor_size[1] * out_channels * filter_size[0]
self.scale = gain / np.sqrt(fan_in)
self.ConvolutionTranspose.weight.data.mul_(self.scale)
self.oc = self.ConvolutionTranspose.weight.data.size(0)
self.tensor_size = tensor_size[0], out_channels, (tensor_size[2] - 1
) * strides[0] - 2 * padding[0] + filter_size[0], (tensor_size[
3] - 1) * strides[1] - 2 * padding[1] + filter_size[1]
if not pre_nm:
if normalization is not None:
self.Normalization = Normalizations((self.tensor_size[0],
out_channels * pst_expansion, self.tensor_size[2], self
.tensor_size[3]), normalization, **kwargs)
if activation in ['relu', 'relu6', 'lklu', 'tanh', 'sigm',
'maxo', 'rmxo', 'swish']:
self.Activation = Activations(activation)
self.pre_nm = pre_nm
def forward(self, tensor, output_size=None):
if hasattr(self, 'dropout'):
tensor = self.dropout(tensor)
if self.pre_nm:
if hasattr(self, 'Normalization'):
tensor = self.Normalization(tensor)
if hasattr(self, 'Activation'):
tensor = self.Activation(tensor)
if output_size is None:
output_size = self.tensor_size
output_size = tensor.size(0), self.oc, output_size[2], output_size[
3]
tensor = self.ConvolutionTranspose(tensor, output_size=output_size)
if self.equalized:
tensor = tensor.mul(self.scale)
else:
if output_size is None:
output_size = self.tensor_size
output_size = tensor.size(0), self.oc, output_size[2], output_size[
3]
tensor = self.ConvolutionTranspose(tensor, output_size=output_size)
if self.equalized:
tensor = tensor.mul(self.scale)
if hasattr(self, 'Normalization'):
tensor = self.Normalization(tensor)
if hasattr(self, 'Activation'):
tensor = self.Activation(tensor)
return tensor
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'tensor_size': [4, 4, 4, 4], 'filter_size': 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.utils.data
import torch.utils.data.distributed
import torch.nn.init
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_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(2, 2), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 3, 3), (36, 9, 3, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(144)](buf1, buf2,
144, XBLOCK=128, num_warps=4, num_stages=1)
return buf1, primals_1, primals_2, buf2
def Normalizations(tensor_size=None, normalization=None, available=False,
**kwargs):
"""Does normalization on 4D tensor.
Args:
tensor_size: shape of tensor in BCHW
(None/any integer >0, channels, height, width)
normalization: None/batch/group/instance/layer/pixelwise
available: if True, returns all available normalization methods
groups: for group (GroupNorm), when not provided groups is the center
value of all possible - ex: for a tensor_size[1] = 128, groups is
set to 16 as the possible groups are [1, 2, 4, 8, 16, 32, 64, 128]
affine: for group and instance normalization, default False
elementwise_affine: for layer normalization. default True
"""
list_available = ['batch', 'group', 'instance', 'layer', 'pixelwise']
if available:
return list_available
normalization = normalization.lower()
assert normalization in list_available, 'Normalization must be None/' + '/'.join(
list_available)
if normalization == 'batch':
return torch.nn.BatchNorm2d(tensor_size[1])
elif normalization == 'group':
affine = kwargs['affine'] if 'affine' in kwargs.keys() else False
if 'groups' in kwargs.keys():
return torch.nn.GroupNorm(kwargs['groups'], tensor_size[1],
affine=affine)
else:
possible = [(tensor_size[1] // i) for i in range(tensor_size[1],
0, -1) if tensor_size[1] % i == 0]
groups = possible[len(possible) // 2]
return torch.nn.GroupNorm(groups, tensor_size[1], affine=affine)
elif normalization == 'instance':
affine = kwargs['affine'] if 'affine' in kwargs.keys() else False
return torch.nn.InstanceNorm2d(tensor_size[1], affine=affine)
elif normalization == 'layer':
elementwise_affine = kwargs['elementwise_affine'
] if 'elementwise_affine' in kwargs.keys() else True
return torch.nn.LayerNorm(tensor_size[1:], elementwise_affine=
elementwise_affine)
elif normalization == 'pixelwise':
return PixelWise()
class Activations(nn.Module):
""" All the usual activations along with maxout, relu + maxout and swish.
MaxOut (maxo) - https://arxiv.org/pdf/1302.4389.pdf
Swish - https://arxiv.org/pdf/1710.05941v1.pdf
Args:
activation: relu/relu6/lklu/elu/prelu/tanh/sigm/maxo/rmxo/swish
channels: parameter for prelu, default is 1
"""
def __init__(self, activation='relu', channels=1):
super(Activations, self).__init__()
if activation is not None:
activation = activation.lower()
self.activation = activation
self.function = None
if activation in self.available():
self.function = getattr(self, '_' + activation)
if activation == 'prelu':
self.weight = nn.Parameter(torch.rand(channels))
else:
self.activation = ''
def forward(self, tensor):
if self.function is None:
return tensor
return self.function(tensor)
def _relu(self, tensor):
return F.relu(tensor)
def _relu6(self, tensor):
return F.relu6(tensor)
def _lklu(self, tensor):
return F.leaky_relu(tensor)
def _elu(self, tensor):
return F.elu(tensor)
def _prelu(self, tensor):
return F.prelu(tensor, self.weight)
def _tanh(self, tensor):
return torch.tanh(tensor)
def _sigm(self, tensor):
return torch.sigmoid(tensor)
def _maxo(self, tensor):
assert tensor.size(1) % 2 == 0, 'MaxOut: tensor.size(1) must be even'
return torch.max(*tensor.split(tensor.size(1) // 2, 1))
def _rmxo(self, tensor):
return self._maxo(F.relu(tensor))
def _swish(self, tensor):
return tensor * torch.sigmoid(tensor)
def __repr__(self):
return self.activation
@staticmethod
def available():
return ['relu', 'relu6', 'lklu', 'elu', 'prelu', 'tanh', 'sigm',
'maxo', 'rmxo', 'swish']
class PixelWise(torch.nn.Module):
""" Implemented - https://arxiv.org/pdf/1710.10196.pdf """
def __init__(self, eps=1e-08):
super(PixelWise, self).__init__()
self.eps = eps
def forward(self, tensor):
return tensor.div(tensor.pow(2).mean(1, True).add(self.eps).pow(0.5))
def __repr__(self):
return 'pixelwise'
class ConvolutionTransposeNew(nn.Module):
"""
Parameters/Inputs
tensor_size = (None/any integer >0, channels, height, width)
filter_size = list(length=2)/tuple(length=2)/integer
out_channels = return tensor.size(1)
strides = list(length=2)/tuple(length=2)/integer
pad = True/False
activation = "relu"/"relu6"/"lklu"/"tanh"/"sigm"/"maxo"/"rmxo"/"swish"
dropout = 0.-1.
normalization = None/"batch"/"group"/"instance"/"layer"/"pixelwise"
pre_nm = True/False
groups = 1, ... out_channels
weight_nm = True/False -- https://arxiv.org/pdf/1602.07868.pdf
equalized = True/False -- https://arxiv.org/pdf/1710.10196.pdf
"""
def __init__(self, tensor_size, filter_size, out_channels, strides=(1,
1), pad=True, activation='relu', dropout=0.0, normalization=None,
pre_nm=False, groups=1, weight_nm=False, equalized=False, **kwargs):
super(ConvolutionTransposeNew, self).__init__()
assert len(tensor_size) == 4 and type(tensor_size) in [list, tuple
], 'ConvolutionTranspose -- tensor_size must be of length 4 (tuple or list)'
assert type(filter_size) in [int, list, tuple
], 'Convolution -- filter_size must be int/tuple/list'
if isinstance(filter_size, int):
filter_size = filter_size, filter_size
if isinstance(filter_size, list):
filter_size = tuple(filter_size)
assert len(filter_size
) == 2, 'ConvolutionTranspose -- filter_size length must be 2'
assert type(strides) in [int, list, tuple
], 'ConvolutionTranspose -- strides must be int/tuple/list'
if isinstance(strides, int):
strides = strides, strides
if isinstance(strides, list):
strides = tuple(strides)
assert len(strides
) == 2, 'ConvolutionTranspose -- strides length must be 2'
assert isinstance(pad, bool
), 'ConvolutionTranspose -- pad must be boolean'
assert isinstance(dropout, float
), 'ConvolutionTranspose -- dropout must be float'
assert normalization in [None, 'batch', 'group', 'instance',
'layer', 'pixelwise'
], "Convolution's normalization must be None/batch/group/instance/layer/pixelwise"
assert isinstance(equalized, bool
), 'Convolution -- equalized must be boolean'
self.equalized = equalized
if activation is not None:
activation = activation.lower()
dilation = kwargs['dilation'] if 'dilation' in kwargs.keys() else (1, 1
)
padding = (filter_size[0] // 2, filter_size[1] // 2) if pad else (0, 0)
if dropout > 0.0:
self.dropout = nn.Dropout2d(dropout)
pre_expansion, pst_expansion = 1, 1
if activation in ('maxo', 'rmxo'):
if pre_nm:
pre_expansion = 2
if not pre_nm:
pst_expansion = 2
if pre_nm:
if normalization is not None:
self.Normalization = Normalizations(tensor_size,
normalization, **kwargs)
if activation in ['relu', 'relu6', 'lklu', 'tanh', 'sigm',
'maxo', 'rmxo', 'swish']:
self.Activation = Activations(activation)
if weight_nm:
self.ConvolutionTranspose = nn.utils.weight_norm(nn.
ConvTranspose2d(tensor_size[1] // pre_expansion,
out_channels * pst_expansion, filter_size, strides, padding,
bias=False, dilation=dilation, groups=groups), name='weight')
else:
self.ConvolutionTranspose = nn.ConvTranspose2d(tensor_size[1] //
pre_expansion, out_channels * pst_expansion, filter_size,
strides, padding, bias=False, groups=groups)
nn.init.kaiming_normal_(self.ConvolutionTranspose.weight, nn.
init.calculate_gain('conv2d'))
if equalized:
import numpy as np
gain = kwargs['gain'] if 'gain' in kwargs.keys() else np.sqrt(2
)
fan_in = tensor_size[1] * out_channels * filter_size[0]
self.scale = gain / np.sqrt(fan_in)
self.ConvolutionTranspose.weight.data.mul_(self.scale)
self.oc = self.ConvolutionTranspose.weight.data.size(0)
self.tensor_size = tensor_size[0], out_channels, (tensor_size[2] - 1
) * strides[0] - 2 * padding[0] + filter_size[0], (tensor_size[
3] - 1) * strides[1] - 2 * padding[1] + filter_size[1]
if not pre_nm:
if normalization is not None:
self.Normalization = Normalizations((self.tensor_size[0],
out_channels * pst_expansion, self.tensor_size[2], self
.tensor_size[3]), normalization, **kwargs)
if activation in ['relu', 'relu6', 'lklu', 'tanh', 'sigm',
'maxo', 'rmxo', 'swish']:
self.Activation = Activations(activation)
self.pre_nm = pre_nm
def forward(self, input_0):
primals_1 = self.ConvolutionTranspose.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
davidwagnerkc/TensorMONK
|
ConvolutionTranspose
| false
| 1,809
|
[
"MIT"
] | 0
|
3607836d3d6bfd0994e044536b2a51bc84b35f31
|
https://github.com/davidwagnerkc/TensorMONK/tree/3607836d3d6bfd0994e044536b2a51bc84b35f31
|
Conv2d
|
from torch.nn import Module
import math
import torch
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
import torch.utils.data
from torch.nn.parameter import Parameter
from torch.nn.functional import pad
from torch.nn.modules import Module
def conv2d_same_padding(input, weight, bias=None, stride=1, padding=1,
dilation=1, groups=1):
input_rows = input.size(2)
filter_rows = weight.size(2)
(filter_rows - 1) * dilation[0] + 1
out_rows = (input_rows + stride[0] - 1) // stride[0]
padding_rows = max(0, (out_rows - 1) * stride[0] + (filter_rows - 1) *
dilation[0] + 1 - input_rows)
rows_odd = padding_rows % 2 != 0
padding_cols = max(0, (out_rows - 1) * stride[0] + (filter_rows - 1) *
dilation[0] + 1 - input_rows)
cols_odd = padding_rows % 2 != 0
if rows_odd or cols_odd:
input = pad(input, [0, int(cols_odd), 0, int(rows_odd)])
return F.conv2d(input, weight, bias, stride, padding=(padding_rows // 2,
padding_cols // 2), dilation=dilation, groups=groups)
class _ConvNd(Module):
def __init__(self, in_channels, out_channels, kernel_size, stride,
padding, dilation, transposed, output_padding, groups, bias,
weight_=None):
super(_ConvNd, self).__init__()
if in_channels % groups != 0:
raise ValueError('in_channels must be divisible by groups')
if out_channels % groups != 0:
raise ValueError('out_channels must be divisible by groups')
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.transposed = transposed
self.output_padding = output_padding
self.groups = groups
if transposed:
self.weight = Parameter(torch.Tensor(in_channels, out_channels //
groups, *kernel_size))
elif weight_ is None:
self.weight = Parameter(torch.Tensor(out_channels, in_channels //
groups, *kernel_size))
elif weight_ is not None and isinstance(weight_, torch.Tensor):
self.weight = Parameter(weight_, requires_grad=False)
else:
raise ValueError('不支持的类型!')
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
n = self.in_channels
for k in self.kernel_size:
n *= k
stdv = 1.0 / math.sqrt(n)
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def __repr__(self):
s = (
'{name}({in_channels}, {out_channels}, kernel_size={kernel_size}, stride={stride}'
)
if self.padding != (0,) * len(self.padding):
s += ', padding={padding}'
if self.dilation != (1,) * len(self.dilation):
s += ', dilation={dilation}'
if self.output_padding != (0,) * len(self.output_padding):
s += ', output_padding={output_padding}'
if self.groups != 1:
s += ', groups={groups}'
if self.bias is None:
s += ', bias=False'
s += ')'
return s.format(name=self.__class__.__name__, **self.__dict__)
class Conv2d(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, weight_=None):
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,
weight_=weight_)
def forward(self, input):
return conv2d_same_padding(input, self.weight, self.bias, self.
stride, self.padding, self.dilation, self.groups)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.nn import Module
import math
from torch.nn.modules.utils import _pair
import torch.nn.functional as F
import torch.utils.data
from torch.nn.parameter import Parameter
from torch.nn.functional import pad
from torch.nn.modules import Module
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 400
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 5 % 5
x0 = xindex % 5
x2 = xindex // 25
x3 = xindex
tmp0 = x1
tmp1 = tl.full([1], 4, tl.int64)
tmp2 = tmp0 < tmp1
tmp3 = x0
tmp4 = tmp3 < tmp1
tmp5 = tmp2 & tmp4
tmp6 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp5 & xmask, other=0.0)
tl.store(out_ptr0 + x3, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(400)](primals_3, buf0, 400,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(256)](buf2, primals_2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
return buf2, primals_1, buf0
def conv2d_same_padding(input, weight, bias=None, stride=1, padding=1,
dilation=1, groups=1):
input_rows = input.size(2)
filter_rows = weight.size(2)
(filter_rows - 1) * dilation[0] + 1
out_rows = (input_rows + stride[0] - 1) // stride[0]
padding_rows = max(0, (out_rows - 1) * stride[0] + (filter_rows - 1) *
dilation[0] + 1 - input_rows)
rows_odd = padding_rows % 2 != 0
padding_cols = max(0, (out_rows - 1) * stride[0] + (filter_rows - 1) *
dilation[0] + 1 - input_rows)
cols_odd = padding_rows % 2 != 0
if rows_odd or cols_odd:
input = pad(input, [0, int(cols_odd), 0, int(rows_odd)])
return F.conv2d(input, weight, bias, stride, padding=(padding_rows // 2,
padding_cols // 2), dilation=dilation, groups=groups)
class _ConvNd(Module):
def __init__(self, in_channels, out_channels, kernel_size, stride,
padding, dilation, transposed, output_padding, groups, bias,
weight_=None):
super(_ConvNd, self).__init__()
if in_channels % groups != 0:
raise ValueError('in_channels must be divisible by groups')
if out_channels % groups != 0:
raise ValueError('out_channels must be divisible by groups')
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.dilation = dilation
self.transposed = transposed
self.output_padding = output_padding
self.groups = groups
if transposed:
self.weight = Parameter(torch.Tensor(in_channels, out_channels //
groups, *kernel_size))
elif weight_ is None:
self.weight = Parameter(torch.Tensor(out_channels, in_channels //
groups, *kernel_size))
elif weight_ is not None and isinstance(weight_, torch.Tensor):
self.weight = Parameter(weight_, requires_grad=False)
else:
raise ValueError('不支持的类型!')
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
n = self.in_channels
for k in self.kernel_size:
n *= k
stdv = 1.0 / math.sqrt(n)
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def __repr__(self):
s = (
'{name}({in_channels}, {out_channels}, kernel_size={kernel_size}, stride={stride}'
)
if self.padding != (0,) * len(self.padding):
s += ', padding={padding}'
if self.dilation != (1,) * len(self.dilation):
s += ', dilation={dilation}'
if self.output_padding != (0,) * len(self.output_padding):
s += ', output_padding={output_padding}'
if self.groups != 1:
s += ', groups={groups}'
if self.bias is None:
s += ', bias=False'
s += ')'
return s.format(name=self.__class__.__name__, **self.__dict__)
class Conv2dNew(_ConvNd):
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
padding=0, dilation=1, groups=1, bias=True, weight_=None):
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, weight_=weight_)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ddayzzz/mmdetection
|
Conv2d
| false
| 1,810
|
[
"Apache-2.0"
] | 0
|
b9940c56cc19b3dda7468a5fd858b9683e93a486
|
https://github.com/ddayzzz/mmdetection/tree/b9940c56cc19b3dda7468a5fd858b9683e93a486
|
GeneralizedDiceLoss
|
import collections
import torch
import warnings
from typing import Optional
from typing import Union
from typing import Any
from typing import Callable
from typing import Tuple
import torch.nn
from torch.nn.modules.loss import _Loss
from enum import Enum
import collections.abc
def issequenceiterable(obj: 'Any') ->bool:
"""
Determine if the object is an iterable sequence and is not a string.
"""
if torch.is_tensor(obj):
return int(obj.dim()) > 0
return isinstance(obj, collections.abc.Iterable) and not isinstance(obj,
str)
def ensure_tuple(vals: 'Any') ->Tuple[Any, ...]:
"""
Returns a tuple of `vals`.
"""
if not issequenceiterable(vals):
vals = vals,
return tuple(vals)
def ensure_tuple_size(tup: 'Any', dim: 'int', pad_val: 'Any'=0) ->Tuple[Any,
...]:
"""
Returns a copy of `tup` with `dim` values by either shortened or padded with `pad_val` as necessary.
"""
tup = ensure_tuple(tup) + (pad_val,) * dim
return tuple(tup[:dim])
def one_hot(labels: 'torch.Tensor', num_classes: 'int', dtype:
'torch.dtype'=torch.float, dim: 'int'=1) ->torch.Tensor:
"""
For a tensor `labels` of dimensions B1[spatial_dims], return a tensor of dimensions `BN[spatial_dims]`
for `num_classes` N number of classes.
Example:
For every value v = labels[b,1,h,w], the value in the result at [b,v,h,w] will be 1 and all others 0.
Note that this will include the background label, thus a binary mask should be treated as having 2 classes.
"""
assert labels.dim() > 0, 'labels should have dim of 1 or more.'
if labels.ndim < dim + 1:
shape = ensure_tuple_size(labels.shape, dim + 1, 1)
labels = labels.reshape(*shape)
sh = list(labels.shape)
assert sh[dim
] == 1, 'labels should have a channel with length equals to one.'
sh[dim] = num_classes
o = torch.zeros(size=sh, dtype=dtype, device=labels.device)
labels = o.scatter_(dim=dim, index=labels.long(), value=1)
return labels
class LossReduction(Enum):
"""
See also:
- :py:class:`monai.losses.dice.DiceLoss`
- :py:class:`monai.losses.dice.GeneralizedDiceLoss`
- :py:class:`monai.losses.focal_loss.FocalLoss`
- :py:class:`monai.losses.tversky.TverskyLoss`
"""
NONE = 'none'
MEAN = 'mean'
SUM = 'sum'
class Weight(Enum):
"""
See also: :py:class:`monai.losses.dice.GeneralizedDiceLoss`
"""
SQUARE = 'square'
SIMPLE = 'simple'
UNIFORM = 'uniform'
class GeneralizedDiceLoss(_Loss):
"""
Compute the generalised Dice loss defined in:
Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning
loss function for highly unbalanced segmentations. DLMIA 2017.
Adapted from:
https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/layer/loss_segmentation.py#L279
"""
def __init__(self, include_background: 'bool'=True, to_onehot_y: 'bool'
=False, sigmoid: 'bool'=False, softmax: 'bool'=False, other_act:
'Optional[Callable]'=None, w_type: 'Union[Weight, str]'=Weight.
SQUARE, reduction: 'Union[LossReduction, str]'=LossReduction.MEAN,
smooth_nr: 'float'=1e-05, smooth_dr: 'float'=1e-05, batch: 'bool'=False
) ->None:
"""
Args:
include_background: If False channel index 0 (background category) is excluded from the calculation.
to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False.
sigmoid: If True, apply a sigmoid function to the prediction.
softmax: If True, apply a softmax function to the prediction.
other_act: if don't want to use `sigmoid` or `softmax`, use other callable function to execute
other activation layers, Defaults to ``None``. for example:
`other_act = torch.tanh`.
squared_pred: use squared versions of targets and predictions in the denominator or not.
w_type: {``"square"``, ``"simple"``, ``"uniform"``}
Type of function to transform ground truth volume to a weight factor. Defaults to ``"square"``.
reduction: {``"none"``, ``"mean"``, ``"sum"``}
Specifies the reduction to apply to the output. Defaults to ``"mean"``.
- ``"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.
smooth_nr: a small constant added to the numerator to avoid zero.
smooth_dr: a small constant added to the denominator to avoid nan.
batch: whether to sum the intersection and union areas over the batch dimension before the dividing.
Defaults to False, intersection over union is computed from each item in the batch.
Raises:
TypeError: When ``other_act`` is not an ``Optional[Callable]``.
ValueError: When more than 1 of [``sigmoid=True``, ``softmax=True``, ``other_act is not None``].
Incompatible values.
"""
super().__init__(reduction=LossReduction(reduction).value)
if other_act is not None and not callable(other_act):
raise TypeError(
f'other_act must be None or callable but is {type(other_act).__name__}.'
)
if int(sigmoid) + int(softmax) + int(other_act is not None) > 1:
raise ValueError(
'Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].'
)
self.include_background = include_background
self.to_onehot_y = to_onehot_y
self.sigmoid = sigmoid
self.softmax = softmax
self.other_act = other_act
w_type = Weight(w_type)
self.w_func: 'Callable' = torch.ones_like
if w_type == Weight.SIMPLE:
self.w_func = torch.reciprocal
elif w_type == Weight.SQUARE:
self.w_func = lambda x: torch.reciprocal(x * x)
self.smooth_nr = float(smooth_nr)
self.smooth_dr = float(smooth_dr)
self.batch = batch
def forward(self, input: 'torch.Tensor', target: 'torch.Tensor'
) ->torch.Tensor:
"""
Args:
input: the shape should be BNH[WD].
target: the shape should be BNH[WD].
Raises:
ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"].
"""
if self.sigmoid:
input = torch.sigmoid(input)
n_pred_ch = input.shape[1]
if self.softmax:
if n_pred_ch == 1:
warnings.warn(
'single channel prediction, `softmax=True` ignored.')
else:
input = torch.softmax(input, 1)
if self.other_act is not None:
input = self.other_act(input)
if self.to_onehot_y:
if n_pred_ch == 1:
warnings.warn(
'single channel prediction, `to_onehot_y=True` ignored.')
else:
target = one_hot(target, num_classes=n_pred_ch)
if not self.include_background:
if n_pred_ch == 1:
warnings.warn(
'single channel prediction, `include_background=False` ignored.'
)
else:
target = target[:, 1:]
input = input[:, 1:]
assert target.shape == input.shape, f'ground truth has differing shape ({target.shape}) from input ({input.shape})'
reduce_axis = list(range(2, len(input.shape)))
if self.batch:
reduce_axis = [0] + reduce_axis
intersection = torch.sum(target * input, reduce_axis)
ground_o = torch.sum(target, reduce_axis)
pred_o = torch.sum(input, reduce_axis)
denominator = ground_o + pred_o
w = self.w_func(ground_o.float())
for b in w:
infs = torch.isinf(b)
b[infs] = 0.0
b[infs] = torch.max(b)
f: 'torch.Tensor' = 1.0 - (2.0 * (intersection * w).sum(0 if self.
batch else 1) + self.smooth_nr) / ((denominator * w).sum(0 if
self.batch else 1) + self.smooth_dr)
if self.reduction == LossReduction.MEAN.value:
f = torch.mean(f)
elif self.reduction == LossReduction.SUM.value:
f = torch.sum(f)
elif self.reduction == LossReduction.NONE.value:
pass
else:
raise ValueError(
f'Unsupported reduction: {self.reduction}, available options are ["mean", "sum", "none"].'
)
return f
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import collections
from typing import Optional
from typing import Union
from typing import Any
from typing import Callable
from typing import Tuple
import torch.nn
from torch.nn.modules.loss import _Loss
from enum import Enum
import collections.abc
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 = 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]
tmp7 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp13 = tl.where(xmask, tmp11, 0)
tmp14 = tl.sum(tmp13, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp10, xmask)
tl.store(out_ptr2 + x0, tmp14, xmask)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tmp0 * tmp0
tmp2 = tl.full([1], 1, tl.int32)
tmp3 = tmp2 / tmp1
tmp4 = libdevice.isinf(tmp3).to(tl.int1)
tmp5 = 0.0
tmp6 = tl.where(tmp4, tmp5, tmp3)
tl.store(out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_mul_reciprocal_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + x2, xmask)
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tmp4 * tmp4
tmp6 = tl.full([1], 1, tl.int32)
tmp7 = tmp6 / tmp5
tmp8 = tl.where(tmp2, tmp3, tmp7)
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_per_fused_index_put_max_3(in_ptr0, in_ptr1, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp2 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp0 = tl.full([1, 1], 0, tl.int32)
tmp1 = tmp0 == tmp0
tmp4 = tmp3 * tmp3
tmp5 = tl.full([1, 1], 1, tl.int32)
tmp6 = tmp5 / tmp4
tmp7 = tl.where(tmp1, tmp2, tmp6)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = triton_helpers.max2(tmp8, 1)[:, None]
tmp11 = libdevice.isinf(tmp6).to(tl.int1)
tmp12 = tl.where(tmp11, tmp10, tmp7)
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp12, None)
@triton.jit
def triton_poi_fused_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_5(in_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
tmp3 = tl.load(in_ptr0 + x0, xmask)
tmp4 = tl.load(in_ptr0 + (4 + x0), xmask)
tmp0 = tl.full([1], 1, tl.int32)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = libdevice.isinf(tmp5).to(tl.int1)
tmp7 = 0.0
tmp8 = tl.where(tmp6, tmp7, tmp5)
tl.store(out_ptr1 + (4 + x0), tmp8, xmask)
@triton.jit
def triton_poi_fused_6(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp0 = x1
tmp1 = tl.full([1], 1, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_per_fused_index_put_max_7(in_ptr0, in_ptr1, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp2 = tl.load(in_ptr0 + (4 + r0), None)
tmp9 = tl.load(in_ptr1 + r0, None)
tmp10 = tl.load(in_ptr1 + (4 + r0), None)
tmp0 = tl.full([1, 1], 1, tl.int32)
tmp1 = tmp0 == tmp0
tmp3 = tl.where(tmp1, tmp2, tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = triton_helpers.max2(tmp4, 1)[:, None]
tmp7 = tl.full([1, 1], 0, tl.int32)
tmp8 = tmp0 == tmp7
tmp11 = tl.where(tmp8, tmp9, tmp10)
tmp12 = libdevice.isinf(tmp11).to(tl.int1)
tmp13 = tl.where(tmp12, tmp6, tmp3)
tl.store(out_ptr2 + tl.broadcast_to(4 + r0, [XBLOCK, RBLOCK]), tmp13, None)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_8(in_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
tmp3 = tl.load(in_ptr0 + (4 + x0), xmask)
tmp4 = tl.load(in_ptr0 + (8 + x0), xmask)
tmp0 = tl.full([1], 2, tl.int32)
tmp1 = tl.full([1], 1, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = libdevice.isinf(tmp5).to(tl.int1)
tmp7 = 0.0
tmp8 = tl.where(tmp6, tmp7, tmp5)
tl.store(out_ptr1 + (8 + x0), tmp8, xmask)
@triton.jit
def triton_poi_fused_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (8 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp0 = x1
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_per_fused_index_put_max_10(in_ptr0, in_ptr1, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp2 = tl.load(in_ptr0 + (8 + r0), None)
tmp9 = tl.load(in_ptr1 + (4 + r0), None)
tmp10 = tl.load(in_ptr1 + (8 + r0), None)
tmp0 = tl.full([1, 1], 2, tl.int32)
tmp1 = tmp0 == tmp0
tmp3 = tl.where(tmp1, tmp2, tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = triton_helpers.max2(tmp4, 1)[:, None]
tmp7 = tl.full([1, 1], 1, tl.int32)
tmp8 = tmp0 == tmp7
tmp11 = tl.where(tmp8, tmp9, tmp10)
tmp12 = libdevice.isinf(tmp11).to(tl.int1)
tmp13 = tl.where(tmp12, tmp6, tmp3)
tl.store(out_ptr2 + tl.broadcast_to(8 + r0, [XBLOCK, RBLOCK]), tmp13, None)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_11(in_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
tmp3 = tl.load(in_ptr0 + (8 + x0), xmask)
tmp4 = tl.load(in_ptr0 + (12 + x0), xmask)
tmp0 = tl.full([1], 3, tl.int32)
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = libdevice.isinf(tmp5).to(tl.int1)
tmp7 = 0.0
tmp8 = tl.where(tmp6, tmp7, tmp5)
tl.store(out_ptr1 + (12 + x0), tmp8, xmask)
@triton.jit
def triton_poi_fused_12(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
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp3 = tl.load(in_ptr0 + (12 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + x2, xmask)
tmp0 = x1
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tl.store(out_ptr0 + x2, tmp5, xmask)
@triton.jit
def triton_per_fused_index_put_max_13(in_ptr0, in_ptr1, out_ptr2, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp2 = tl.load(in_ptr0 + (12 + r0), None)
tmp9 = tl.load(in_ptr1 + (8 + r0), None)
tmp10 = tl.load(in_ptr1 + (12 + r0), None)
tmp0 = tl.full([1, 1], 3, tl.int32)
tmp1 = tmp0 == tmp0
tmp3 = tl.where(tmp1, tmp2, tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = triton_helpers.max2(tmp4, 1)[:, None]
tmp7 = tl.full([1, 1], 2, tl.int32)
tmp8 = tmp0 == tmp7
tmp11 = tl.where(tmp8, tmp9, tmp10)
tmp12 = libdevice.isinf(tmp11).to(tl.int1)
tmp13 = tl.where(tmp12, tmp6, tmp3)
tl.store(out_ptr2 + tl.broadcast_to(12 + r0, [XBLOCK, RBLOCK]), tmp13, None
)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_sum_14(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, 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')
tmp4 = tl.load(in_ptr1 + 12)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK, RBLOCK])
tmp6 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + 13)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp12 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr1 + 14)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
tmp19 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr1 + 15)
tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
tmp26 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr3 + 4 * r0, None, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp35 = tl.load(in_ptr3 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp39 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr3 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp44 = tl.load(in_ptr2 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp45 = tl.load(in_ptr3 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp1 = r0
tmp2 = tl.full([1, 1], 3, tl.int32)
tmp3 = tmp1 == tmp2
tmp7 = tl.where(tmp3, tmp5, tmp6)
tmp8 = tmp0 * tmp7
tmp13 = tl.where(tmp3, tmp11, tmp12)
tmp14 = tmp9 * tmp13
tmp15 = tmp8 + tmp14
tmp20 = tl.where(tmp3, tmp18, tmp19)
tmp21 = tmp16 * tmp20
tmp22 = tmp15 + tmp21
tmp27 = tl.where(tmp3, tmp25, tmp26)
tmp28 = tmp23 * tmp27
tmp29 = tmp22 + tmp28
tmp32 = tmp30 + tmp31
tmp33 = tmp32 * tmp7
tmp36 = tmp34 + tmp35
tmp37 = tmp36 * tmp13
tmp38 = tmp33 + tmp37
tmp41 = tmp39 + tmp40
tmp42 = tmp41 * tmp20
tmp43 = tmp38 + tmp42
tmp46 = tmp44 + tmp45
tmp47 = tmp46 * tmp27
tmp48 = tmp43 + tmp47
tmp49 = 2.0
tmp50 = tmp29 * tmp49
tmp51 = 1e-05
tmp52 = tmp50 + tmp51
tmp53 = tmp48 + tmp51
tmp54 = tmp52 / tmp53
tmp55 = 1.0
tmp56 = tmp55 - tmp54
tmp57 = tl.broadcast_to(tmp56, [XBLOCK, RBLOCK])
tmp59 = tl.sum(tmp57, 1)[:, None]
tmp60 = 4.0
tmp61 = tmp59 / tmp60
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp61, 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, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf29 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(16)](arg1_1, arg0_1, buf0, buf1,
buf29, 16, 16, XBLOCK=8, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_index_put_lift_fresh_1[grid(4)](buf1, buf2, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_mul_reciprocal_2[grid(16)](buf2, buf1, buf4, 16,
XBLOCK=16, num_warps=1, num_stages=1)
triton_per_fused_index_put_max_3[grid(1)](buf2, buf1, buf4, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
del buf2
buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_4[grid(16)](buf4, buf7, 16, XBLOCK=16, num_warps=1,
num_stages=1)
triton_poi_fused_index_put_lift_fresh_5[grid(4)](buf4, buf7, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_6[grid(16)](buf7, buf11, 16, XBLOCK=16, num_warps=
1, num_stages=1)
triton_per_fused_index_put_max_7[grid(1)](buf7, buf4, buf11, 1, 4,
XBLOCK=1, num_warps=2, num_stages=1)
buf14 = buf7
del buf7
triton_poi_fused_6[grid(16)](buf11, buf14, 16, XBLOCK=16, num_warps
=1, num_stages=1)
triton_poi_fused_index_put_lift_fresh_8[grid(4)](buf11, buf14, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf18 = buf4
del buf4
triton_poi_fused_9[grid(16)](buf14, buf18, 16, XBLOCK=16, num_warps
=1, num_stages=1)
triton_per_fused_index_put_max_10[grid(1)](buf14, buf11, buf18, 1,
4, XBLOCK=1, num_warps=2, num_stages=1)
buf21 = buf14
del buf14
triton_poi_fused_9[grid(16)](buf18, buf21, 16, XBLOCK=16, num_warps
=1, num_stages=1)
triton_poi_fused_index_put_lift_fresh_11[grid(4)](buf18, buf21, 4,
XBLOCK=4, num_warps=1, num_stages=1)
buf25 = buf11
del buf11
triton_poi_fused_12[grid(16)](buf21, buf25, 16, XBLOCK=16,
num_warps=1, num_stages=1)
triton_per_fused_index_put_max_13[grid(1)](buf21, buf18, buf25, 1,
4, XBLOCK=1, num_warps=2, num_stages=1)
del buf18
del buf21
buf31 = empty_strided_cuda((), (), torch.float32)
buf32 = buf31
del buf31
triton_per_fused_add_div_mean_mul_rsub_sum_14[grid(1)](buf32, buf0,
buf25, buf1, buf29, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf25
del buf29
return buf32,
def issequenceiterable(obj: 'Any') ->bool:
"""
Determine if the object is an iterable sequence and is not a string.
"""
if torch.is_tensor(obj):
return int(obj.dim()) > 0
return isinstance(obj, collections.abc.Iterable) and not isinstance(obj,
str)
def ensure_tuple(vals: 'Any') ->Tuple[Any, ...]:
"""
Returns a tuple of `vals`.
"""
if not issequenceiterable(vals):
vals = vals,
return tuple(vals)
def ensure_tuple_size(tup: 'Any', dim: 'int', pad_val: 'Any'=0) ->Tuple[Any,
...]:
"""
Returns a copy of `tup` with `dim` values by either shortened or padded with `pad_val` as necessary.
"""
tup = ensure_tuple(tup) + (pad_val,) * dim
return tuple(tup[:dim])
def one_hot(labels: 'torch.Tensor', num_classes: 'int', dtype:
'torch.dtype'=torch.float, dim: 'int'=1) ->torch.Tensor:
"""
For a tensor `labels` of dimensions B1[spatial_dims], return a tensor of dimensions `BN[spatial_dims]`
for `num_classes` N number of classes.
Example:
For every value v = labels[b,1,h,w], the value in the result at [b,v,h,w] will be 1 and all others 0.
Note that this will include the background label, thus a binary mask should be treated as having 2 classes.
"""
assert labels.dim() > 0, 'labels should have dim of 1 or more.'
if labels.ndim < dim + 1:
shape = ensure_tuple_size(labels.shape, dim + 1, 1)
labels = labels.reshape(*shape)
sh = list(labels.shape)
assert sh[dim
] == 1, 'labels should have a channel with length equals to one.'
sh[dim] = num_classes
o = torch.zeros(size=sh, dtype=dtype, device=labels.device)
labels = o.scatter_(dim=dim, index=labels.long(), value=1)
return labels
class LossReduction(Enum):
"""
See also:
- :py:class:`monai.losses.dice.DiceLoss`
- :py:class:`monai.losses.dice.GeneralizedDiceLoss`
- :py:class:`monai.losses.focal_loss.FocalLoss`
- :py:class:`monai.losses.tversky.TverskyLoss`
"""
NONE = 'none'
MEAN = 'mean'
SUM = 'sum'
class Weight(Enum):
"""
See also: :py:class:`monai.losses.dice.GeneralizedDiceLoss`
"""
SQUARE = 'square'
SIMPLE = 'simple'
UNIFORM = 'uniform'
class GeneralizedDiceLossNew(_Loss):
"""
Compute the generalised Dice loss defined in:
Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning
loss function for highly unbalanced segmentations. DLMIA 2017.
Adapted from:
https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/layer/loss_segmentation.py#L279
"""
def __init__(self, include_background: 'bool'=True, to_onehot_y: 'bool'
=False, sigmoid: 'bool'=False, softmax: 'bool'=False, other_act:
'Optional[Callable]'=None, w_type: 'Union[Weight, str]'=Weight.
SQUARE, reduction: 'Union[LossReduction, str]'=LossReduction.MEAN,
smooth_nr: 'float'=1e-05, smooth_dr: 'float'=1e-05, batch: 'bool'=False
) ->None:
"""
Args:
include_background: If False channel index 0 (background category) is excluded from the calculation.
to_onehot_y: whether to convert `y` into the one-hot format. Defaults to False.
sigmoid: If True, apply a sigmoid function to the prediction.
softmax: If True, apply a softmax function to the prediction.
other_act: if don't want to use `sigmoid` or `softmax`, use other callable function to execute
other activation layers, Defaults to ``None``. for example:
`other_act = torch.tanh`.
squared_pred: use squared versions of targets and predictions in the denominator or not.
w_type: {``"square"``, ``"simple"``, ``"uniform"``}
Type of function to transform ground truth volume to a weight factor. Defaults to ``"square"``.
reduction: {``"none"``, ``"mean"``, ``"sum"``}
Specifies the reduction to apply to the output. Defaults to ``"mean"``.
- ``"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.
smooth_nr: a small constant added to the numerator to avoid zero.
smooth_dr: a small constant added to the denominator to avoid nan.
batch: whether to sum the intersection and union areas over the batch dimension before the dividing.
Defaults to False, intersection over union is computed from each item in the batch.
Raises:
TypeError: When ``other_act`` is not an ``Optional[Callable]``.
ValueError: When more than 1 of [``sigmoid=True``, ``softmax=True``, ``other_act is not None``].
Incompatible values.
"""
super().__init__(reduction=LossReduction(reduction).value)
if other_act is not None and not callable(other_act):
raise TypeError(
f'other_act must be None or callable but is {type(other_act).__name__}.'
)
if int(sigmoid) + int(softmax) + int(other_act is not None) > 1:
raise ValueError(
'Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].'
)
self.include_background = include_background
self.to_onehot_y = to_onehot_y
self.sigmoid = sigmoid
self.softmax = softmax
self.other_act = other_act
w_type = Weight(w_type)
self.w_func: 'Callable' = torch.ones_like
if w_type == Weight.SIMPLE:
self.w_func = torch.reciprocal
elif w_type == Weight.SQUARE:
self.w_func = lambda x: torch.reciprocal(x * x)
self.smooth_nr = float(smooth_nr)
self.smooth_dr = float(smooth_dr)
self.batch = batch
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
danielschulz/MONAI
|
GeneralizedDiceLoss
| false
| 1,811
|
[
"Apache-2.0"
] | 0
|
54ef6e9e700f0de3d50184c0148f953be871a58e
|
https://github.com/danielschulz/MONAI/tree/54ef6e9e700f0de3d50184c0148f953be871a58e
|
AngularPenaltySMLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class AngularPenaltySMLoss(nn.Module):
def __init__(self, in_features, out_features, loss_type='arcface', eps=
1e-07, s=None, m=None):
"""
Angular Penalty Softmax Loss
Three 'loss_types' available: ['arcface', 'sphereface', 'cosface']
These losses are described in the following papers:
ArcFace: https://arxiv.org/abs/1801.07698
SphereFace: https://arxiv.org/abs/1704.08063
CosFace/Ad Margin: https://arxiv.org/abs/1801.05599
"""
super(AngularPenaltySMLoss, self).__init__()
loss_type = loss_type.lower()
assert loss_type in ['arcface', 'sphereface', 'cosface']
if loss_type == 'arcface':
self.s = 64.0 if not s else s
self.m = 0.5 if not m else m
if loss_type == 'sphereface':
self.s = 64.0 if not s else s
self.m = 1.35 if not m else m
if loss_type == 'cosface':
self.s = 30.0 if not s else s
self.m = 0.4 if not m else m
self.loss_type = loss_type
self.in_features = in_features
self.out_features = out_features
self.fc = nn.Linear(in_features, out_features, bias=False)
self.eps = eps
def forward(self, x, labels):
"""
input shape (N, in_features)
"""
assert len(x) == len(labels)
assert torch.min(labels) >= 0
assert torch.max(labels) < self.out_features
for W in self.fc.parameters():
W = F.normalize(W, p=2, dim=1)
x = F.normalize(x, p=2, dim=1)
wf = self.fc(x)
if self.loss_type == 'cosface':
numerator = self.s * (torch.diagonal(wf.transpose(0, 1)[labels]
) - self.m)
if self.loss_type == 'arcface':
numerator = self.s * torch.cos(torch.acos(torch.clamp(torch.
diagonal(wf.transpose(0, 1)[labels]), -1.0 + self.eps, 1 -
self.eps)) + self.m)
if self.loss_type == 'sphereface':
numerator = self.s * torch.cos(self.m * torch.acos(torch.clamp(
torch.diagonal(wf.transpose(0, 1)[labels]), -1.0 + self.eps,
1 - self.eps)))
excl = torch.cat([torch.cat((wf[i, :y], wf[i, y + 1:])).unsqueeze(0
) for i, y in enumerate(labels)], dim=0)
denominator = torch.exp(numerator) + torch.sum(torch.exp(self.s *
excl), dim=1)
L = numerator - torch.log(denominator)
return -torch.mean(L)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.ones([4], dtype=torch.int64)]
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._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_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-12
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x3, tmp15, xmask)
@triton.jit
def triton_poi_fused_index_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 64
x0 = xindex % 16
x1 = xindex // 16 % 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + (x0 + 16 * tmp4 + 64 * x1), xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
@triton.jit
def triton_poi_fused_acos_add_clamp_cos_mul_2(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 80 * x1), xmask)
tmp1 = -0.9999999
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = 0.9999999
tmp4 = triton_helpers.minimum(tmp2, tmp3)
tmp5 = libdevice.acos(tmp4)
tmp6 = 0.5
tmp7 = tmp5 + tmp6
tmp8 = tl_math.cos(tmp7)
tmp9 = 64.0
tmp10 = tmp8 * tmp9
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(256)](primals_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_index_1[grid(256)](primals_2, buf1, buf2, 256,
XBLOCK=256, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4), (4, 1, 16), torch.float32)
triton_poi_fused_acos_add_clamp_cos_mul_2[grid(64)](buf2, buf3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
return buf3, reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_2, reinterpret_tensor(buf0, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (4, 4, 4), (4, 1, 80), 0)
class AngularPenaltySMLossNew(nn.Module):
def __init__(self, in_features, out_features, loss_type='arcface', eps=
1e-07, s=None, m=None):
"""
Angular Penalty Softmax Loss
Three 'loss_types' available: ['arcface', 'sphereface', 'cosface']
These losses are described in the following papers:
ArcFace: https://arxiv.org/abs/1801.07698
SphereFace: https://arxiv.org/abs/1704.08063
CosFace/Ad Margin: https://arxiv.org/abs/1801.05599
"""
super(AngularPenaltySMLossNew, self).__init__()
loss_type = loss_type.lower()
assert loss_type in ['arcface', 'sphereface', 'cosface']
if loss_type == 'arcface':
self.s = 64.0 if not s else s
self.m = 0.5 if not m else m
if loss_type == 'sphereface':
self.s = 64.0 if not s else s
self.m = 1.35 if not m else m
if loss_type == 'cosface':
self.s = 30.0 if not s else s
self.m = 0.4 if not m else m
self.loss_type = loss_type
self.in_features = in_features
self.out_features = out_features
self.fc = nn.Linear(in_features, out_features, bias=False)
self.eps = eps
def forward(self, input_0, input_1):
primals_3 = self.fc.weight
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dayoungMM/Angular-Penalty-Softmax-Losses-Pytorch
|
AngularPenaltySMLoss
| false
| 1,812
|
[
"MIT"
] | 0
|
5599f2e280b2af8d40e53727290eb797d18e7239
|
https://github.com/dayoungMM/Angular-Penalty-Softmax-Losses-Pytorch/tree/5599f2e280b2af8d40e53727290eb797d18e7239
|
ToSEG
|
from torch.autograd import Function
import math
import torch
import warnings
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.cpp_extension
def fused_leaky_relu(input, bias=None, negative_slope=0.2, scale=2 ** 0.5):
if input.device.type == 'cpu':
if bias is not None:
rest_dim = [1] * (input.ndim - bias.ndim - 1)
return F.leaky_relu(input + bias.view(1, bias.shape[0], *
rest_dim), negative_slope=0.2) * scale
else:
return F.leaky_relu(input, negative_slope=0.2) * scale
else:
return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
return k
def _init():
global _inited, _plugin
if not _inited:
sources = ['upfirdn2d.cpp', 'upfirdn2d.cu']
sources = [os.path.join(os.path.dirname(__file__), s) for s in sources]
try:
_plugin = custom_ops.get_plugin('upfirdn2d_plugin', sources=
sources, extra_cuda_cflags=['--use_fast_math'])
except:
warnings.warn(
"""Failed to build CUDA kernels for upfirdn2d. Falling back to slow reference implementation. Details:
"""
+ traceback.format_exc())
return _plugin is not None
def _get_filter_size(f):
if f is None:
return 1, 1
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
fw = f.shape[-1]
fh = f.shape[0]
with misc.suppress_tracer_warnings():
fw = int(fw)
fh = int(fh)
misc.assert_shape(f, [fh, fw][:f.ndim])
assert fw >= 1 and fh >= 1
return fw, fh
def _parse_padding(padding):
if isinstance(padding, int):
padding = [padding, padding]
assert isinstance(padding, (list, tuple))
assert all(isinstance(x, int) for x in padding)
if len(padding) == 2:
padx, pady = padding
padding = [padx, padx, pady, pady]
padx0, padx1, pady0, pady1 = padding
return padx0, padx1, pady0, pady1
def _parse_scaling(scaling):
if isinstance(scaling, int):
scaling = [scaling, scaling]
assert isinstance(scaling, (list, tuple))
assert all(isinstance(x, int) for x in scaling)
sx, sy = scaling
assert sx >= 1 and sy >= 1
return sx, sy
def _upfirdn2d_cuda(up=1, down=1, padding=0, flip_filter=False, gain=1):
"""Fast CUDA implementation of `upfirdn2d()` using custom ops.
"""
upx, upy = _parse_scaling(up)
downx, downy = _parse_scaling(down)
padx0, padx1, pady0, pady1 = _parse_padding(padding)
key = upx, upy, downx, downy, padx0, padx1, pady0, pady1, flip_filter, gain
if key in _upfirdn2d_cuda_cache:
return _upfirdn2d_cuda_cache[key]
class Upfirdn2dCuda(torch.autograd.Function):
@staticmethod
def forward(ctx, x, f):
assert isinstance(x, torch.Tensor) and x.ndim == 4
if f is None:
f = torch.ones([1, 1], dtype=torch.float32, device=x.device)
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
y = x
if f.ndim == 2:
y = _plugin.upfirdn2d(y, f, upx, upy, downx, downy, padx0,
padx1, pady0, pady1, flip_filter, gain)
else:
y = _plugin.upfirdn2d(y, f.unsqueeze(0), upx, 1, downx, 1,
padx0, padx1, 0, 0, flip_filter, np.sqrt(gain))
y = _plugin.upfirdn2d(y, f.unsqueeze(1), 1, upy, 1, downy,
0, 0, pady0, pady1, flip_filter, np.sqrt(gain))
ctx.save_for_backward(f)
ctx.x_shape = x.shape
return y
@staticmethod
def backward(ctx, dy):
f, = ctx.saved_tensors
_, _, ih, iw = ctx.x_shape
_, _, oh, ow = dy.shape
fw, fh = _get_filter_size(f)
p = [fw - padx0 - 1, iw * upx - ow * downx + padx0 - upx + 1,
fh - pady0 - 1, ih * upy - oh * downy + pady0 - upy + 1]
dx = None
df = None
if ctx.needs_input_grad[0]:
dx = _upfirdn2d_cuda(up=down, down=up, padding=p,
flip_filter=not flip_filter, gain=gain).apply(dy, f)
assert not ctx.needs_input_grad[1]
return dx, df
_upfirdn2d_cuda_cache[key] = Upfirdn2dCuda
return Upfirdn2dCuda
def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1,
impl='cuda'):
"""Pad, upsample, filter, and downsample a batch of 2D images.
Performs the following sequence of operations for each channel:
1. Upsample the image by inserting N-1 zeros after each pixel (`up`).
2. Pad the image with the specified number of zeros on each side (`padding`).
Negative padding corresponds to cropping the image.
3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it
so that the footprint of all output pixels lies within the input image.
4. Downsample the image by keeping every Nth pixel (`down`).
This sequence of operations bears close resemblance to scipy.signal.upfirdn().
The fused op is considerably more efficient than performing the same calculation
using standard PyTorch ops. It supports gradients of arbitrary order.
Args:
x: Float32/float64/float16 input tensor of the shape
`[batch_size, num_channels, in_height, in_width]`.
f: Float32 FIR filter of the shape
`[filter_height, filter_width]` (non-separable),
`[filter_taps]` (separable), or
`None` (identity).
up: Integer upsampling factor. Can be a single int or a list/tuple
`[x, y]` (default: 1).
down: Integer downsampling factor. Can be a single int or a list/tuple
`[x, y]` (default: 1).
padding: Padding with respect to the upsampled image. Can be a single number
or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
(default: 0).
flip_filter: False = convolution, True = correlation (default: False).
gain: Overall scaling factor for signal magnitude (default: 1).
impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
Returns:
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
"""
assert isinstance(x, torch.Tensor)
assert impl in ['ref', 'cuda']
if impl == 'cuda' and x.device.type == 'cuda' and _init():
return _upfirdn2d_cuda(up=up, down=down, padding=padding,
flip_filter=flip_filter, gain=gain).apply(x, f)
return _upfirdn2d_ref(x, f, up=up, down=down, padding=padding,
flip_filter=flip_filter, gain=gain)
def upsample(in_tens, out_H=64):
in_H = in_tens.shape[2]
scale_factor = 1.0 * out_H / in_H
return nn.Upsample(scale_factor=scale_factor, mode='bilinear',
align_corners=False)(in_tens)
class FusedLeakyReLUFunctionBackward(Function):
@staticmethod
def forward(ctx, grad_output, out, bias, negative_slope, scale):
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
empty = grad_output.new_empty(0)
grad_input = fused.fused_bias_act(grad_output, empty, out, 3, 1,
negative_slope, scale)
dim = [0]
if grad_input.ndim > 2:
dim += list(range(2, grad_input.ndim))
if bias:
grad_bias = grad_input.sum(dim).detach()
else:
grad_bias = empty
return grad_input, grad_bias
@staticmethod
def backward(ctx, gradgrad_input, gradgrad_bias):
out, = ctx.saved_tensors
gradgrad_out = fused.fused_bias_act(gradgrad_input, gradgrad_bias,
out, 3, 1, ctx.negative_slope, ctx.scale)
return gradgrad_out, None, None, None, None
class FusedLeakyReLUFunction(Function):
@staticmethod
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
ctx.bias = bias is not None
if bias is None:
bias = empty
out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope,
scale)
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
return out
@staticmethod
def backward(ctx, grad_output):
out, = ctx.saved_tensors
grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(
grad_output, out, ctx.bias, ctx.negative_slope, ctx.scale)
if not ctx.bias:
grad_bias = None
return grad_input, grad_bias, None, None
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, input):
if self.activation:
out = F.linear(input, self.weight * self.scale)
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
out = F.linear(input, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, input):
out = upfirdn2d(input, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=[1,
3, 3, 1]):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2 + 1
self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor
=factor)
if downsample:
factor = 2
p = len(blur_kernel) - factor + (kernel_size - 1)
pad0 = (p + 1) // 2
pad1 = p // 2
self.blur = Blur(blur_kernel, pad=(pad0, pad1))
fan_in = in_channel * kernel_size ** 2
self.scale = 1 / math.sqrt(fan_in)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, input, style):
batch, in_channel, height, width = input.shape
style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
weight = self.scale * self.weight * style
if self.demodulate:
demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-08)
weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)
weight = weight.view(batch * self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
if self.upsample:
input = input.view(1, batch * in_channel, height, width)
weight = weight.view(batch, self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
weight = weight.transpose(1, 2).reshape(batch * in_channel,
self.out_channel, self.kernel_size, self.kernel_size)
out = F.conv_transpose2d(input, weight, padding=0, stride=2,
groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
_, _, height, width = input.shape
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=0, stride=2, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
else:
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=self.padding, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
return out
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * factor ** 2
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = pad0, pad1
def forward(self, input):
out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=
self.pad)
return out
class ToSEG(nn.Module):
def __init__(self, in_channel, out_channel, style_dim, upsample=True,
blur_kernel=[1, 3, 3, 1]):
super().__init__()
if upsample:
self.upsample = Upsample(blur_kernel)
self.conv = ModulatedConv2d(in_channel, out_channel, 1, style_dim,
demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1))
def forward(self, input, style, skip=None):
out = self.conv(input, style)
out = out + self.bias
if skip is not None:
skip = self.upsample(skip)
out = out + skip
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_channel': 4, 'out_channel': 4, 'style_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Function
import math
import warnings
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 16
x0 = xindex % 4
x2 = xindex // 16
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x4, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (1, 4, 4, 1, 1), (16, 4, 1, 1, 1))
assert_size_stride(primals_6, (1, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mul_1[grid(4)](primals_3, buf1, 4, XBLOCK=4,
num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf1, primals_4, reinterpret_tensor(buf0, (4,
4), (1, 4), 0), alpha=1, beta=1, out=buf2)
del buf0
del buf1
buf3 = empty_strided_cuda((4, 4, 4, 1, 1), (16, 4, 1, 1, 1), torch.
float32)
triton_poi_fused_mul_2[grid(64)](primals_5, buf2, buf3, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf4 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf3, (16, 4,
1, 1), (4, 1, 0, 0), 0), stride=(1, 1), padding=(0, 0),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=4, bias=None)
assert_size_stride(buf4, (1, 16, 4, 4), (256, 16, 4, 1))
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused_add_3[grid(256)](buf5, primals_6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_6
return buf5, primals_4, primals_5, buf2, reinterpret_tensor(buf3, (16,
4, 1, 1), (4, 1, 1, 1), 0), reinterpret_tensor(primals_1, (1, 16, 4,
4), (256, 16, 4, 1), 0)
def fused_leaky_relu(input, bias=None, negative_slope=0.2, scale=2 ** 0.5):
if input.device.type == 'cpu':
if bias is not None:
rest_dim = [1] * (input.ndim - bias.ndim - 1)
return F.leaky_relu(input + bias.view(1, bias.shape[0], *
rest_dim), negative_slope=0.2) * scale
else:
return F.leaky_relu(input, negative_slope=0.2) * scale
else:
return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale)
def make_kernel(k):
k = torch.tensor(k, dtype=torch.float32)
if k.ndim == 1:
k = k[None, :] * k[:, None]
k /= k.sum()
return k
def _init():
global _inited, _plugin
if not _inited:
sources = ['upfirdn2d.cpp', 'upfirdn2d.cu']
sources = [os.path.join(os.path.dirname(__file__), s) for s in sources]
try:
_plugin = custom_ops.get_plugin('upfirdn2d_plugin', sources=
sources, extra_cuda_cflags=['--use_fast_math'])
except:
warnings.warn(
"""Failed to build CUDA kernels for upfirdn2d. Falling back to slow reference implementation. Details:
"""
+ traceback.format_exc())
return _plugin is not None
def _get_filter_size(f):
if f is None:
return 1, 1
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
fw = f.shape[-1]
fh = f.shape[0]
with misc.suppress_tracer_warnings():
fw = int(fw)
fh = int(fh)
misc.assert_shape(f, [fh, fw][:f.ndim])
assert fw >= 1 and fh >= 1
return fw, fh
def _parse_padding(padding):
if isinstance(padding, int):
padding = [padding, padding]
assert isinstance(padding, (list, tuple))
assert all(isinstance(x, int) for x in padding)
if len(padding) == 2:
padx, pady = padding
padding = [padx, padx, pady, pady]
padx0, padx1, pady0, pady1 = padding
return padx0, padx1, pady0, pady1
def _parse_scaling(scaling):
if isinstance(scaling, int):
scaling = [scaling, scaling]
assert isinstance(scaling, (list, tuple))
assert all(isinstance(x, int) for x in scaling)
sx, sy = scaling
assert sx >= 1 and sy >= 1
return sx, sy
def _upfirdn2d_cuda(up=1, down=1, padding=0, flip_filter=False, gain=1):
"""Fast CUDA implementation of `upfirdn2d()` using custom ops.
"""
upx, upy = _parse_scaling(up)
downx, downy = _parse_scaling(down)
padx0, padx1, pady0, pady1 = _parse_padding(padding)
key = upx, upy, downx, downy, padx0, padx1, pady0, pady1, flip_filter, gain
if key in _upfirdn2d_cuda_cache:
return _upfirdn2d_cuda_cache[key]
class Upfirdn2dCuda(torch.autograd.Function):
@staticmethod
def forward(ctx, x, f):
assert isinstance(x, torch.Tensor) and x.ndim == 4
if f is None:
f = torch.ones([1, 1], dtype=torch.float32, device=x.device)
assert isinstance(f, torch.Tensor) and f.ndim in [1, 2]
y = x
if f.ndim == 2:
y = _plugin.upfirdn2d(y, f, upx, upy, downx, downy, padx0,
padx1, pady0, pady1, flip_filter, gain)
else:
y = _plugin.upfirdn2d(y, f.unsqueeze(0), upx, 1, downx, 1,
padx0, padx1, 0, 0, flip_filter, np.sqrt(gain))
y = _plugin.upfirdn2d(y, f.unsqueeze(1), 1, upy, 1, downy,
0, 0, pady0, pady1, flip_filter, np.sqrt(gain))
ctx.save_for_backward(f)
ctx.x_shape = x.shape
return y
@staticmethod
def backward(ctx, dy):
f, = ctx.saved_tensors
_, _, ih, iw = ctx.x_shape
_, _, oh, ow = dy.shape
fw, fh = _get_filter_size(f)
p = [fw - padx0 - 1, iw * upx - ow * downx + padx0 - upx + 1,
fh - pady0 - 1, ih * upy - oh * downy + pady0 - upy + 1]
dx = None
df = None
if ctx.needs_input_grad[0]:
dx = _upfirdn2d_cuda(up=down, down=up, padding=p,
flip_filter=not flip_filter, gain=gain).apply(dy, f)
assert not ctx.needs_input_grad[1]
return dx, df
_upfirdn2d_cuda_cache[key] = Upfirdn2dCuda
return Upfirdn2dCuda
def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1,
impl='cuda'):
"""Pad, upsample, filter, and downsample a batch of 2D images.
Performs the following sequence of operations for each channel:
1. Upsample the image by inserting N-1 zeros after each pixel (`up`).
2. Pad the image with the specified number of zeros on each side (`padding`).
Negative padding corresponds to cropping the image.
3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it
so that the footprint of all output pixels lies within the input image.
4. Downsample the image by keeping every Nth pixel (`down`).
This sequence of operations bears close resemblance to scipy.signal.upfirdn().
The fused op is considerably more efficient than performing the same calculation
using standard PyTorch ops. It supports gradients of arbitrary order.
Args:
x: Float32/float64/float16 input tensor of the shape
`[batch_size, num_channels, in_height, in_width]`.
f: Float32 FIR filter of the shape
`[filter_height, filter_width]` (non-separable),
`[filter_taps]` (separable), or
`None` (identity).
up: Integer upsampling factor. Can be a single int or a list/tuple
`[x, y]` (default: 1).
down: Integer downsampling factor. Can be a single int or a list/tuple
`[x, y]` (default: 1).
padding: Padding with respect to the upsampled image. Can be a single number
or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]`
(default: 0).
flip_filter: False = convolution, True = correlation (default: False).
gain: Overall scaling factor for signal magnitude (default: 1).
impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`).
Returns:
Tensor of the shape `[batch_size, num_channels, out_height, out_width]`.
"""
assert isinstance(x, torch.Tensor)
assert impl in ['ref', 'cuda']
if impl == 'cuda' and x.device.type == 'cuda' and _init():
return _upfirdn2d_cuda(up=up, down=down, padding=padding,
flip_filter=flip_filter, gain=gain).apply(x, f)
return _upfirdn2d_ref(x, f, up=up, down=down, padding=padding,
flip_filter=flip_filter, gain=gain)
def upsample(in_tens, out_H=64):
in_H = in_tens.shape[2]
scale_factor = 1.0 * out_H / in_H
return nn.Upsample(scale_factor=scale_factor, mode='bilinear',
align_corners=False)(in_tens)
class FusedLeakyReLUFunctionBackward(Function):
@staticmethod
def forward(ctx, grad_output, out, bias, negative_slope, scale):
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
empty = grad_output.new_empty(0)
grad_input = fused.fused_bias_act(grad_output, empty, out, 3, 1,
negative_slope, scale)
dim = [0]
if grad_input.ndim > 2:
dim += list(range(2, grad_input.ndim))
if bias:
grad_bias = grad_input.sum(dim).detach()
else:
grad_bias = empty
return grad_input, grad_bias
@staticmethod
def backward(ctx, gradgrad_input, gradgrad_bias):
out, = ctx.saved_tensors
gradgrad_out = fused.fused_bias_act(gradgrad_input, gradgrad_bias,
out, 3, 1, ctx.negative_slope, ctx.scale)
return gradgrad_out, None, None, None, None
class FusedLeakyReLUFunction(Function):
@staticmethod
def forward(ctx, input, bias, negative_slope, scale):
empty = input.new_empty(0)
ctx.bias = bias is not None
if bias is None:
bias = empty
out = fused.fused_bias_act(input, bias, empty, 3, 0, negative_slope,
scale)
ctx.save_for_backward(out)
ctx.negative_slope = negative_slope
ctx.scale = scale
return out
@staticmethod
def backward(ctx, grad_output):
out, = ctx.saved_tensors
grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply(
grad_output, out, ctx.bias, ctx.negative_slope, ctx.scale)
if not ctx.bias:
grad_bias = None
return grad_input, grad_bias, None, None
class EqualLinear(nn.Module):
def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1,
activation=None):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
if bias:
self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
else:
self.bias = None
self.activation = activation
self.scale = 1 / math.sqrt(in_dim) * lr_mul
self.lr_mul = lr_mul
def forward(self, input):
if self.activation:
out = F.linear(input, self.weight * self.scale)
out = fused_leaky_relu(out, self.bias * self.lr_mul)
else:
out = F.linear(input, self.weight * self.scale, bias=self.bias *
self.lr_mul)
return out
def __repr__(self):
return (
f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})'
)
class Blur(nn.Module):
def __init__(self, kernel, pad, upsample_factor=1):
super().__init__()
kernel = make_kernel(kernel)
if upsample_factor > 1:
kernel = kernel * upsample_factor ** 2
self.register_buffer('kernel', kernel)
self.pad = pad
def forward(self, input):
out = upfirdn2d(input, self.kernel, pad=self.pad)
return out
class ModulatedConv2d(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, style_dim,
demodulate=True, upsample=False, downsample=False, blur_kernel=[1,
3, 3, 1]):
super().__init__()
self.eps = 1e-08
self.kernel_size = kernel_size
self.in_channel = in_channel
self.out_channel = out_channel
self.upsample = upsample
self.downsample = downsample
if upsample:
factor = 2
p = len(blur_kernel) - factor - (kernel_size - 1)
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2 + 1
self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor
=factor)
if downsample:
factor = 2
p = len(blur_kernel) - factor + (kernel_size - 1)
pad0 = (p + 1) // 2
pad1 = p // 2
self.blur = Blur(blur_kernel, pad=(pad0, pad1))
fan_in = in_channel * kernel_size ** 2
self.scale = 1 / math.sqrt(fan_in)
self.padding = kernel_size // 2
self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel,
kernel_size, kernel_size))
self.modulation = EqualLinear(style_dim, in_channel, bias_init=1)
self.demodulate = demodulate
def __repr__(self):
return (
f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, upsample={self.upsample}, downsample={self.downsample})'
)
def forward(self, input, style):
batch, in_channel, height, width = input.shape
style = self.modulation(style).view(batch, 1, in_channel, 1, 1)
weight = self.scale * self.weight * style
if self.demodulate:
demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-08)
weight = weight * demod.view(batch, self.out_channel, 1, 1, 1)
weight = weight.view(batch * self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
if self.upsample:
input = input.view(1, batch * in_channel, height, width)
weight = weight.view(batch, self.out_channel, in_channel, self.
kernel_size, self.kernel_size)
weight = weight.transpose(1, 2).reshape(batch * in_channel,
self.out_channel, self.kernel_size, self.kernel_size)
out = F.conv_transpose2d(input, weight, padding=0, stride=2,
groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
out = self.blur(out)
elif self.downsample:
input = self.blur(input)
_, _, height, width = input.shape
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=0, stride=2, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
else:
input = input.view(1, batch * in_channel, height, width)
out = F.conv2d(input, weight, padding=self.padding, groups=batch)
_, _, height, width = out.shape
out = out.view(batch, self.out_channel, height, width)
return out
class Upsample(nn.Module):
def __init__(self, kernel, factor=2):
super().__init__()
self.factor = factor
kernel = make_kernel(kernel) * factor ** 2
self.register_buffer('kernel', kernel)
p = kernel.shape[0] - factor
pad0 = (p + 1) // 2 + factor - 1
pad1 = p // 2
self.pad = pad0, pad1
def forward(self, input):
out = upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=
self.pad)
return out
class ToSEGNew(nn.Module):
def __init__(self, in_channel, out_channel, style_dim, upsample=True,
blur_kernel=[1, 3, 3, 1]):
super().__init__()
if upsample:
self.upsample = Upsample(blur_kernel)
self.conv = ModulatedConv2d(in_channel, out_channel, 1, style_dim,
demodulate=False)
self.bias = nn.Parameter(torch.zeros(1, out_channel, 1, 1))
def forward(self, input_0, input_1):
primals_6 = self.bias
primals_5 = self.conv.weight
primals_2 = self.conv.modulation.weight
primals_3 = self.conv.modulation.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
crobbins327/semanticGAN_WSI
|
ToSEG
| false
| 1,813
|
[
"BSD-2-Clause",
"MIT"
] | 0
|
4046ddc822f463e03952402247f79d540bf7be95
|
https://github.com/crobbins327/semanticGAN_WSI/tree/4046ddc822f463e03952402247f79d540bf7be95
|
ResidualAttentionBlock
|
import math
import torch
import torch as th
import torch.nn as nn
class LayerNorm(nn.LayerNorm):
"""
Implementation that supports fp16 inputs but fp32 gains/biases.
"""
def forward(self, x: 'th.Tensor'):
return super().forward(x.float())
class QKVMultiheadAttention(nn.Module):
def __init__(self, n_heads: 'int', n_ctx: 'int'):
super().__init__()
self.n_heads = n_heads
self.n_ctx = n_ctx
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.n_heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.n_heads, -1)
q, k, v = th.split(qkv, attn_ch, dim=-1)
weight = th.einsum('bthc,bshc->bhts', q * scale, k * scale)
wdtype = weight.dtype
weight = th.softmax(weight.float(), dim=-1).type(wdtype)
return th.einsum('bhts,bshc->bthc', weight, v).reshape(bs, n_ctx, -1)
class MultiheadAttention(nn.Module):
def __init__(self, n_ctx, width, heads):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3)
self.c_proj = nn.Linear(width, width)
self.attention = QKVMultiheadAttention(heads, n_ctx)
def forward(self, x):
x = self.c_qkv(x)
x = self.attention(x)
x = self.c_proj(x)
return x
class MLP(nn.Module):
def __init__(self, width):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * 4)
self.c_proj = nn.Linear(width * 4, width)
self.gelu = nn.GELU()
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class ResidualAttentionBlock(nn.Module):
def __init__(self, n_ctx: 'int', width: 'int', heads: 'int'):
super().__init__()
self.attn = MultiheadAttention(n_ctx, width, heads)
self.ln_1 = LayerNorm(width)
self.mlp = MLP(width)
self.ln_2 = LayerNorm(width)
def forward(self, x: 'th.Tensor'):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'n_ctx': 4, 'width': 4, '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 math
import torch as th
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_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_mul_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + (1 + 3 * x2), xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (1 + 3 * x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused__softmax_mul_3(in_ptr0, in_ptr1, in_ptr2, 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
x4 = xindex
x0 = xindex % 4
x3 = xindex // 16
tmp0 = tl.load(in_ptr0 + 3 * x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 3 * x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + (x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp7 = tl.load(in_ptr2 + (4 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp10 = tl.load(in_ptr2 + (8 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp13 = tl.load(in_ptr2 + (12 + x0 + 16 * x3), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp4 * tmp7
tmp9 = triton_helpers.maximum(tmp6, tmp8)
tmp11 = tmp4 * tmp10
tmp12 = triton_helpers.maximum(tmp9, tmp11)
tmp14 = tmp4 * tmp13
tmp15 = triton_helpers.maximum(tmp12, tmp14)
tmp16 = tmp6 - tmp15
tmp17 = tl_math.exp(tmp16)
tmp18 = tmp8 - tmp15
tmp19 = tl_math.exp(tmp18)
tmp20 = tmp17 + tmp19
tmp21 = tmp11 - tmp15
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp20 + tmp22
tmp24 = tmp14 - tmp15
tmp25 = tl_math.exp(tmp24)
tmp26 = tmp23 + tmp25
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp15, xmask)
tl.store(out_ptr2 + x4, tmp26, xmask)
@triton.jit
def triton_poi_fused__softmax_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
x4 = xindex // 4
x0 = xindex % 4
x1 = xindex // 4 % 4
x3 = xindex // 64
x2 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x1 + 4 * x0 + 16 * x3), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp4 = tmp2 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp7 = tmp5 / tmp6
tl.store(out_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), tmp7, xmask)
@triton.jit
def triton_poi_fused_clone_5(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 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (2 + 3 * x1 + 12 * x0 + 48 * x2), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (2 + 3 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x3, tmp2, 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 + (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_7(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_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr6 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp6 = tmp4 - tmp5
tmp8 = 1e-05
tmp9 = tmp7 + tmp8
tmp10 = libdevice.rsqrt(tmp9)
tmp11 = tmp6 * tmp10
tmp13 = tmp11 * tmp12
tmp15 = tmp13 + tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
@triton.jit
def triton_poi_fused_gelu_9(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp3 = 0.7071067811865476
tmp4 = tmp0 * tmp3
tmp5 = libdevice.erf(tmp4)
tmp6 = 1.0
tmp7 = tmp5 + tmp6
tmp8 = tmp2 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_10(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,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (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,))
assert_size_stride(primals_8, (4,), (1,))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (16, 4), (4, 1))
assert_size_stride(primals_11, (16,), (1,))
assert_size_stride(primals_12, (4, 16), (16, 1))
assert_size_stride(primals_13, (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_1, 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_1, buf0,
buf1, primals_2, primals_3, buf2, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del primals_2
del primals_3
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)
buf5 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_mul_2[grid(64)](buf3, primals_5, buf5, 64, XBLOCK=
64, num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 1, 4, 64), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 1, 4, 64), torch.float32)
triton_poi_fused__softmax_mul_3[grid(64)](buf3, primals_5, buf5,
buf4, buf6, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(256)](buf4, buf5, buf6, buf7, buf8,
256, XBLOCK=256, num_warps=4, num_stages=1)
buf9 = reinterpret_tensor(buf7, (4, 4, 4, 1, 1), (16, 4, 1, 1, 1), 0)
del buf7
triton_poi_fused_clone_5[grid(64)](buf3, primals_5, buf9, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf3
del primals_5
buf10 = reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 1), 0)
del buf6
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_6[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_6, (4, 4), (1, 4), 0), out=buf12)
buf13 = buf1
del buf1
buf14 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_7[grid(16)](primals_1, buf12,
primals_7, 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_8[grid(64)](primals_1, buf12,
primals_7, buf13, buf14, primals_8, primals_9, buf15, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf13
del buf14
del primals_9
buf16 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf15, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 16), (1, 4), 0),
alpha=1, beta=1, out=buf16)
del primals_11
buf17 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_gelu_9[grid(256)](buf16, buf17, 256, XBLOCK=128,
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_12, (16, 4), (1, 16), 0), out=buf18)
buf19 = reinterpret_tensor(buf18, (4, 4, 4), (16, 4, 1), 0)
del buf18
triton_poi_fused_add_10[grid(64)](buf19, primals_1, buf12,
primals_7, primals_13, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_13
return buf19, primals_1, primals_7, primals_8, reinterpret_tensor(buf2,
(16, 4), (4, 1), 0), reinterpret_tensor(buf4, (4, 4, 4, 1, 1), (16,
1, 4, 1, 1), 0), reinterpret_tensor(buf5, (4, 4, 1, 4, 1), (16, 1,
1, 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_12, primals_10, primals_6, reinterpret_tensor(buf9, (16,
1, 4), (4, 1, 1), 0), primals_4
class LayerNorm(nn.LayerNorm):
"""
Implementation that supports fp16 inputs but fp32 gains/biases.
"""
def forward(self, x: 'th.Tensor'):
return super().forward(x.float())
class QKVMultiheadAttention(nn.Module):
def __init__(self, n_heads: 'int', n_ctx: 'int'):
super().__init__()
self.n_heads = n_heads
self.n_ctx = n_ctx
def forward(self, qkv):
bs, n_ctx, width = qkv.shape
attn_ch = width // self.n_heads // 3
scale = 1 / math.sqrt(math.sqrt(attn_ch))
qkv = qkv.view(bs, n_ctx, self.n_heads, -1)
q, k, v = th.split(qkv, attn_ch, dim=-1)
weight = th.einsum('bthc,bshc->bhts', q * scale, k * scale)
wdtype = weight.dtype
weight = th.softmax(weight.float(), dim=-1).type(wdtype)
return th.einsum('bhts,bshc->bthc', weight, v).reshape(bs, n_ctx, -1)
class MultiheadAttention(nn.Module):
def __init__(self, n_ctx, width, heads):
super().__init__()
self.n_ctx = n_ctx
self.width = width
self.heads = heads
self.c_qkv = nn.Linear(width, width * 3)
self.c_proj = nn.Linear(width, width)
self.attention = QKVMultiheadAttention(heads, n_ctx)
def forward(self, x):
x = self.c_qkv(x)
x = self.attention(x)
x = self.c_proj(x)
return x
class MLP(nn.Module):
def __init__(self, width):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * 4)
self.c_proj = nn.Linear(width * 4, width)
self.gelu = nn.GELU()
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class ResidualAttentionBlockNew(nn.Module):
def __init__(self, n_ctx: 'int', width: 'int', heads: 'int'):
super().__init__()
self.attn = MultiheadAttention(n_ctx, width, heads)
self.ln_1 = LayerNorm(width)
self.mlp = MLP(width)
self.ln_2 = LayerNorm(width)
def forward(self, input_0):
primals_4 = self.attn.c_qkv.weight
primals_5 = self.attn.c_qkv.bias
primals_6 = self.attn.c_proj.weight
primals_2 = self.attn.c_proj.bias
primals_3 = self.ln_1.weight
primals_7 = self.ln_1.bias
primals_10 = self.mlp.c_fc.weight
primals_11 = self.mlp.c_fc.bias
primals_12 = self.mlp.c_proj.weight
primals_8 = self.mlp.c_proj.bias
primals_9 = self.ln_2.weight
primals_13 = self.ln_2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
dashstander/glide-text2im
|
ResidualAttentionBlock
| false
| 1,814
|
[
"MIT"
] | 0
|
58f03a871ee0567e27fccc40df98203e675a9b8e
|
https://github.com/dashstander/glide-text2im/tree/58f03a871ee0567e27fccc40df98203e675a9b8e
|
FilterResponseNorm_layer
|
import torch
import torch.nn as nn
class FilterResponseNorm_layer(nn.Module):
def __init__(self, num_filters, eps=1e-06):
super(FilterResponseNorm_layer, self).__init__()
self.eps = eps
par_shape = 1, num_filters, 1, 1
self.tau = torch.nn.Parameter(torch.zeros(par_shape))
self.beta = torch.nn.Parameter(torch.zeros(par_shape))
self.gamma = torch.nn.Parameter(torch.ones(par_shape))
def forward(self, x):
nu2 = torch.mean(torch.square(x), dim=[2, 3], keepdim=True)
x = x * 1 / torch.sqrt(nu2 + self.eps)
y = self.gamma * x + self.beta
z = torch.max(y, self.tau)
return z
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_filters': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_div_maximum_mean_mul_pow_sqrt_0(in_out_ptr0,
in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp11 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = 16.0
tmp7 = tmp5 / tmp6
tmp8 = 1e-06
tmp9 = tmp7 + tmp8
tmp10 = libdevice.sqrt(tmp9)
tmp12 = 1.0
tmp13 = tmp0 * tmp12
tmp14 = tmp13 / tmp10
tmp15 = tmp11 * tmp14
tmp17 = tmp15 + tmp16
tmp19 = triton_helpers.maximum(tmp17, tmp18)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp10, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp19, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_4, (1, 4, 1, 1), (4, 1, 1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
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
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_maximum_mean_mul_pow_sqrt_0[grid(16)](buf1,
primals_1, primals_2, primals_3, primals_4, buf2, 16, 16,
XBLOCK=8, num_warps=2, num_stages=1)
return buf2, primals_1, primals_2, primals_3, primals_4, buf1
class FilterResponseNorm_layerNew(nn.Module):
def __init__(self, num_filters, eps=1e-06):
super(FilterResponseNorm_layerNew, self).__init__()
self.eps = eps
par_shape = 1, num_filters, 1, 1
self.tau = torch.nn.Parameter(torch.zeros(par_shape))
self.beta = torch.nn.Parameter(torch.zeros(par_shape))
self.gamma = torch.nn.Parameter(torch.ones(par_shape))
def forward(self, input_0):
primals_2 = self.tau
primals_3 = self.beta
primals_4 = self.gamma
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
deebuls/pytorch-cifar
|
FilterResponseNorm_layer
| false
| 1,815
|
[
"MIT"
] | 0
|
c6d9b16eeb00418d8c4f4f4c1e97f141c1f7d198
|
https://github.com/deebuls/pytorch-cifar/tree/c6d9b16eeb00418d8c4f4f4c1e97f141c1f7d198
|
TSA_Fusion
|
import torch
import torch.utils.data
import torch.nn.functional as F
import torch.nn as nn
class TSA_Fusion(nn.Module):
""" Temporal Spatial Attention fusion module
Temporal: correlation;
Spatial: 3 pyramid levels.
"""
def __init__(self, nf=64, nframes=5, center=2):
super(TSA_Fusion, self).__init__()
self.center = center
self.tAtt_1 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.tAtt_2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.fea_fusion = nn.Conv2d(nframes * nf, nf, 1, 1, bias=True)
self.sAtt_1 = nn.Conv2d(nframes * nf, nf, 1, 1, bias=True)
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
self.avgpool = nn.AvgPool2d(3, stride=2, padding=1)
self.sAtt_2 = nn.Conv2d(nf * 2, nf, 1, 1, bias=True)
self.sAtt_3 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.sAtt_4 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.sAtt_5 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.sAtt_L1 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.sAtt_L2 = nn.Conv2d(nf * 2, nf, 3, 1, 1, bias=True)
self.sAtt_L3 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.sAtt_add_1 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.sAtt_add_2 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
def forward(self, aligned_fea):
B, N, C, H, W = aligned_fea.size()
emb_ref = self.tAtt_2(aligned_fea[:, self.center, :, :, :].clone())
emb = self.tAtt_1(aligned_fea.view(-1, C, H, W)).view(B, N, -1, H, W)
cor_l = []
for i in range(N):
emb_nbr = emb[:, i, :, :, :]
cor_tmp = torch.sum(emb_nbr * emb_ref, 1).unsqueeze(1)
cor_l.append(cor_tmp)
cor_prob = torch.sigmoid(torch.cat(cor_l, dim=1))
cor_prob = cor_prob.unsqueeze(2).repeat(1, 1, C, 1, 1).view(B, -1, H, W
)
aligned_fea = aligned_fea.view(B, -1, H, W) * cor_prob
fea = self.lrelu(self.fea_fusion(aligned_fea))
att = self.lrelu(self.sAtt_1(aligned_fea))
att_max = self.maxpool(att)
att_avg = self.avgpool(att)
att = self.lrelu(self.sAtt_2(torch.cat([att_max, att_avg], dim=1)))
att_L = self.lrelu(self.sAtt_L1(att))
att_max = self.maxpool(att_L)
att_avg = self.avgpool(att_L)
att_L = self.lrelu(self.sAtt_L2(torch.cat([att_max, att_avg], dim=1)))
att_L = self.lrelu(self.sAtt_L3(att_L))
att_L = F.interpolate(att_L, scale_factor=2, mode='bilinear',
align_corners=False)
att = self.lrelu(self.sAtt_3(att))
att = att + att_L
att = self.lrelu(self.sAtt_4(att))
att = F.interpolate(att, scale_factor=2, mode='bilinear',
align_corners=False)
att = self.sAtt_5(att)
att_add = self.sAtt_add_2(self.lrelu(self.sAtt_add_1(att)))
att = torch.sigmoid(att)
fea = fea * att * 2 + att_add
return fea
def get_inputs():
return [torch.rand([4, 5, 64, 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
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_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 1024
x1 = xindex // 1024
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2048 + x0 + 5120 * x1), None)
tl.store(out_ptr0 + x2, tmp0, None)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_per_fused_cat_mul_sum_3(in_ptr0, in_ptr1, out_ptr5, out_ptr6,
out_ptr7, out_ptr8, out_ptr9, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 64
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)
r2 = rindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 5120 * x1), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0)
tmp7 = tl.load(in_ptr0 + (1024 + x0 + 16 * r2 + 5120 * x1), xmask,
other=0.0)
tmp13 = tl.load(in_ptr0 + (2048 + x0 + 16 * r2 + 5120 * x1), xmask,
other=0.0)
tmp19 = tl.load(in_ptr0 + (3072 + x0 + 16 * r2 + 5120 * x1), xmask,
other=0.0)
tmp25 = tl.load(in_ptr0 + (4096 + x0 + 16 * r2 + 5120 * x1), 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]
tmp8 = tmp7 * tmp1
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.where(xmask, tmp9, 0)
tmp12 = tl.sum(tmp11, 1)[:, None]
tmp14 = tmp13 * tmp1
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp20 = tmp19 * tmp1
tmp21 = tl.broadcast_to(tmp20, [XBLOCK, RBLOCK])
tmp23 = tl.where(xmask, tmp21, 0)
tmp24 = tl.sum(tmp23, 1)[:, None]
tmp26 = tmp25 * tmp1
tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK])
tmp29 = tl.where(xmask, tmp27, 0)
tmp30 = tl.sum(tmp29, 1)[:, None]
tl.store(out_ptr5 + (x0 + 80 * x1), tmp6, xmask)
tl.store(out_ptr6 + (x0 + 80 * x1), tmp12, xmask)
tl.store(out_ptr7 + (x0 + 80 * x1), tmp18, xmask)
tl.store(out_ptr8 + (x0 + 80 * x1), tmp24, xmask)
tl.store(out_ptr9 + (x0 + 80 * x1), tmp30, xmask)
@triton.jit
def triton_poi_fused_mul_4(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
x0 = xindex % 16
x1 = xindex // 16 % 320
x2 = xindex // 5120
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + (x0 + 16 * (x1 // 64) + 80 * x2), None)
tmp2 = tl.sigmoid(tmp1)
tmp3 = tmp0 * tmp2
tl.store(out_ptr0 + x3, tmp3, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + 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(in_out_ptr0 + x3, tmp7, None)
@triton.jit
def triton_poi_fused_avg_pool2d_max_pool2d_with_indices_6(in_ptr0, out_ptr0,
out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 2 % 2
x0 = xindex % 2
x5 = xindex // 2
x3 = xindex // 256
x6 = xindex % 256
x7 = 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 * x5), tmp10 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp12 = 2 * x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x5), tmp16 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + 2 * x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-3 + 2 * x0 + 8 * x5), tmp23 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = 2 * x1
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x5), tmp30 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + (2 * x0 + 8 * x5), tmp33 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x5), tmp36 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = 1 + 2 * x1
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (3 + 2 * x0 + 8 * x5), tmp43 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp38)
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x5), tmp46 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x5), tmp49 & xmask,
eviction_policy='evict_last', other=float('-inf'))
tmp51 = triton_helpers.maximum(tmp50, tmp48)
tmp52 = tmp17 > tmp11
tmp53 = tl.full([1], 1, tl.int8)
tmp54 = tl.full([1], 0, tl.int8)
tmp55 = tl.where(tmp52, tmp53, tmp54)
tmp56 = tmp24 > tmp18
tmp57 = tl.full([1], 2, tl.int8)
tmp58 = tl.where(tmp56, tmp57, tmp55)
tmp59 = tmp31 > tmp25
tmp60 = tl.full([1], 3, tl.int8)
tmp61 = tl.where(tmp59, tmp60, tmp58)
tmp62 = tmp34 > tmp32
tmp63 = tl.full([1], 4, tl.int8)
tmp64 = tl.where(tmp62, tmp63, tmp61)
tmp65 = tmp37 > tmp35
tmp66 = tl.full([1], 5, tl.int8)
tmp67 = tl.where(tmp65, tmp66, tmp64)
tmp68 = tmp44 > tmp38
tmp69 = tl.full([1], 6, tl.int8)
tmp70 = tl.where(tmp68, tmp69, tmp67)
tmp71 = tmp47 > tmp45
tmp72 = tl.full([1], 7, tl.int8)
tmp73 = tl.where(tmp71, tmp72, tmp70)
tmp74 = tmp50 > tmp48
tmp75 = tl.full([1], 8, tl.int8)
tmp76 = tl.where(tmp74, tmp75, tmp73)
tmp77 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x5), tmp10 & xmask,
eviction_policy='evict_last', other=0.0)
tmp78 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x5), tmp16 & xmask,
eviction_policy='evict_last', other=0.0)
tmp79 = tmp78 + tmp77
tmp80 = tl.load(in_ptr0 + (-3 + 2 * x0 + 8 * x5), tmp23 & xmask,
eviction_policy='evict_last', other=0.0)
tmp81 = tmp80 + tmp79
tmp82 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x5), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp83 = tmp82 + tmp81
tmp84 = tl.load(in_ptr0 + (2 * x0 + 8 * x5), tmp33 & xmask,
eviction_policy='evict_last', other=0.0)
tmp85 = tmp84 + tmp83
tmp86 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x5), tmp36 & xmask,
eviction_policy='evict_last', other=0.0)
tmp87 = tmp86 + tmp85
tmp88 = tl.load(in_ptr0 + (3 + 2 * x0 + 8 * x5), tmp43 & xmask,
eviction_policy='evict_last', other=0.0)
tmp89 = tmp88 + tmp87
tmp90 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x5), tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp91 = tmp90 + tmp89
tmp92 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x5), tmp49 & xmask,
eviction_policy='evict_last', other=0.0)
tmp93 = tmp92 + tmp91
tmp94 = 1 + -2 * x0 + -2 * x1 + (5 * (5 <= 2 + 2 * x0) + (2 + 2 * x0) *
(2 + 2 * x0 < 5)) * (5 * (5 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 *
x1 < 5)) + -2 * x0 * (5 * (5 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 *
x1 < 5)) + -2 * x1 * (5 * (5 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 *
x0 < 5)) + 4 * x0 * x1 + (5 * (5 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 +
2 * x0 < 5)) + (5 * (5 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 5)
)
tmp95 = tmp93 / tmp94
tl.store(out_ptr0 + (x6 + 512 * x3), tmp51, xmask)
tl.store(out_ptr1 + x7, tmp76, xmask)
tl.store(out_ptr2 + (x6 + 512 * x3), tmp95, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_7(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
x3 = xindex
x1 = xindex // 4 % 64
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_max_pool2d_with_indices_8(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
x2 = xindex
x0 = xindex % 64
x1 = xindex // 64
tmp0 = tl.full([1], -1, tl.int64)
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 2, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = tmp5 & tmp5
tmp7 = tl.load(in_ptr0 + (-3 + 4 * x2), tmp6 & xmask, eviction_policy=
'evict_last', other=float('-inf'))
tmp8 = tmp1 >= tmp1
tmp9 = tmp1 < tmp3
tmp10 = tmp8 & tmp9
tmp11 = tmp5 & tmp10
tmp12 = tl.load(in_ptr0 + (-2 + 4 * x2), tmp11 & xmask, eviction_policy
='evict_last', other=float('-inf'))
tmp13 = triton_helpers.maximum(tmp12, tmp7)
tmp14 = tl.full([1], 1, tl.int64)
tmp15 = tmp14 >= tmp1
tmp16 = tmp14 < tmp3
tmp17 = tmp15 & tmp16
tmp18 = tmp5 & tmp17
tmp19 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp18 & xmask, eviction_policy
='evict_last', other=float('-inf'))
tmp20 = triton_helpers.maximum(tmp19, tmp13)
tmp21 = tmp10 & tmp5
tmp22 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp21 & xmask, eviction_policy
='evict_last', other=float('-inf'))
tmp23 = triton_helpers.maximum(tmp22, tmp20)
tmp24 = tmp10 & tmp10
tmp25 = tl.load(in_ptr0 + 4 * x2, tmp24 & xmask, eviction_policy=
'evict_last', other=float('-inf'))
tmp26 = triton_helpers.maximum(tmp25, tmp23)
tmp27 = tmp10 & tmp17
tmp28 = tl.load(in_ptr0 + (1 + 4 * x2), tmp27 & xmask, eviction_policy=
'evict_last', other=float('-inf'))
tmp29 = triton_helpers.maximum(tmp28, tmp26)
tmp30 = tmp17 & tmp5
tmp31 = tl.load(in_ptr0 + (1 + 4 * x2), tmp30 & xmask, eviction_policy=
'evict_last', other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp29)
tmp33 = tmp17 & tmp10
tmp34 = tl.load(in_ptr0 + (2 + 4 * x2), tmp33 & xmask, eviction_policy=
'evict_last', other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp17 & tmp17
tmp37 = tl.load(in_ptr0 + (3 + 4 * x2), tmp36 & xmask, eviction_policy=
'evict_last', other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = tmp12 > tmp7
tmp40 = tl.full([1], 1, tl.int8)
tmp41 = tl.full([1], 0, tl.int8)
tmp42 = tl.where(tmp39, tmp40, tmp41)
tmp43 = tmp19 > tmp13
tmp44 = tl.full([1], 2, tl.int8)
tmp45 = tl.where(tmp43, tmp44, tmp42)
tmp46 = tmp22 > tmp20
tmp47 = tl.full([1], 3, tl.int8)
tmp48 = tl.where(tmp46, tmp47, tmp45)
tmp49 = tmp25 > tmp23
tmp50 = tl.full([1], 4, tl.int8)
tmp51 = tl.where(tmp49, tmp50, tmp48)
tmp52 = tmp28 > tmp26
tmp53 = tl.full([1], 5, tl.int8)
tmp54 = tl.where(tmp52, tmp53, tmp51)
tmp55 = tmp31 > tmp29
tmp56 = tl.full([1], 6, tl.int8)
tmp57 = tl.where(tmp55, tmp56, tmp54)
tmp58 = tmp34 > tmp32
tmp59 = tl.full([1], 7, tl.int8)
tmp60 = tl.where(tmp58, tmp59, tmp57)
tmp61 = tmp37 > tmp35
tmp62 = tl.full([1], 8, tl.int8)
tmp63 = tl.where(tmp61, tmp62, tmp60)
tmp64 = tl.load(in_ptr0 + (-3 + 4 * x2), tmp6 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp65 = tl.load(in_ptr0 + (-2 + 4 * x2), tmp11 & xmask, eviction_policy
='evict_last', other=0.0)
tmp66 = tmp65 + tmp64
tmp67 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp18 & xmask, eviction_policy
='evict_last', other=0.0)
tmp68 = tmp67 + tmp66
tmp69 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp21 & xmask, eviction_policy
='evict_last', other=0.0)
tmp70 = tmp69 + tmp68
tmp71 = tl.load(in_ptr0 + 4 * x2, tmp24 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp72 = tmp71 + tmp70
tmp73 = tl.load(in_ptr0 + (1 + 4 * x2), tmp27 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp74 = tmp73 + tmp72
tmp75 = tl.load(in_ptr0 + (1 + 4 * x2), tmp30 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp76 = tmp75 + tmp74
tmp77 = tl.load(in_ptr0 + (2 + 4 * x2), tmp33 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp78 = tmp77 + tmp76
tmp79 = tl.load(in_ptr0 + (3 + 4 * x2), tmp36 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp80 = tmp79 + tmp78
tmp81 = tl.full([1], 9, tl.int32)
tmp82 = tmp80 / tmp81
tl.store(out_ptr0 + (x0 + 128 * x1), tmp38, xmask)
tl.store(out_ptr1 + x2, tmp63, xmask)
tl.store(out_ptr2 + (x0 + 128 * x1), tmp82, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_9(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x2, tmp7, xmask)
@triton.jit
def triton_poi_fused__to_copy_10(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 2
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_11(out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 2
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], 0, 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_12(out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 2
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_leaky_relu_backward_mul_sub_13(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, in_ptr8, in_ptr9, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 2 % 2
x0 = xindex % 2
x5 = xindex // 4
x2 = xindex // 4 % 64
x6 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr6 + x6, xmask)
tmp26 = tl.load(in_ptr7 + x2, xmask, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp36 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp1 = tl.full([XBLOCK], 1, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tl.where(tmp3, tmp2, tmp0)
tmp6 = tmp5 + tmp1
tmp7 = tmp5 < 0
tl.where(tmp7, tmp6, tmp5)
tmp11 = tmp9 + tmp10
tmp12 = 0.0
tmp13 = tmp11 > tmp12
tmp14 = 0.1
tmp15 = tmp11 * tmp14
tmp16 = tl.where(tmp13, tmp11, tmp15)
tmp18 = tmp17 + tmp1
tmp19 = tmp17 < 0
tl.where(tmp19, tmp18, tmp17)
tmp21 = tmp16 - tmp16
tmp23 = tmp21 * tmp22
tmp24 = tmp16 + tmp23
tmp27 = tmp25 + tmp26
tmp28 = tmp27 > tmp12
tmp29 = tmp27 * tmp14
tmp30 = tl.where(tmp28, tmp27, tmp29)
tmp32 = tmp31 + tmp1
tmp33 = tmp31 < 0
tl.where(tmp33, tmp32, tmp31)
tmp35 = tmp24 - tmp24
tmp37 = tmp35 * tmp36
tmp38 = tmp24 + tmp37
tmp39 = tmp30 + tmp38
tmp40 = tmp30 > tmp12
tl.store(in_out_ptr0 + x6, tmp39, xmask)
tl.store(out_ptr0 + x6, tmp40, xmask)
@triton.jit
def triton_poi_fused__to_copy_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)
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_15(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_16(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_17(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5,
in_ptr6, in_ptr7, 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 % 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')
tmp10 = tl.load(in_ptr3 + x2, None, eviction_policy='evict_last')
tmp17 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr5 + x0, None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr6 + x1, None, eviction_policy='evict_last')
tmp48 = tl.load(in_ptr7 + 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')
tmp11 = tmp9 + tmp10
tmp12 = 0.0
tmp13 = tmp11 > tmp12
tmp14 = 0.1
tmp15 = tmp11 * tmp14
tmp16 = tl.where(tmp13, tmp11, tmp15)
tmp18 = tmp17 + tmp1
tmp19 = tmp17 < 0
tmp20 = tl.where(tmp19, tmp18, tmp17)
tmp21 = tl.load(in_ptr2 + (tmp20 + 2 * tmp4 + 4 * x6), None,
eviction_policy='evict_last')
tmp22 = tmp21 + tmp10
tmp23 = tmp22 > tmp12
tmp24 = tmp22 * tmp14
tmp25 = tl.where(tmp23, tmp22, tmp24)
tmp26 = tmp25 - tmp16
tmp28 = tmp26 * tmp27
tmp29 = tmp16 + tmp28
tmp31 = tmp30 + tmp1
tmp32 = tmp30 < 0
tmp33 = tl.where(tmp32, tmp31, tmp30)
tmp34 = tl.load(in_ptr2 + (tmp8 + 2 * tmp33 + 4 * x6), None,
eviction_policy='evict_last')
tmp35 = tmp34 + tmp10
tmp36 = tmp35 > tmp12
tmp37 = tmp35 * tmp14
tmp38 = tl.where(tmp36, tmp35, tmp37)
tmp39 = tl.load(in_ptr2 + (tmp20 + 2 * tmp33 + 4 * x6), None,
eviction_policy='evict_last')
tmp40 = tmp39 + tmp10
tmp41 = tmp40 > tmp12
tmp42 = tmp40 * tmp14
tmp43 = tl.where(tmp41, tmp40, tmp42)
tmp44 = tmp43 - tmp38
tmp45 = tmp44 * tmp27
tmp46 = tmp38 + tmp45
tmp47 = tmp46 - tmp29
tmp49 = tmp47 * tmp48
tmp50 = tmp29 + tmp49
tl.store(in_out_ptr0 + x4, tmp50, None)
@triton.jit
def triton_poi_fused_add_convolution_leaky_relu_mul_sigmoid_18(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + x3, None)
tmp13 = tl.load(in_out_ptr1 + x3, None)
tmp14 = tl.load(in_ptr2 + 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)
tmp9 = tl.sigmoid(tmp8)
tmp10 = tmp7 * tmp9
tmp11 = 2.0
tmp12 = tmp10 * tmp11
tmp15 = tmp13 + tmp14
tmp16 = tmp12 + tmp15
tl.store(in_out_ptr0 + x3, tmp2, None)
tl.store(in_out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_19(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp8 = tmp7 > tmp3
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_20(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.1
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp8 = tmp7 > tmp3
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27) = args
args.clear()
assert_size_stride(primals_1, (4, 5, 64, 4, 4), (5120, 1024, 16, 4, 1))
assert_size_stride(primals_2, (64, 64, 3, 3), (576, 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, (64, 320, 1, 1), (320, 1, 1, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (64, 320, 1, 1), (320, 1, 1, 1))
assert_size_stride(primals_9, (64,), (1,))
assert_size_stride(primals_10, (64, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_11, (64,), (1,))
assert_size_stride(primals_12, (64, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (64, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_15, (64,), (1,))
assert_size_stride(primals_16, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_17, (64,), (1,))
assert_size_stride(primals_18, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_19, (64,), (1,))
assert_size_stride(primals_20, (64, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_21, (64,), (1,))
assert_size_stride(primals_22, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_23, (64,), (1,))
assert_size_stride(primals_24, (64, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_25, (64,), (1,))
assert_size_stride(primals_26, (64, 64, 1, 1), (64, 1, 1, 1))
assert_size_stride(primals_27, (64,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 64, 4, 4), (1024, 16, 4, 1), torch.
float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(4096)](primals_1, buf0, 4096, XBLOCK=
128, num_warps=4, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 64, 4, 4), (1024, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(4096)](buf2, primals_3, 4096,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
buf3 = extern_kernels.convolution(reinterpret_tensor(primals_1, (20,
64, 4, 4), (1024, 16, 4, 1), 0), primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (20, 64, 4, 4), (1024, 16, 4, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_2[grid(20480)](buf4, primals_5, 20480,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf15 = empty_strided_cuda((4, 5, 4, 4), (80, 16, 4, 1), torch.float32)
buf10 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 0)
buf11 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 16)
buf12 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 32)
buf13 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 48)
buf14 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 64)
triton_per_fused_cat_mul_sum_3[grid(64)](buf4, buf2, buf10, buf11,
buf12, buf13, buf14, 64, 64, XBLOCK=32, num_warps=8, num_stages=1)
buf16 = empty_strided_cuda((4, 320, 4, 4), (5120, 16, 4, 1), torch.
float32)
triton_poi_fused_mul_4[grid(20480)](primals_1, buf15, buf16, 20480,
XBLOCK=256, num_warps=4, num_stages=1)
buf17 = extern_kernels.convolution(buf16, primals_6, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 64, 4, 4), (1024, 16, 4, 1))
buf19 = extern_kernels.convolution(buf16, primals_8, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 64, 4, 4), (1024, 16, 4, 1))
buf20 = buf19
del buf19
triton_poi_fused_convolution_leaky_relu_5[grid(4096)](buf20,
primals_9, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf24 = empty_strided_cuda((4, 128, 2, 2), (512, 4, 2, 1), torch.
float32)
buf21 = reinterpret_tensor(buf24, (4, 64, 2, 2), (512, 4, 2, 1), 0)
buf22 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.int8)
buf23 = reinterpret_tensor(buf24, (4, 64, 2, 2), (512, 4, 2, 1), 256)
triton_poi_fused_avg_pool2d_max_pool2d_with_indices_6[grid(1024)](buf20
, buf21, buf22, buf23, 1024, XBLOCK=128, num_warps=4, num_stages=1)
buf25 = extern_kernels.convolution(buf24, primals_10, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf25, (4, 64, 2, 2), (256, 4, 2, 1))
buf26 = buf25
del buf25
triton_poi_fused_convolution_leaky_relu_7[grid(1024)](buf26,
primals_11, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_11
buf27 = extern_kernels.convolution(buf26, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 64, 2, 2), (256, 4, 2, 1))
buf28 = buf27
del buf27
triton_poi_fused_convolution_leaky_relu_7[grid(1024)](buf28,
primals_13, 1024, XBLOCK=256, num_warps=4, num_stages=1)
del primals_13
buf32 = empty_strided_cuda((4, 128, 1, 1), (128, 1, 1, 1), torch.
float32)
buf29 = reinterpret_tensor(buf32, (4, 64, 1, 1), (128, 1, 1, 1), 0)
buf30 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 1, 1), torch.int8)
buf31 = reinterpret_tensor(buf32, (4, 64, 1, 1), (128, 1, 1, 1), 64)
triton_poi_fused_avg_pool2d_max_pool2d_with_indices_8[grid(256)](buf28,
buf29, buf30, buf31, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf33 = extern_kernels.convolution(buf32, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf33, (4, 64, 1, 1), (64, 1, 1, 1))
buf34 = buf33
del buf33
triton_poi_fused_convolution_leaky_relu_9[grid(256)](buf34,
primals_15, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_15
buf35 = extern_kernels.convolution(buf34, primals_16, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf35, (4, 64, 1, 1), (64, 1, 1, 1))
buf36 = empty_strided_cuda((2, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_10[grid(2)](buf36, 2, XBLOCK=2, num_warps
=1, num_stages=1)
buf37 = empty_strided_cuda((2, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_11[grid(2)](buf37, 2, XBLOCK=2,
num_warps=1, num_stages=1)
buf38 = empty_strided_cuda((2,), (1,), torch.int64)
triton_poi_fused__to_copy_10[grid(2)](buf38, 2, XBLOCK=2, num_warps
=1, num_stages=1)
buf39 = empty_strided_cuda((2,), (1,), torch.int64)
triton_poi_fused_add_clamp_11[grid(2)](buf39, 2, XBLOCK=2,
num_warps=1, num_stages=1)
buf40 = empty_strided_cuda((2,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_12[grid(2)](buf40,
2, XBLOCK=2, num_warps=1, num_stages=1)
buf42 = empty_strided_cuda((2, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_12[grid(2)](buf42,
2, XBLOCK=2, num_warps=1, num_stages=1)
buf43 = extern_kernels.convolution(buf26, primals_18, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf43, (4, 64, 2, 2), (256, 4, 2, 1))
buf41 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.float32
)
buf44 = buf41
del buf41
buf62 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.bool)
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_leaky_relu_backward_mul_sub_13[
grid(1024)](buf44, buf36, buf38, buf35, primals_17, buf39,
buf40, buf43, primals_19, buf37, buf42, buf62, 1024, XBLOCK=128,
num_warps=4, num_stages=1)
del buf43
del primals_19
buf45 = extern_kernels.convolution(buf44, primals_20, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf45, (4, 64, 2, 2), (256, 4, 2, 1))
buf46 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused__to_copy_14[grid(4)](buf46, 4, XBLOCK=4, num_warps
=1, num_stages=1)
buf47 = empty_strided_cuda((4, 1), (1, 1), torch.int64)
triton_poi_fused_add_clamp_15[grid(4)](buf47, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf48 = empty_strided_cuda((4,), (1,), torch.int64)
triton_poi_fused__to_copy_14[grid(4)](buf48, 4, XBLOCK=4, num_warps
=1, num_stages=1)
buf49 = empty_strided_cuda((4,), (1,), torch.int64)
triton_poi_fused_add_clamp_15[grid(4)](buf49, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf50 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_16[grid(4)](buf50,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf52 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
triton_poi_fused__to_copy_add_arange_clamp_mul_sub_16[grid(4)](buf52,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf53 = empty_strided_cuda((4, 64, 4, 4), (1024, 16, 4, 1), torch.
float32)
buf54 = buf53
del buf53
triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_17[
grid(4096)](buf54, buf46, buf48, buf45, primals_21, buf49,
buf50, buf47, buf52, 4096, XBLOCK=128, num_warps=4, num_stages=1)
buf55 = extern_kernels.convolution(buf54, primals_22, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf55, (4, 64, 4, 4), (1024, 16, 4, 1))
buf56 = buf55
del buf55
triton_poi_fused_convolution_1[grid(4096)](buf56, primals_23, 4096,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_23
buf57 = extern_kernels.convolution(buf56, primals_24, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf57, (4, 64, 4, 4), (1024, 16, 4, 1))
buf58 = buf57
del buf57
triton_poi_fused_convolution_leaky_relu_5[grid(4096)](buf58,
primals_25, 4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_25
buf59 = extern_kernels.convolution(buf58, primals_26, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf59, (4, 64, 4, 4), (1024, 16, 4, 1))
buf18 = buf17
del buf17
buf60 = buf59
del buf59
triton_poi_fused_add_convolution_leaky_relu_mul_sigmoid_18[grid(4096)](
buf18, buf60, primals_7, buf56, primals_27, 4096, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_27
del primals_7
buf61 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.bool)
triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_19[grid
(1024)](buf45, primals_21, buf61, 1024, XBLOCK=256, num_warps=4,
num_stages=1)
del buf45
del primals_21
buf63 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 1, 1), torch.bool)
triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_20[grid
(256)](buf35, primals_17, buf63, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del buf35
del primals_17
return (buf60, primals_1, primals_2, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, primals_16, primals_18,
primals_20, primals_22, primals_24, primals_26, buf0, buf2,
reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 0),
reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 1024),
reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 2048),
reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 3072),
reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 4096),
buf15, buf16, buf18, buf20, buf22, buf24, buf26, buf28, buf30,
buf32, buf34, buf36, buf37, buf38, buf39, buf40, buf42, buf44,
buf46, buf47, buf48, buf49, buf50, buf52, buf54, buf56, buf58,
buf61, buf62, buf63)
class TSA_FusionNew(nn.Module):
""" Temporal Spatial Attention fusion module
Temporal: correlation;
Spatial: 3 pyramid levels.
"""
def __init__(self, nf=64, nframes=5, center=2):
super(TSA_FusionNew, self).__init__()
self.center = center
self.tAtt_1 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.tAtt_2 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.fea_fusion = nn.Conv2d(nframes * nf, nf, 1, 1, bias=True)
self.sAtt_1 = nn.Conv2d(nframes * nf, nf, 1, 1, bias=True)
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
self.avgpool = nn.AvgPool2d(3, stride=2, padding=1)
self.sAtt_2 = nn.Conv2d(nf * 2, nf, 1, 1, bias=True)
self.sAtt_3 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.sAtt_4 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.sAtt_5 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.sAtt_L1 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.sAtt_L2 = nn.Conv2d(nf * 2, nf, 3, 1, 1, bias=True)
self.sAtt_L3 = nn.Conv2d(nf, nf, 3, 1, 1, bias=True)
self.sAtt_add_1 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.sAtt_add_2 = nn.Conv2d(nf, nf, 1, 1, bias=True)
self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)
def forward(self, input_0):
primals_2 = self.tAtt_1.weight
primals_3 = self.tAtt_1.bias
primals_4 = self.tAtt_2.weight
primals_5 = self.tAtt_2.bias
primals_6 = self.fea_fusion.weight
primals_7 = self.fea_fusion.bias
primals_8 = self.sAtt_1.weight
primals_9 = self.sAtt_1.bias
primals_10 = self.sAtt_2.weight
primals_11 = self.sAtt_2.bias
primals_16 = self.sAtt_3.weight
primals_13 = self.sAtt_3.bias
primals_12 = self.sAtt_4.weight
primals_15 = self.sAtt_4.bias
primals_18 = self.sAtt_5.weight
primals_17 = self.sAtt_5.bias
primals_20 = self.sAtt_L1.weight
primals_19 = self.sAtt_L1.bias
primals_14 = self.sAtt_L2.weight
primals_21 = self.sAtt_L2.bias
primals_22 = self.sAtt_L3.weight
primals_23 = self.sAtt_L3.bias
primals_24 = self.sAtt_add_1.weight
primals_25 = self.sAtt_add_1.bias
primals_26 = self.sAtt_add_2.weight
primals_27 = self.sAtt_add_2.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])
return output[0]
|
creeper121386/EDVR-modified
|
TSA_Fusion
| false
| 1,816
|
[
"Apache-2.0"
] | 0
|
3fa565b99811e8f84f6ea3793090614606382332
|
https://github.com/creeper121386/EDVR-modified/tree/3fa565b99811e8f84f6ea3793090614606382332
|
ps_FNNDenoiser
|
from torch.nn import Module
import torch
from torch.nn import Linear
from torch.nn.init import xavier_normal_
from torch.nn.functional import relu
class ps_FNNDenoiser(Module):
def __init__(self, input_dim):
"""The FNN enc and FNN dec of the Denoiser.
:param input_dim: The input dimensionality.
:type input_dim: int
"""
super(ps_FNNDenoiser, self).__init__()
self._input_dim = input_dim
self.fnn_enc = Linear(self._input_dim, int(self._input_dim / 2))
self.fnn_dec = Linear(int(self._input_dim / 2), self._input_dim)
self.initialize_module()
def initialize_module(self):
"""Manual weight/bias initialization.
"""
xavier_normal_(self.fnn_enc.weight)
self.fnn_enc.bias.data.zero_()
xavier_normal_(self.fnn_dec.weight)
self.fnn_dec.bias.data.zero_()
def forward(self, v_j_filt_prime):
"""The forward pass.
:param v_j_filt_prime: The output of the Masker.
:type v_j_filt_prime: torch.autograd.variable.Variable
:return: The output of the Denoiser
:rtype: torch.autograd.variable.Variable
"""
fnn_enc_output = relu(self.fnn_enc(v_j_filt_prime))
fnn_dec_output = relu(self.fnn_dec(fnn_enc_output))
v_j_filt = fnn_dec_output.mul(v_j_filt_prime)
return v_j_filt
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch.nn import Module
from torch.nn import Linear
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_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_mul_relu_threshold_backward_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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = tmp4 * tmp5
tmp7 = 0.0
tmp8 = tmp4 <= tmp7
tl.store(out_ptr0 + x2, tmp6, xmask)
tl.store(out_ptr1 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (2, 4), (4, 1))
assert_size_stride(primals_2, (2,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 2), (2, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 2), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 2), (32, 8, 2, 1), 0)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(128)](buf1,
primals_2, buf5, 128, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 2), (2, 1), 0),
reinterpret_tensor(primals_4, (2, 4), (1, 2), 0), out=buf2)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_mul_relu_threshold_backward_1[grid(256)](buf2,
primals_5, primals_3, buf3, buf4, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del primals_5
return buf3, primals_3, reinterpret_tensor(buf1, (64, 2), (2, 1), 0
), buf4, primals_4, buf5
class ps_FNNDenoiserNew(Module):
def __init__(self, input_dim):
"""The FNN enc and FNN dec of the Denoiser.
:param input_dim: The input dimensionality.
:type input_dim: int
"""
super(ps_FNNDenoiserNew, self).__init__()
self._input_dim = input_dim
self.fnn_enc = Linear(self._input_dim, int(self._input_dim / 2))
self.fnn_dec = Linear(int(self._input_dim / 2), self._input_dim)
self.initialize_module()
def initialize_module(self):
"""Manual weight/bias initialization.
"""
xavier_normal_(self.fnn_enc.weight)
self.fnn_enc.bias.data.zero_()
xavier_normal_(self.fnn_dec.weight)
self.fnn_dec.bias.data.zero_()
def forward(self, input_0):
primals_1 = self.fnn_enc.weight
primals_2 = self.fnn_enc.bias
primals_4 = self.fnn_dec.weight
primals_5 = self.fnn_dec.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
ddcas/singing-language-identification
|
ps_FNNDenoiser
| false
| 1,817
|
[
"MIT"
] | 0
|
d104419b196d56d4de37cff47c32e88e28c58690
|
https://github.com/ddcas/singing-language-identification/tree/d104419b196d56d4de37cff47c32e88e28c58690
|
RegularizedLinear
|
import torch
import torch.nn as nn
class RegularizedLinear(nn.Linear):
def __init__(self, *args, ar_weight=0.001, l1_weight=0.001, **kwargs):
super(RegularizedLinear, self).__init__(*args, **kwargs)
self.ar_weight = ar_weight
self.l1_weight = l1_weight
self._losses = {}
def forward(self, input):
output = super(RegularizedLinear, self).forward(input)
self._losses['activity_regularization'] = (output * output).sum(
) * self.ar_weight
self._losses['l1_weight_regularization'] = torch.abs(self.weight).sum(
) * self.l1_weight
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_mul_sum_0(in_out_ptr0, in_ptr0, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [RBLOCK])
tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0))
tmp5 = 0.001
tmp6 = tmp4 * tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp6, None)
@triton.jit
def triton_per_fused_abs_mul_sum_1(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl_math.abs(tmp0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.sum(tmp2, 1)[:, None]
tmp5 = 0.001
tmp6 = tmp4 * tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp6, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
buf1 = empty_strided_cuda((), (), torch.float32)
buf3 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(1)](buf3, buf0, 1, 256, num_warps=2,
num_stages=1)
buf2 = empty_strided_cuda((), (), torch.float32)
buf4 = buf2
del buf2
triton_per_fused_abs_mul_sum_1[grid(1)](buf4, primals_1, 1, 16,
XBLOCK=1, num_warps=2, num_stages=1)
return reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf3, buf4, primals_1, reinterpret_tensor(primals_3, (64, 4), (4,
1), 0), reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
class RegularizedLinearNew(nn.Linear):
def __init__(self, *args, ar_weight=0.001, l1_weight=0.001, **kwargs):
super(RegularizedLinearNew, self).__init__(*args, **kwargs)
self.ar_weight = ar_weight
self.l1_weight = l1_weight
self._losses = {}
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dearkafka/inferno
|
RegularizedLinear
| false
| 1,818
|
[
"Apache-2.0"
] | 0
|
e9e3b863fd1fc97cf94d08ac6b4f8df7665f996a
|
https://github.com/dearkafka/inferno/tree/e9e3b863fd1fc97cf94d08ac6b4f8df7665f996a
|
SorensenDiceLoss
|
import torch
import torch.nn as nn
from torch.autograd import Variable
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
def flatten_samples(tensor_or_variable):
"""
Flattens a tensor or a variable such that the channel axis is first and the sample axis
is second. The shapes are transformed as follows:
(N, C, H, W) --> (C, N * H * W)
(N, C, D, H, W) --> (C, N * D * H * W)
(N, C) --> (C, N)
The input must be atleast 2d.
"""
assert_(tensor_or_variable.dim() >= 2,
'Tensor or variable must be atleast 2D. Got one of dim {}.'.format(
tensor_or_variable.dim()), ShapeError)
num_channels = tensor_or_variable.size(1)
permute_axes = list(range(tensor_or_variable.dim()))
permute_axes[0], permute_axes[1] = permute_axes[1], permute_axes[0]
permuted = tensor_or_variable.permute(*permute_axes).contiguous()
flattened = permuted.view(num_channels, -1)
return flattened
class ShapeError(ValueError):
pass
class SorensenDiceLoss(nn.Module):
"""
Computes a loss scalar, which when minimized maximizes the Sorensen-Dice similarity
between the input and the target. For both inputs and targets it must be the case that
`input_or_target.size(1) = num_channels`.
"""
def __init__(self, weight=None, channelwise=True, eps=1e-06):
"""
Parameters
----------
weight : torch.FloatTensor or torch.cuda.FloatTensor
Class weights. Applies only if `channelwise = True`.
channelwise : bool
Whether to apply the loss channelwise and sum the results (True)
or to apply it on all channels jointly (False).
"""
super(SorensenDiceLoss, self).__init__()
self.register_buffer('weight', weight)
self.channelwise = channelwise
self.eps = eps
def forward(self, input, target):
if not self.channelwise:
numerator = (input * target).sum()
denominator = (input * input).sum() + (target * target).sum()
loss = -2.0 * (numerator / denominator.clamp(min=self.eps))
else:
input = flatten_samples(input)
target = flatten_samples(target)
numerator = (input * target).sum(-1)
denominator = (input * input).sum(-1) + (target * target).sum(-1)
channelwise_loss = -2 * (numerator / denominator.clamp(min=self
.eps))
if self.weight is not None:
if channelwise_loss.dim() == 2:
channelwise_loss = channelwise_loss.squeeze(1)
weight = Variable(self.weight, requires_grad=False)
channelwise_loss = weight * channelwise_loss
loss = channelwise_loss.sum()
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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 + (16 * x0 + 64 * (r1 // 16) + r1 % 16), xmask,
other=0.0)
tmp1 = tl.load(in_ptr1 + (16 * x0 + 64 * (r1 // 16) + r1 % 16), xmask,
other=0.0)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
tmp7 = tmp0 * tmp0
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.where(xmask, tmp8, 0)
tmp11 = tl.sum(tmp10, 1)[:, None]
tmp12 = tmp1 * tmp1
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp11, xmask)
tl.store(out_ptr2 + x0, tmp16, xmask)
@triton.jit
def triton_per_fused_add_clamp_div_mul_sum_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tl.load(in_ptr2 + r0, None)
tmp3 = tmp1 + tmp2
tmp4 = 1e-06
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp6 = tmp0 / tmp5
tmp7 = -2.0
tmp8 = tmp6 * tmp7
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.sum(tmp9, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp11, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
buf2 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_sum_0[grid(4)](arg0_1, arg1_1, buf0, buf1,
buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf3 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_add_clamp_div_mul_sum_1[grid(1)](buf0, buf1, buf2,
buf3, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf2
return buf3,
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
def flatten_samples(tensor_or_variable):
"""
Flattens a tensor or a variable such that the channel axis is first and the sample axis
is second. The shapes are transformed as follows:
(N, C, H, W) --> (C, N * H * W)
(N, C, D, H, W) --> (C, N * D * H * W)
(N, C) --> (C, N)
The input must be atleast 2d.
"""
assert_(tensor_or_variable.dim() >= 2,
'Tensor or variable must be atleast 2D. Got one of dim {}.'.format(
tensor_or_variable.dim()), ShapeError)
num_channels = tensor_or_variable.size(1)
permute_axes = list(range(tensor_or_variable.dim()))
permute_axes[0], permute_axes[1] = permute_axes[1], permute_axes[0]
permuted = tensor_or_variable.permute(*permute_axes).contiguous()
flattened = permuted.view(num_channels, -1)
return flattened
class ShapeError(ValueError):
pass
class SorensenDiceLossNew(nn.Module):
"""
Computes a loss scalar, which when minimized maximizes the Sorensen-Dice similarity
between the input and the target. For both inputs and targets it must be the case that
`input_or_target.size(1) = num_channels`.
"""
def __init__(self, weight=None, channelwise=True, eps=1e-06):
"""
Parameters
----------
weight : torch.FloatTensor or torch.cuda.FloatTensor
Class weights. Applies only if `channelwise = True`.
channelwise : bool
Whether to apply the loss channelwise and sum the results (True)
or to apply it on all channels jointly (False).
"""
super(SorensenDiceLossNew, self).__init__()
self.register_buffer('weight', weight)
self.channelwise = channelwise
self.eps = eps
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dearkafka/inferno
|
SorensenDiceLoss
| false
| 1,819
|
[
"Apache-2.0"
] | 0
|
e9e3b863fd1fc97cf94d08ac6b4f8df7665f996a
|
https://github.com/dearkafka/inferno/tree/e9e3b863fd1fc97cf94d08ac6b4f8df7665f996a
|
MTFullyConnected
|
import time
import torch
import numpy as np
from torch import nn
from torch import optim
from torch.nn import functional as F
class Base(nn.Module):
""" This class is the base structure for all of classification/regression DNN models.
Mainly, it provides the general methods for training, evaluating model and predcting the given data.
"""
def fit(self, train_loader, valid_loader, out, epochs=100, lr=0.0001):
"""Training the DNN model, similar to the scikit-learn or Keras style.
In the end, the optimal value of parameters will also be persisted on the hard drive.
Arguments:
train_loader (DataLoader): Data loader for training set,
including m X n target FloatTensor and m X l label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
valid_loader (DataLoader): Data loader for validation set.
The data structure is as same as loader_train.
out (str): the file path for the model file (suffix with '.pkg')
and log file (suffix with '.log').
epochs(int, optional): The maximum of training epochs (default: 100)
lr (float, optional): learning rate (default: 1e-4)
"""
if 'optim' in self.__dict__:
optimizer = self.optim
else:
optimizer = optim.Adam(self.parameters(), lr=lr)
best_loss = np.inf
last_save = 0
log = open(out + '.log', 'w')
for epoch in range(epochs):
time.time()
for param_group in optimizer.param_groups:
param_group['lr'] = lr * (1 - 1 / epochs) ** (epoch * 10)
for i, (Xb, yb) in enumerate(train_loader):
Xb, yb = Xb, yb
optimizer.zero_grad()
y_ = self.forward(Xb, istrain=True)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss = self.criterion(y_, yb)
loss.backward()
optimizer.step()
loss_valid = self.evaluate(valid_loader)
None
if loss_valid < best_loss:
torch.save(self.state_dict(), out + '.pkg')
None
best_loss = loss_valid
last_save = epoch
else:
None
if epoch - last_save > 100:
break
log.close()
self.load_state_dict(torch.load(out + '.pkg'))
def evaluate(self, loader):
"""Evaluating the performance of the DNN model.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
including m X n target FloatTensor and l X n label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
Return:
loss (float): the average loss value based on the calculation of loss function with given test set.
"""
loss = 0
for Xb, yb in loader:
Xb, yb = Xb, yb
y_ = self.forward(Xb)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss += self.criterion(y_, yb).data[0]
loss = loss / len(loader)
return loss
def predict(self, loader):
"""Predicting the probability of each sample in the given dataset.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
only including m X n target FloatTensor
(m is the No. of sample, n is the No. of features)
Return:
score (ndarray): probability of each sample in the given dataset,
it is a m X l FloatTensor (m is the No. of sample, l is the No. of classes or tasks.)
"""
score = []
for Xb, yb in loader:
Xb = Xb
y_ = self.forward(Xb)
score.append(y_.detach().cpu())
score = torch.cat(score, dim=0).numpy()
return score
class MTFullyConnected(Base):
"""Multi-task DNN classification/regression model. It contains four fully connected layers
between which are dropout layer for robustness.
Arguments:
n_dim (int): the No. of columns (features) for input tensor
n_task (int): the No. of columns (tasks) for output tensor.
is_reg (bool, optional): Regression model (True) or Classification model (False)
"""
def __init__(self, n_dim, n_task, is_reg=False):
super(MTFullyConnected, self).__init__()
self.n_task = n_task
self.dropout = nn.Dropout(0.25)
self.fc0 = nn.Linear(n_dim, 8000)
self.fc1 = nn.Linear(8000, 4000)
self.fc2 = nn.Linear(4000, 2000)
self.output = nn.Linear(2000, n_task)
self.is_reg = is_reg
if is_reg:
self.criterion = nn.MSELoss()
else:
self.criterion = nn.BCELoss()
self.activation = nn.Sigmoid()
self
def forward(self, X, istrain=False):
"""Invoke the class directly as a function
Arguments:
X (FloatTensor): m X n FloatTensor, m is the No. of samples, n is the No. of features.
istrain (bool, optional): is it invoked during training process (True)
or just for prediction (False)
Return:
y (FloatTensor): m X l FloatTensor, m is the No. of samples, n is the No. of tasks
"""
y = F.relu(self.fc0(X))
if istrain:
y = self.dropout(y)
y = F.relu(self.fc1(y))
if istrain:
y = self.dropout(y)
y = F.relu(self.fc2(y))
if istrain:
y = self.dropout(y)
if self.is_reg:
y = self.output(y)
else:
y = self.activation(self.output(y))
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_dim': 4, 'n_task': 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 time
import numpy as np
from torch import nn
from torch import optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 8000
x1 = xindex // 8000
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 + (x0 + 8064 * x1), tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 4000
x1 = xindex // 4000
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 + (x0 + 4096 * x1), tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2000
x1 = xindex // 2000
tmp0 = tl.load(in_out_ptr0 + (x0 + 2016 * x1), 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 + (x0 + 2016 * x1), tmp4, xmask)
tl.store(out_ptr0 + (x0 + 2048 * x1), tmp6, xmask)
@triton.jit
def triton_poi_fused_sigmoid_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (8000, 4), (4, 1))
assert_size_stride(primals_2, (8000,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4000, 8000), (8000, 1))
assert_size_stride(primals_5, (4000,), (1,))
assert_size_stride(primals_6, (2000, 4000), (4000, 1))
assert_size_stride(primals_7, (2000,), (1,))
assert_size_stride(primals_8, (4, 2000), (2000, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 8000), (8000, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 8000), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 8000), (128000, 32000,
8000, 1), 0)
del buf0
buf10 = empty_strided_cuda((4, 4, 4, 8000), (129024, 32256, 8064, 1
), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(512000)](buf1,
primals_2, buf10, 512000, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4000), (4000, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 8000), (8000, 1), 0
), reinterpret_tensor(primals_4, (8000, 4000), (1, 8000), 0),
out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4000), (64000, 16000,
4000, 1), 0)
del buf2
buf9 = empty_strided_cuda((4, 4, 4, 4000), (65536, 16384, 4096, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256000)](buf3,
primals_5, buf9, 256000, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 2000), (2016, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4000), (4000, 1), 0
), reinterpret_tensor(primals_6, (4000, 2000), (1, 4000), 0),
out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 2000), (32256, 8064, 2016,
1), 0)
del buf4
buf8 = empty_strided_cuda((4, 4, 4, 2000), (32768, 8192, 2048, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(128000)](buf5,
primals_7, buf8, 128000, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf5, (64, 2000), (2016, 1), 0
), reinterpret_tensor(primals_8, (2000, 4), (1, 2000), 0), out=buf6
)
buf7 = reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf6
triton_poi_fused_sigmoid_3[grid(256)](buf7, primals_9, 256, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
return buf7, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 8000), (8000, 1), 0
), reinterpret_tensor(buf3, (64, 4000), (4000, 1), 0
), reinterpret_tensor(buf5, (64, 2000), (2016, 1), 0
), buf7, primals_8, buf8, primals_6, buf9, primals_4, buf10
class Base(nn.Module):
""" This class is the base structure for all of classification/regression DNN models.
Mainly, it provides the general methods for training, evaluating model and predcting the given data.
"""
def fit(self, train_loader, valid_loader, out, epochs=100, lr=0.0001):
"""Training the DNN model, similar to the scikit-learn or Keras style.
In the end, the optimal value of parameters will also be persisted on the hard drive.
Arguments:
train_loader (DataLoader): Data loader for training set,
including m X n target FloatTensor and m X l label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
valid_loader (DataLoader): Data loader for validation set.
The data structure is as same as loader_train.
out (str): the file path for the model file (suffix with '.pkg')
and log file (suffix with '.log').
epochs(int, optional): The maximum of training epochs (default: 100)
lr (float, optional): learning rate (default: 1e-4)
"""
if 'optim' in self.__dict__:
optimizer = self.optim
else:
optimizer = optim.Adam(self.parameters(), lr=lr)
best_loss = np.inf
last_save = 0
log = open(out + '.log', 'w')
for epoch in range(epochs):
time.time()
for param_group in optimizer.param_groups:
param_group['lr'] = lr * (1 - 1 / epochs) ** (epoch * 10)
for i, (Xb, yb) in enumerate(train_loader):
Xb, yb = Xb, yb
optimizer.zero_grad()
y_ = self.forward(Xb, istrain=True)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss = self.criterion(y_, yb)
loss.backward()
optimizer.step()
loss_valid = self.evaluate(valid_loader)
None
if loss_valid < best_loss:
torch.save(self.state_dict(), out + '.pkg')
None
best_loss = loss_valid
last_save = epoch
else:
None
if epoch - last_save > 100:
break
log.close()
self.load_state_dict(torch.load(out + '.pkg'))
def evaluate(self, loader):
"""Evaluating the performance of the DNN model.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
including m X n target FloatTensor and l X n label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
Return:
loss (float): the average loss value based on the calculation of loss function with given test set.
"""
loss = 0
for Xb, yb in loader:
Xb, yb = Xb, yb
y_ = self.forward(Xb)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss += self.criterion(y_, yb).data[0]
loss = loss / len(loader)
return loss
def predict(self, loader):
"""Predicting the probability of each sample in the given dataset.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
only including m X n target FloatTensor
(m is the No. of sample, n is the No. of features)
Return:
score (ndarray): probability of each sample in the given dataset,
it is a m X l FloatTensor (m is the No. of sample, l is the No. of classes or tasks.)
"""
score = []
for Xb, yb in loader:
Xb = Xb
y_ = self.forward(Xb)
score.append(y_.detach().cpu())
score = torch.cat(score, dim=0).numpy()
return score
class MTFullyConnectedNew(Base):
"""Multi-task DNN classification/regression model. It contains four fully connected layers
between which are dropout layer for robustness.
Arguments:
n_dim (int): the No. of columns (features) for input tensor
n_task (int): the No. of columns (tasks) for output tensor.
is_reg (bool, optional): Regression model (True) or Classification model (False)
"""
def __init__(self, n_dim, n_task, is_reg=False):
super(MTFullyConnectedNew, self).__init__()
self.n_task = n_task
self.dropout = nn.Dropout(0.25)
self.fc0 = nn.Linear(n_dim, 8000)
self.fc1 = nn.Linear(8000, 4000)
self.fc2 = nn.Linear(4000, 2000)
self.output = nn.Linear(2000, n_task)
self.is_reg = is_reg
if is_reg:
self.criterion = nn.MSELoss()
else:
self.criterion = nn.BCELoss()
self.activation = nn.Sigmoid()
self
def forward(self, input_0):
primals_1 = self.fc0.weight
primals_2 = self.fc0.bias
primals_4 = self.fc1.weight
primals_5 = self.fc1.bias
primals_6 = self.fc2.weight
primals_7 = self.fc2.bias
primals_8 = self.output.weight
primals_9 = self.output.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
cthoyt/DrugEx
|
MTFullyConnected
| false
| 1,820
|
[
"MIT"
] | 0
|
9e4d31adb2c65d0afc852948f502c79dcf8308a3
|
https://github.com/cthoyt/DrugEx/tree/9e4d31adb2c65d0afc852948f502c79dcf8308a3
|
Maxout
|
import torch
from torch import nn
class Maxout(nn.Module):
def __init__(self, pool_size):
super().__init__()
self._pool_size = pool_size
def forward(self, x):
assert x.shape[-1
] % self._pool_size == 0, 'Wrong input last dim size ({}) for Maxout({})'.format(
x.shape[-1], self._pool_size)
m, _i = x.view(*x.shape[:-1], x.shape[-1] // self._pool_size, self.
_pool_size).max(-1)
return m
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'pool_size': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_max_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
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, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_max_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
return buf0,
class MaxoutNew(nn.Module):
def __init__(self, pool_size):
super().__init__()
self._pool_size = pool_size
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
demdecuong/SEGMENT
|
Maxout
| false
| 1,821
|
[
"MIT"
] | 0
|
629dc55dcbc9629b35fb237e313b95ceacecdc89
|
https://github.com/demdecuong/SEGMENT/tree/629dc55dcbc9629b35fb237e313b95ceacecdc89
|
Debayer2x2
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Debayer2x2(nn.Module):
"""Demosaicing of Bayer images using 2x2 convolutions.
Requires BG-Bayer color filter array layout. That is,
the image[1,1]='B', image[1,2]='G'.
"""
def __init__(self):
super(Debayer2x2, self).__init__()
self.kernels = nn.Parameter(torch.tensor([[1, 0], [0, 0], [0, 0.5],
[0.5, 0], [0, 0], [0, 1]]).view(3, 1, 2, 2), requires_grad=False)
def forward(self, x):
"""Debayer image.
Parameters
----------
x : Bx1xHxW tensor
Images to debayer
Returns
-------
rgb : Bx3xHxW tensor
Color images in RGB channel order.
"""
x = F.conv2d(x, self.kernels, stride=2)
x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners
=False)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_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)
x1 = xindex // 64 % 64
x0 = xindex % 64
x2 = xindex // 4096
x4 = xindex
tmp0 = x1
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)
tmp13 = x0
tmp14 = tmp13.to(tl.float32)
tmp15 = tmp14 + tmp2
tmp16 = tmp15 * tmp2
tmp17 = tmp16 - tmp2
tmp18 = triton_helpers.maximum(tmp17, tmp6)
tmp19 = tmp18.to(tl.int32)
tmp20 = tmp19 + tmp9
tmp21 = triton_helpers.minimum(tmp20, tmp11)
tmp22 = tl.load(in_ptr0 + (tmp21 + 32 * tmp12 + 1024 * x2), None,
eviction_policy='evict_last')
tmp23 = tl.load(in_ptr0 + (tmp19 + 32 * tmp12 + 1024 * x2), None,
eviction_policy='evict_last')
tmp24 = tmp22 - tmp23
tmp25 = tmp19.to(tl.float32)
tmp26 = tmp18 - tmp25
tmp27 = triton_helpers.maximum(tmp26, tmp6)
tmp28 = 1.0
tmp29 = triton_helpers.minimum(tmp27, tmp28)
tmp30 = tmp24 * tmp29
tmp31 = tmp23 + tmp30
tmp32 = tl.load(in_ptr0 + (tmp19 + 32 * tmp8 + 1024 * x2), None,
eviction_policy='evict_last')
tmp33 = tl.load(in_ptr0 + (tmp21 + 32 * tmp8 + 1024 * x2), None,
eviction_policy='evict_last')
tmp34 = tmp33 - tmp32
tmp35 = tmp34 * tmp29
tmp36 = tmp32 + tmp35
tmp37 = tmp31 - tmp36
tmp38 = tmp8.to(tl.float32)
tmp39 = tmp7 - tmp38
tmp40 = triton_helpers.maximum(tmp39, tmp6)
tmp41 = triton_helpers.minimum(tmp40, tmp28)
tmp42 = tmp37 * tmp41
tmp43 = tmp36 + tmp42
tl.store(in_out_ptr0 + x4, tmp43, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (3, 1, 2, 2), (4, 4, 2, 1))
assert_size_stride(arg1_1, (4, 1, 64, 64), (4096, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(arg1_1, arg0_1, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 3, 32, 32), (3072, 1024, 32, 1))
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.float32)
buf2 = buf1
del buf1
buf3 = buf2
del buf2
get_raw_stream(0)
triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_0[grid
(49152)](buf3, buf0, 49152, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
return buf3,
class Debayer2x2New(nn.Module):
"""Demosaicing of Bayer images using 2x2 convolutions.
Requires BG-Bayer color filter array layout. That is,
the image[1,1]='B', image[1,2]='G'.
"""
def __init__(self):
super(Debayer2x2New, self).__init__()
self.kernels = nn.Parameter(torch.tensor([[1, 0], [0, 0], [0, 0.5],
[0.5, 0], [0, 0], [0, 1]]).view(3, 1, 2, 2), requires_grad=False)
def forward(self, input_0):
arg0_1 = self.kernels
arg1_1 = input_0
output = call([arg0_1, arg1_1])
return output[0]
|
delldu/ImageClean
|
Debayer2x2
| false
| 1,822
|
[
"MIT"
] | 0
|
ffa5b180d36afb3840c6b36c08a767c520068498
|
https://github.com/delldu/ImageClean/tree/ffa5b180d36afb3840c6b36c08a767c520068498
|
MuSigmaEncoder
|
import torch
from typing import Tuple
from torch import nn
class MuSigmaEncoder(nn.Module):
"""
Maps a representation r to mu and sigma which will define the normal
distribution from which we sample the latent variable z.
Parameters
----------
r_dim : int
Dimension of output representation r.
z_dim : int
Dimension of latent variable z.
"""
def __init__(self, r_dim: 'int', z_dim: 'int') ->None:
super(MuSigmaEncoder, self).__init__()
self.r_dim = r_dim
self.z_dim = z_dim
self.r_to_hidden = nn.Linear(r_dim, r_dim)
self.hidden_to_mu = nn.Linear(r_dim, z_dim)
self.hidden_to_sigma = nn.Linear(r_dim, z_dim)
def forward(self, r: 'torch.Tensor') ->Tuple[torch.Tensor, torch.Tensor]:
"""
r : torch.Tensor
Shape (batch_size, r_dim)
"""
hidden = torch.relu(self.r_to_hidden(r))
mu = self.hidden_to_mu(hidden)
sigma = 0.1 + 0.9 * torch.sigmoid(self.hidden_to_sigma(hidden))
return mu, sigma
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'r_dim': 4, 'z_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_mul_sigmoid_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 = tl.sigmoid(tmp0)
tmp2 = 0.9
tmp3 = tmp1 * tmp2
tmp4 = 0.1
tmp5 = tmp3 + tmp4
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf1, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_7
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_sigmoid_1[grid(256)](buf3, buf4, 256,
XBLOCK=128, num_warps=4, num_stages=1)
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0
), buf3, primals_6, primals_4, buf5
class MuSigmaEncoderNew(nn.Module):
"""
Maps a representation r to mu and sigma which will define the normal
distribution from which we sample the latent variable z.
Parameters
----------
r_dim : int
Dimension of output representation r.
z_dim : int
Dimension of latent variable z.
"""
def __init__(self, r_dim: 'int', z_dim: 'int') ->None:
super(MuSigmaEncoderNew, self).__init__()
self.r_dim = r_dim
self.z_dim = z_dim
self.r_to_hidden = nn.Linear(r_dim, r_dim)
self.hidden_to_mu = nn.Linear(r_dim, z_dim)
self.hidden_to_sigma = nn.Linear(r_dim, z_dim)
def forward(self, input_0):
primals_1 = self.r_to_hidden.weight
primals_2 = self.r_to_hidden.bias
primals_4 = self.hidden_to_mu.weight
primals_5 = self.hidden_to_mu.bias
primals_6 = self.hidden_to_sigma.weight
primals_7 = self.hidden_to_sigma.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
deltaskelta/neural-processes
|
MuSigmaEncoder
| false
| 1,823
|
[
"MIT"
] | 0
|
34a6b98b7a9142f5e5f87f7f1644217d5aa9e1bb
|
https://github.com/deltaskelta/neural-processes/tree/34a6b98b7a9142f5e5f87f7f1644217d5aa9e1bb
|
fixed_loss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class fixed_loss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, out_image, gt_image, est_noise, gt_noise, if_asym):
h_x = est_noise.size()[2]
w_x = est_noise.size()[3]
count_h = self._tensor_size(est_noise[:, :, 1:, :])
count_w = self._tensor_size(est_noise[:, :, :, 1:])
h_tv = torch.pow(est_noise[:, :, 1:, :] - est_noise[:, :, :h_x - 1,
:], 2).sum()
w_tv = torch.pow(est_noise[:, :, :, 1:] - est_noise[:, :, :, :w_x -
1], 2).sum()
tvloss = h_tv / count_h + w_tv / count_w
loss = torch.mean(torch.pow(out_image - gt_image, 2)
) + if_asym * 0.5 * torch.mean(torch.mul(torch.abs(0.3 - F.relu
(gt_noise - est_noise)), torch.pow(est_noise - gt_noise, 2))
) + 0.05 * tvloss
return loss
def _tensor_size(self, t):
return t.size()[1] * t.size()[2] * t.size()[3]
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]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_pow_sub_sum_0(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
rnumel = 192
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r0 = rindex % 12
r1 = rindex // 12
tmp0 = tl.load(in_ptr0 + (4 + r0 + 16 * r1), rmask, other=0.0)
tmp1 = tl.load(in_ptr0 + (r0 + 16 * r1), rmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(rmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_per_fused_pow_sub_sum_1(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
rnumel = 192
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r0 = rindex % 3
r1 = rindex // 3
tmp0 = tl.load(in_ptr0 + (1 + r0 + 4 * r1), rmask, other=0.0)
tmp1 = tl.load(in_ptr0 + (r0 + 4 * r1), rmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(rmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)
@triton.jit
def triton_per_fused_abs_add_div_mean_mul_pow_relu_rsub_sub_2(in_ptr0,
in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, out_ptr2, xnumel,
rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp7 = tl.load(in_ptr2 + r0, None)
tmp8 = tl.load(in_ptr3 + r0, None)
tmp23 = tl.load(in_ptr4 + r0, None)
tmp29 = tl.load(in_ptr5 + 0)
tmp30 = tl.broadcast_to(tmp29, [RBLOCK])
tmp33 = tl.load(in_ptr6 + 0)
tmp34 = tl.broadcast_to(tmp33, [RBLOCK])
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp9 = tmp7 - tmp8
tmp10 = tl.full([1], 0, tl.int32)
tmp11 = triton_helpers.maximum(tmp10, tmp9)
tmp12 = 0.3
tmp13 = tmp12 - tmp11
tmp14 = tl_math.abs(tmp13)
tmp15 = tmp8 - tmp7
tmp16 = tmp15 * tmp15
tmp17 = tmp14 * tmp16
tmp18 = tl.broadcast_to(tmp17, [RBLOCK])
tmp20 = triton_helpers.promote_to_tensor(tl.sum(tmp18, 0))
tmp21 = 256.0
tmp22 = tmp6 / tmp21
tmp24 = 0.5
tmp25 = tmp23 * tmp24
tmp26 = tmp20 / tmp21
tmp27 = tmp25 * tmp26
tmp28 = tmp22 + tmp27
tmp31 = 0.020833333333333332
tmp32 = tmp30 * tmp31
tmp35 = tmp34 * tmp31
tmp36 = tmp32 + tmp35
tmp37 = 0.05
tmp38 = tmp36 * tmp37
tmp39 = tmp28 + tmp38
tl.store(out_ptr2 + tl.broadcast_to(r0, [RBLOCK]), tmp39, None)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1, arg4_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))
assert_size_stride(arg4_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_pow_sub_sum_0[grid(1)](arg0_1, buf2, 1, 192,
XBLOCK=1, num_warps=2, num_stages=1)
buf3 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_pow_sub_sum_1[grid(1)](arg0_1, buf3, 1, 192,
XBLOCK=1, num_warps=2, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused_abs_add_div_mean_mul_pow_relu_rsub_sub_2[grid(1)](
arg1_1, arg2_1, arg4_1, arg0_1, arg3_1, buf2, buf3, buf4, 1,
256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
del arg3_1
del arg4_1
del buf2
del buf3
return buf4,
class fixed_lossNew(nn.Module):
def __init__(self):
super().__init__()
def _tensor_size(self, t):
return t.size()[1] * t.size()[2] * t.size()[3]
def forward(self, input_0, input_1, input_2, input_3, input_4):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
arg4_1 = input_4
output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1])
return output[0]
|
delldu/ImageClean
|
fixed_loss
| false
| 1,824
|
[
"MIT"
] | 0
|
ffa5b180d36afb3840c6b36c08a767c520068498
|
https://github.com/delldu/ImageClean/tree/ffa5b180d36afb3840c6b36c08a767c520068498
|
Discriminator
|
import math
import torch
import torch.nn as nn
import torch.utils.data
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class Discriminator(nn.Module):
def __init__(self, hidden_dim):
super(Discriminator, self).__init__()
self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
self.reset_parameters()
def reset_parameters(self):
size = self.weight.size(0)
uniform(size, self.weight)
def forward(self, x, summary):
x = torch.matmul(x, torch.matmul(self.weight, summary))
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 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
import math
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
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, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64, 4)](primals_2, buf0, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf1)
del primals_1
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(64, 4)](buf1, buf2, 64, 4, XBLOCK=4,
YBLOCK=32, num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(primals_3, (16, 4, 4), (16, 4,
1), 0), reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0),
out=buf3)
del buf2
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(buf0, (64, 4), (4, 1), 0), reinterpret_tensor(
primals_3, (16, 4, 4), (16, 1, 4), 0)
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class DiscriminatorNew(nn.Module):
def __init__(self, hidden_dim):
super(DiscriminatorNew, self).__init__()
self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))
self.reset_parameters()
def reset_parameters(self):
size = self.weight.size(0)
uniform(size, self.weight)
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]
|
dendisuhubdy/pytorch_geometric
|
Discriminator
| false
| 1,825
|
[
"MIT"
] | 0
|
a0592f61aef617c0c8ff61b3d822d04901054c22
|
https://github.com/dendisuhubdy/pytorch_geometric/tree/a0592f61aef617c0c8ff61b3d822d04901054c22
|
STFullyConnected
|
import time
import torch
import numpy as np
from torch import nn
from torch import optim
from torch.nn import functional as F
class Base(nn.Module):
""" This class is the base structure for all of classification/regression DNN models.
Mainly, it provides the general methods for training, evaluating model and predcting the given data.
"""
def fit(self, train_loader, valid_loader, out, epochs=100, lr=0.0001):
"""Training the DNN model, similar to the scikit-learn or Keras style.
In the end, the optimal value of parameters will also be persisted on the hard drive.
Arguments:
train_loader (DataLoader): Data loader for training set,
including m X n target FloatTensor and m X l label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
valid_loader (DataLoader): Data loader for validation set.
The data structure is as same as loader_train.
out (str): the file path for the model file (suffix with '.pkg')
and log file (suffix with '.log').
epochs(int, optional): The maximum of training epochs (default: 100)
lr (float, optional): learning rate (default: 1e-4)
"""
if 'optim' in self.__dict__:
optimizer = self.optim
else:
optimizer = optim.Adam(self.parameters(), lr=lr)
best_loss = np.inf
last_save = 0
log = open(out + '.log', 'w')
for epoch in range(epochs):
time.time()
for param_group in optimizer.param_groups:
param_group['lr'] = lr * (1 - 1 / epochs) ** (epoch * 10)
for i, (Xb, yb) in enumerate(train_loader):
Xb, yb = Xb, yb
optimizer.zero_grad()
y_ = self.forward(Xb, istrain=True)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss = self.criterion(y_, yb)
loss.backward()
optimizer.step()
loss_valid = self.evaluate(valid_loader)
None
if loss_valid < best_loss:
torch.save(self.state_dict(), out + '.pkg')
None
best_loss = loss_valid
last_save = epoch
else:
None
if epoch - last_save > 100:
break
log.close()
self.load_state_dict(torch.load(out + '.pkg'))
def evaluate(self, loader):
"""Evaluating the performance of the DNN model.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
including m X n target FloatTensor and l X n label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
Return:
loss (float): the average loss value based on the calculation of loss function with given test set.
"""
loss = 0
for Xb, yb in loader:
Xb, yb = Xb, yb
y_ = self.forward(Xb)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss += self.criterion(y_, yb).data[0]
loss = loss / len(loader)
return loss
def predict(self, loader):
"""Predicting the probability of each sample in the given dataset.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
only including m X n target FloatTensor
(m is the No. of sample, n is the No. of features)
Return:
score (ndarray): probability of each sample in the given dataset,
it is a m X l FloatTensor (m is the No. of sample, l is the No. of classes or tasks.)
"""
score = []
for Xb, yb in loader:
Xb = Xb
y_ = self.forward(Xb)
score.append(y_.detach().cpu())
score = torch.cat(score, dim=0).numpy()
return score
class STFullyConnected(Base):
"""Single task DNN classification/regression model. It contains four fully connected layers between which
are dropout layer for robustness.
Arguments:
n_dim (int): the No. of columns (features) for input tensor
n_class (int): the No. of columns (classes) for output tensor.
is_reg (bool, optional): Regression model (True) or Classification model (False)
"""
def __init__(self, n_dim, n_class, is_reg=False):
super(STFullyConnected, self).__init__()
self.dropout = nn.Dropout(0.25)
self.fc0 = nn.Linear(n_dim, 8000)
self.fc1 = nn.Linear(8000, 4000)
self.fc2 = nn.Linear(4000, 2000)
self.fc3 = nn.Linear(2000, n_class)
self.is_reg = is_reg
if is_reg:
self.criterion = nn.MSELoss()
elif n_class == 1:
self.criterion = nn.BCELoss()
self.activation = nn.Sigmoid()
else:
self.criterion = nn.CrossEntropyLoss()
self.activation = nn.Softmax()
self
def forward(self, X, istrain=False):
"""Invoke the class directly as a function
Arguments:
X (FloatTensor): m X n FloatTensor, m is the No. of samples, n is the No. of features.
istrain (bool, optional): is it invoked during training process (True) or just for prediction (False)
Return:
y (FloatTensor): m X l FloatTensor, m is the No. of samples, n is the No. of classes
"""
y = F.relu(self.fc0(X))
if istrain:
y = self.dropout(y)
y = F.relu(self.fc1(y))
if istrain:
y = self.dropout(y)
y = F.relu(self.fc2(y))
if istrain:
y = self.dropout(y)
if self.is_reg:
y = self.fc3(y)
else:
y = self.activation(self.fc3(y))
return y
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_dim': 4, 'n_class': 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 time
import numpy as np
from torch import nn
from torch import optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 8000
x1 = xindex // 8000
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 + (x0 + 8064 * x1), tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 4000
x1 = xindex // 4000
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 + (x0 + 4096 * x1), tmp6, None)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2000
x1 = xindex // 2000
tmp0 = tl.load(in_out_ptr0 + (x0 + 2016 * x1), 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 + (x0 + 2016 * x1), tmp4, xmask)
tl.store(out_ptr0 + (x0 + 2048 * x1), tmp6, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
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, (8000, 4), (4, 1))
assert_size_stride(primals_2, (8000,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4000, 8000), (8000, 1))
assert_size_stride(primals_5, (4000,), (1,))
assert_size_stride(primals_6, (2000, 4000), (4000, 1))
assert_size_stride(primals_7, (2000,), (1,))
assert_size_stride(primals_8, (4, 2000), (2000, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 8000), (8000, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 8000), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 8000), (128000, 32000,
8000, 1), 0)
del buf0
buf11 = empty_strided_cuda((4, 4, 4, 8000), (129024, 32256, 8064, 1
), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(512000)](buf1,
primals_2, buf11, 512000, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4000), (4000, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 8000), (8000, 1), 0
), reinterpret_tensor(primals_4, (8000, 4000), (1, 8000), 0),
out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4000), (64000, 16000,
4000, 1), 0)
del buf2
buf10 = empty_strided_cuda((4, 4, 4, 4000), (65536, 16384, 4096, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(256000)](buf3,
primals_5, buf10, 256000, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 2000), (2016, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4000), (4000, 1), 0
), reinterpret_tensor(primals_6, (4000, 2000), (1, 4000), 0),
out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 2000), (32256, 8064, 2016,
1), 0)
del buf4
buf9 = empty_strided_cuda((4, 4, 4, 2000), (32768, 8192, 2048, 1),
torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(128000)](buf5,
primals_7, buf9, 128000, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 2000),
(2016, 1), 0), reinterpret_tensor(primals_8, (2000, 4), (1,
2000), 0), alpha=1, beta=1, out=buf6)
del primals_9
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_3[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_4[grid(256)](buf7, buf8, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf7
return buf8, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 8000), (8000, 1), 0
), reinterpret_tensor(buf3, (64, 4000), (4000, 1), 0
), reinterpret_tensor(buf5, (64, 2000), (2016, 1), 0
), buf8, primals_8, buf9, primals_6, buf10, primals_4, buf11
class Base(nn.Module):
""" This class is the base structure for all of classification/regression DNN models.
Mainly, it provides the general methods for training, evaluating model and predcting the given data.
"""
def fit(self, train_loader, valid_loader, out, epochs=100, lr=0.0001):
"""Training the DNN model, similar to the scikit-learn or Keras style.
In the end, the optimal value of parameters will also be persisted on the hard drive.
Arguments:
train_loader (DataLoader): Data loader for training set,
including m X n target FloatTensor and m X l label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
valid_loader (DataLoader): Data loader for validation set.
The data structure is as same as loader_train.
out (str): the file path for the model file (suffix with '.pkg')
and log file (suffix with '.log').
epochs(int, optional): The maximum of training epochs (default: 100)
lr (float, optional): learning rate (default: 1e-4)
"""
if 'optim' in self.__dict__:
optimizer = self.optim
else:
optimizer = optim.Adam(self.parameters(), lr=lr)
best_loss = np.inf
last_save = 0
log = open(out + '.log', 'w')
for epoch in range(epochs):
time.time()
for param_group in optimizer.param_groups:
param_group['lr'] = lr * (1 - 1 / epochs) ** (epoch * 10)
for i, (Xb, yb) in enumerate(train_loader):
Xb, yb = Xb, yb
optimizer.zero_grad()
y_ = self.forward(Xb, istrain=True)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss = self.criterion(y_, yb)
loss.backward()
optimizer.step()
loss_valid = self.evaluate(valid_loader)
None
if loss_valid < best_loss:
torch.save(self.state_dict(), out + '.pkg')
None
best_loss = loss_valid
last_save = epoch
else:
None
if epoch - last_save > 100:
break
log.close()
self.load_state_dict(torch.load(out + '.pkg'))
def evaluate(self, loader):
"""Evaluating the performance of the DNN model.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
including m X n target FloatTensor and l X n label FloatTensor
(m is the No. of sample, n is the No. of features, l is the No. of classes or tasks)
Return:
loss (float): the average loss value based on the calculation of loss function with given test set.
"""
loss = 0
for Xb, yb in loader:
Xb, yb = Xb, yb
y_ = self.forward(Xb)
ix = yb == yb
yb, y_ = yb[ix], y_[ix]
loss += self.criterion(y_, yb).data[0]
loss = loss / len(loader)
return loss
def predict(self, loader):
"""Predicting the probability of each sample in the given dataset.
Arguments:
loader (torch.utils.data.DataLoader): data loader for test set,
only including m X n target FloatTensor
(m is the No. of sample, n is the No. of features)
Return:
score (ndarray): probability of each sample in the given dataset,
it is a m X l FloatTensor (m is the No. of sample, l is the No. of classes or tasks.)
"""
score = []
for Xb, yb in loader:
Xb = Xb
y_ = self.forward(Xb)
score.append(y_.detach().cpu())
score = torch.cat(score, dim=0).numpy()
return score
class STFullyConnectedNew(Base):
"""Single task DNN classification/regression model. It contains four fully connected layers between which
are dropout layer for robustness.
Arguments:
n_dim (int): the No. of columns (features) for input tensor
n_class (int): the No. of columns (classes) for output tensor.
is_reg (bool, optional): Regression model (True) or Classification model (False)
"""
def __init__(self, n_dim, n_class, is_reg=False):
super(STFullyConnectedNew, self).__init__()
self.dropout = nn.Dropout(0.25)
self.fc0 = nn.Linear(n_dim, 8000)
self.fc1 = nn.Linear(8000, 4000)
self.fc2 = nn.Linear(4000, 2000)
self.fc3 = nn.Linear(2000, n_class)
self.is_reg = is_reg
if is_reg:
self.criterion = nn.MSELoss()
elif n_class == 1:
self.criterion = nn.BCELoss()
self.activation = nn.Sigmoid()
else:
self.criterion = nn.CrossEntropyLoss()
self.activation = nn.Softmax()
self
def forward(self, input_0):
primals_1 = self.fc0.weight
primals_2 = self.fc0.bias
primals_4 = self.fc1.weight
primals_5 = self.fc1.bias
primals_6 = self.fc2.weight
primals_7 = self.fc2.bias
primals_8 = self.fc3.weight
primals_9 = 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])
return output[0]
|
cthoyt/DrugEx
|
STFullyConnected
| false
| 1,826
|
[
"MIT"
] | 0
|
9e4d31adb2c65d0afc852948f502c79dcf8308a3
|
https://github.com/cthoyt/DrugEx/tree/9e4d31adb2c65d0afc852948f502c79dcf8308a3
|
SoftDetectionModule
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class SoftDetectionModule(nn.Module):
def __init__(self, soft_local_max_size=3):
super(SoftDetectionModule, self).__init__()
self.soft_local_max_size = soft_local_max_size
self.pad = self.soft_local_max_size // 2
def forward(self, batch):
b = batch.size(0)
batch = F.relu(batch)
max_per_sample = torch.max(batch.view(b, -1), dim=1)[0]
exp = torch.exp(batch / max_per_sample.view(b, 1, 1, 1))
sum_exp = self.soft_local_max_size ** 2 * F.avg_pool2d(F.pad(exp, [
self.pad] * 4, mode='constant', value=1.0), self.
soft_local_max_size, stride=1)
local_max_score = exp / sum_exp
depth_wise_max = torch.max(batch, dim=1)[0]
depth_wise_max_score = batch / depth_wise_max.unsqueeze(1)
all_scores = local_max_score * depth_wise_max_score
score = torch.max(all_scores, dim=1)[0]
score = score / torch.sum(score.view(b, -1), dim=1).view(b, 1, 1)
return score
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_max_0(in_ptr0, 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.full([1, 1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, float('-inf'))
tmp6 = triton_helpers.max2(tmp5, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
@triton.jit
def triton_poi_fused_constant_pad_nd_div_exp_relu_1(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 6 % 6
x0 = xindex % 6
x4 = xindex // 36
x3 = xindex // 144
x6 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = -1 + x0
tmp6 = tmp5 >= tmp1
tmp7 = tmp5 < tmp3
tmp8 = tmp2 & tmp4
tmp9 = tmp8 & tmp6
tmp10 = tmp9 & tmp7
tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x4), tmp10 & xmask,
other=0.0)
tmp12 = tl.full([1], 0, tl.int32)
tmp13 = triton_helpers.maximum(tmp12, tmp11)
tmp14 = tl.load(in_ptr1 + x3, tmp10 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tmp13 / tmp14
tmp16 = tl_math.exp(tmp15)
tmp17 = tl.full(tmp16.shape, 1.0, tmp16.dtype)
tmp18 = tl.where(tmp10, tmp16, tmp17)
tl.store(out_ptr0 + x6, tmp18, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_constant_pad_nd_div_exp_relu_2(in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 6 * x1 + 36 * x2), xmask)
tmp1 = tl.load(in_ptr0 + (1 + x0 + 6 * x1 + 36 * x2), xmask)
tmp3 = tl.load(in_ptr0 + (2 + x0 + 6 * x1 + 36 * x2), xmask)
tmp5 = tl.load(in_ptr0 + (6 + x0 + 6 * x1 + 36 * x2), xmask)
tmp7 = tl.load(in_ptr0 + (7 + x0 + 6 * x1 + 36 * x2), xmask)
tmp9 = tl.load(in_ptr0 + (8 + x0 + 6 * x1 + 36 * x2), xmask)
tmp11 = tl.load(in_ptr0 + (12 + x0 + 6 * x1 + 36 * x2), xmask)
tmp13 = tl.load(in_ptr0 + (13 + x0 + 6 * x1 + 36 * x2), xmask)
tmp15 = tl.load(in_ptr0 + (14 + x0 + 6 * x1 + 36 * x2), xmask)
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp8 = tmp7 + tmp6
tmp10 = tmp9 + tmp8
tmp12 = tmp11 + tmp10
tmp14 = tmp13 + tmp12
tmp16 = tmp15 + tmp14
tmp17 = 0.1111111111111111
tmp18 = tmp16 * tmp17
tl.store(out_ptr0 + x3, tmp18, xmask)
@triton.jit
def triton_per_fused_div_exp_max_mul_relu_sum_3(in_ptr0, in_ptr1, in_ptr2,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp3 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr2 + (r1 + 64 * x0), xmask, other=0.0)
tmp10 = tl.load(in_ptr0 + (16 + r1 + 64 * x0), xmask, other=0.0)
tmp13 = tl.load(in_ptr0 + (32 + r1 + 64 * x0), xmask, other=0.0)
tmp16 = tl.load(in_ptr0 + (48 + r1 + 64 * x0), xmask, other=0.0)
tmp23 = tl.load(in_ptr2 + (16 + r1 + 64 * x0), xmask, other=0.0)
tmp31 = tl.load(in_ptr2 + (32 + r1 + 64 * x0), xmask, other=0.0)
tmp39 = tl.load(in_ptr2 + (48 + r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.full([1, 1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = tmp2 / tmp3
tmp5 = tl_math.exp(tmp4)
tmp7 = 9.0
tmp8 = tmp6 * tmp7
tmp9 = tmp5 / tmp8
tmp11 = triton_helpers.maximum(tmp1, tmp10)
tmp12 = triton_helpers.maximum(tmp2, tmp11)
tmp14 = triton_helpers.maximum(tmp1, tmp13)
tmp15 = triton_helpers.maximum(tmp12, tmp14)
tmp17 = triton_helpers.maximum(tmp1, tmp16)
tmp18 = triton_helpers.maximum(tmp15, tmp17)
tmp19 = tmp2 / tmp18
tmp20 = tmp9 * tmp19
tmp21 = tmp11 / tmp3
tmp22 = tl_math.exp(tmp21)
tmp24 = tmp23 * tmp7
tmp25 = tmp22 / tmp24
tmp26 = tmp11 / tmp18
tmp27 = tmp25 * tmp26
tmp28 = triton_helpers.maximum(tmp20, tmp27)
tmp29 = tmp14 / tmp3
tmp30 = tl_math.exp(tmp29)
tmp32 = tmp31 * tmp7
tmp33 = tmp30 / tmp32
tmp34 = tmp14 / tmp18
tmp35 = tmp33 * tmp34
tmp36 = triton_helpers.maximum(tmp28, tmp35)
tmp37 = tmp17 / tmp3
tmp38 = tl_math.exp(tmp37)
tmp40 = tmp39 * tmp7
tmp41 = tmp38 / tmp40
tmp42 = tmp17 / tmp18
tmp43 = tmp41 * tmp42
tmp44 = triton_helpers.maximum(tmp36, tmp43)
tmp45 = tl.broadcast_to(tmp44, [XBLOCK, RBLOCK])
tmp47 = tl.where(xmask, tmp45, 0)
tmp48 = tl.sum(tmp47, 1)[:, None]
tmp49 = tmp44 / tmp48
tl.store(out_ptr2 + (r1 + 16 * x0), tmp49, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_max_0[grid(4)](arg0_1, buf0, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
triton_poi_fused_constant_pad_nd_div_exp_relu_1[grid(576)](arg0_1,
buf0, buf2, 576, XBLOCK=256, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_avg_pool2d_constant_pad_nd_div_exp_relu_2[grid(256)](
buf2, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
buf6 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused_div_exp_max_mul_relu_sum_3[grid(4)](arg0_1, buf0,
buf3, buf6, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del buf0
del buf3
return buf6,
class SoftDetectionModuleNew(nn.Module):
def __init__(self, soft_local_max_size=3):
super(SoftDetectionModuleNew, self).__init__()
self.soft_local_max_size = soft_local_max_size
self.pad = self.soft_local_max_size // 2
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
deep-learning-20/d2-net
|
SoftDetectionModule
| false
| 1,827
|
[
"BSD-3-Clause-Clear"
] | 0
|
b092186353af23e9247c7f56ac2de3396b8c5a00
|
https://github.com/deep-learning-20/d2-net/tree/b092186353af23e9247c7f56ac2de3396b8c5a00
|
AdaptiveAvgPool3dOutSize1
|
import torch
import torch.nn as nn
import torch.utils.data
from abc import abstractmethod
from typing import Tuple
import torch.nn
class EfficientBlockBase(nn.Module):
"""
PyTorchVideo/accelerator provides a set of efficient blocks
that have optimal efficiency for each target hardware device.
Each efficient block has two forms:
- original form: this form is for training. When efficient block is instantiated,
it is in this original form.
- deployable form: this form is for deployment. Once the network is ready for
deploy, it can be converted into deployable form for efficient execution
on target hardware. One block is transformed into deployable form by calling
convert() method. By conversion to deployable form,
various optimization (operator fuse, kernel optimization, etc.) are applied.
EfficientBlockBase is the base class for efficient blocks.
All efficient blocks should inherit this base class
and implement following methods:
- forward(): same as required by nn.Module
- convert(): called to convert block into deployable form
"""
@abstractmethod
def convert(self):
pass
@abstractmethod
def forward(self):
pass
class AdaptiveAvgPool3dOutSize1(EfficientBlockBase):
"""
Implements AdaptiveAvgPool3d with output (T, H, W) = (1, 1, 1). This operator has
better efficiency than AdaptiveAvgPool for mobile CPU.
"""
def __init__(self):
super().__init__()
self.pool = nn.AdaptiveAvgPool3d(1)
self.convert_flag = False
def convert(self, input_blob_size: 'Tuple', **kwargs):
"""
Converts AdaptiveAvgPool into AvgPool with constant kernel size for better
efficiency.
Args:
input_blob_size (tuple): blob size at the input of
AdaptiveAvgPool3dOutSize1 instance during forward.
kwargs (any): any keyword argument (unused).
"""
assert self.convert_flag is False, 'AdaptiveAvgPool3dOutSize1: already converted, cannot be converted again'
kernel_size = input_blob_size[2:]
self.pool = nn.AvgPool3d(kernel_size)
self.convert_flag = True
def forward(self, x):
return self.pool(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
from abc import abstractmethod
from typing import Tuple
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_per_fused_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp5 = 64.0
tmp6 = tmp4 / tmp5
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_mean_0[grid(4)](buf1, arg0_1, 4, 64, XBLOCK=1,
num_warps=2, num_stages=1)
del arg0_1
return buf1,
class EfficientBlockBase(nn.Module):
"""
PyTorchVideo/accelerator provides a set of efficient blocks
that have optimal efficiency for each target hardware device.
Each efficient block has two forms:
- original form: this form is for training. When efficient block is instantiated,
it is in this original form.
- deployable form: this form is for deployment. Once the network is ready for
deploy, it can be converted into deployable form for efficient execution
on target hardware. One block is transformed into deployable form by calling
convert() method. By conversion to deployable form,
various optimization (operator fuse, kernel optimization, etc.) are applied.
EfficientBlockBase is the base class for efficient blocks.
All efficient blocks should inherit this base class
and implement following methods:
- forward(): same as required by nn.Module
- convert(): called to convert block into deployable form
"""
@abstractmethod
def convert(self):
pass
@abstractmethod
def forward(self):
pass
class AdaptiveAvgPool3dOutSize1New(EfficientBlockBase):
"""
Implements AdaptiveAvgPool3d with output (T, H, W) = (1, 1, 1). This operator has
better efficiency than AdaptiveAvgPool for mobile CPU.
"""
def __init__(self):
super().__init__()
self.pool = nn.AdaptiveAvgPool3d(1)
self.convert_flag = False
def convert(self, input_blob_size: 'Tuple', **kwargs):
"""
Converts AdaptiveAvgPool into AvgPool with constant kernel size for better
efficiency.
Args:
input_blob_size (tuple): blob size at the input of
AdaptiveAvgPool3dOutSize1 instance during forward.
kwargs (any): any keyword argument (unused).
"""
assert self.convert_flag is False, 'AdaptiveAvgPool3dOutSize1: already converted, cannot be converted again'
kernel_size = input_blob_size[2:]
self.pool = nn.AvgPool3d(kernel_size)
self.convert_flag = True
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
denred0/pytorchvideo
|
AdaptiveAvgPool3dOutSize1
| false
| 1,828
|
[
"Apache-2.0"
] | 0
|
d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
https://github.com/denred0/pytorchvideo/tree/d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
SELU
|
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
def where(condition, if_true, if_false):
"""
Torch equivalent of numpy.where.
Parameters
----------
condition : torch.ByteTensor or torch.cuda.ByteTensor or torch.autograd.Variable
Condition to check.
if_true : torch.Tensor or torch.cuda.Tensor or torch.autograd.Variable
Output value if condition is true.
if_false: torch.Tensor or torch.cuda.Tensor or torch.autograd.Variable
Output value if condition is false
Returns
-------
torch.Tensor
Raises
------
AssertionError
if if_true and if_false are not both variables or both tensors.
AssertionError
if if_true and if_false don't have the same datatype.
"""
if isinstance(if_true, Variable) or isinstance(if_false, Variable):
assert isinstance(condition, Variable
), 'Condition must be a variable if either if_true or if_false is a variable.'
assert isinstance(if_false, Variable) and isinstance(if_false, Variable
), 'Both if_true and if_false must be variables if either is one.'
assert if_true.data.type() == if_false.data.type(
), 'Type mismatch: {} and {}'.format(if_true.data.type(),
if_false.data.type())
else:
assert not isinstance(condition, Variable
), 'Condition must not be a variable because neither if_true nor if_false is one.'
assert if_true.type() == if_false.type(
), 'Type mismatch: {} and {}'.format(if_true.data.type(),
if_false.data.type())
casted_condition = condition.type_as(if_true)
output = casted_condition * if_true + (1 - casted_condition) * if_false
return output
class SELU(nn.Module):
def forward(self, input):
return self.selu(input)
@staticmethod
def selu(x):
alpha = 1.6732632423543772
scale = 1.0507009873554805
return scale * where(x >= 0, x, alpha * F.elu(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
from torch.autograd import Variable
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__to_copy_add_elu_ge_mul_rsub_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.0
tmp2 = tmp0 >= tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tmp3 * tmp0
tmp5 = 1.0
tmp6 = tmp5 - tmp3
tmp7 = tmp0 > tmp1
tmp8 = tmp0 * tmp5
tmp9 = libdevice.expm1(tmp8)
tmp10 = tmp9 * tmp5
tmp11 = tl.where(tmp7, tmp8, tmp10)
tmp12 = 1.6732632423543772
tmp13 = tmp11 * tmp12
tmp14 = tmp6 * tmp13
tmp15 = tmp4 + tmp14
tmp16 = 1.0507009873554805
tmp17 = tmp15 * tmp16
tl.store(out_ptr0 + x0, tmp17, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__to_copy_add_elu_ge_mul_rsub_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def where(condition, if_true, if_false):
"""
Torch equivalent of numpy.where.
Parameters
----------
condition : torch.ByteTensor or torch.cuda.ByteTensor or torch.autograd.Variable
Condition to check.
if_true : torch.Tensor or torch.cuda.Tensor or torch.autograd.Variable
Output value if condition is true.
if_false: torch.Tensor or torch.cuda.Tensor or torch.autograd.Variable
Output value if condition is false
Returns
-------
torch.Tensor
Raises
------
AssertionError
if if_true and if_false are not both variables or both tensors.
AssertionError
if if_true and if_false don't have the same datatype.
"""
if isinstance(if_true, Variable) or isinstance(if_false, Variable):
assert isinstance(condition, Variable
), 'Condition must be a variable if either if_true or if_false is a variable.'
assert isinstance(if_false, Variable) and isinstance(if_false, Variable
), 'Both if_true and if_false must be variables if either is one.'
assert if_true.data.type() == if_false.data.type(
), 'Type mismatch: {} and {}'.format(if_true.data.type(),
if_false.data.type())
else:
assert not isinstance(condition, Variable
), 'Condition must not be a variable because neither if_true nor if_false is one.'
assert if_true.type() == if_false.type(
), 'Type mismatch: {} and {}'.format(if_true.data.type(),
if_false.data.type())
casted_condition = condition.type_as(if_true)
output = casted_condition * if_true + (1 - casted_condition) * if_false
return output
class SELUNew(nn.Module):
@staticmethod
def selu(x):
alpha = 1.6732632423543772
scale = 1.0507009873554805
return scale * where(x >= 0, x, alpha * F.elu(x))
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
dearkafka/inferno
|
SELU
| false
| 1,829
|
[
"Apache-2.0"
] | 0
|
e9e3b863fd1fc97cf94d08ac6b4f8df7665f996a
|
https://github.com/dearkafka/inferno/tree/e9e3b863fd1fc97cf94d08ac6b4f8df7665f996a
|
BatchDHCN
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils
import torch.utils.data
import torch.optim
class BatchDHCN(nn.Module):
"""docstring for BatchDHCN"""
def __init__(self, embed_size=512, output_size=512, num_channel=2,
conv_size=3, batch_norm=True):
super(BatchDHCN, self).__init__()
self.batch_norm = batch_norm
self.embed_size = embed_size
self.output_size = output_size
self.num_channel = num_channel
self.padding = nn.ZeroPad2d((0, conv_size - 1, conv_size - 1, 0))
self.conv_1 = nn.Conv2d(self.num_channel, self.output_size, (
conv_size, conv_size))
self.dropout = nn.Dropout(p=0.5)
def forward(self, x):
x_conv_1 = self.conv_1(self.padding(x))
x_conv_1 = F.relu(x_conv_1)
return x_conv_1
def get_inputs():
return [torch.rand([4, 2, 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
import torch.nn as nn
import torch.utils
import torch.utils.data
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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 2
y1 = yindex // 2
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 2 * x2 + 18 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_constant_pad_nd_1(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 8
xnumel = 36
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x3 = xindex // 6
x2 = xindex % 6
y4 = yindex
x5 = xindex
y0 = yindex % 2
y1 = yindex // 2
tmp0 = -2 + x3
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = x2
tmp4 = tl.full([1, 1], 4, tl.int64)
tmp5 = tmp3 < tmp4
tmp6 = tmp2 & tmp5
tmp7 = tl.load(in_ptr0 + (-8 + x2 + 4 * x3 + 16 * y4), tmp6 & xmask &
ymask, eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (y0 + 2 * x5 + 72 * y1), tmp7, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_2(in_ptr0, in_ptr1,
out_ptr0, out_ptr1, 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 % 512
y1 = yindex // 512
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 512 * x2 + 8192 * y1), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1, 1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + (x2 + 16 * y3), tmp4, xmask)
tl.store(out_ptr1 + (y0 + 512 * x2 + 8192 * y1), tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 2, 4, 4), (32, 16, 4, 1))
assert_size_stride(primals_2, (512, 2, 3, 3), (18, 9, 3, 1))
assert_size_stride(primals_3, (512,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((512, 2, 3, 3), (18, 1, 6, 2), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(1024, 9)](primals_2, buf0, 1024, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_2
buf1 = empty_strided_cuda((4, 2, 6, 6), (72, 1, 12, 2), torch.float32)
triton_poi_fused_constant_pad_nd_1[grid(8, 36)](primals_1, buf1, 8,
36, XBLOCK=32, YBLOCK=8, num_warps=4, num_stages=1)
del primals_1
buf2 = 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(buf2, (4, 512, 4, 4), (8192, 1, 2048, 512))
buf3 = empty_strided_cuda((4, 512, 4, 4), (8192, 16, 4, 1), torch.
float32)
buf4 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_2[grid(2048, 16)](
buf2, primals_3, buf3, buf4, 2048, 16, XBLOCK=16, YBLOCK=64,
num_warps=4, num_stages=1)
del buf2
del primals_3
return buf3, buf0, buf1, buf4
class BatchDHCNNew(nn.Module):
"""docstring for BatchDHCN"""
def __init__(self, embed_size=512, output_size=512, num_channel=2,
conv_size=3, batch_norm=True):
super(BatchDHCNNew, self).__init__()
self.batch_norm = batch_norm
self.embed_size = embed_size
self.output_size = output_size
self.num_channel = num_channel
self.padding = nn.ZeroPad2d((0, conv_size - 1, conv_size - 1, 0))
self.conv_1 = nn.Conv2d(self.num_channel, self.output_size, (
conv_size, conv_size))
self.dropout = nn.Dropout(p=0.5)
def forward(self, input_0):
primals_2 = self.conv_1.weight
primals_3 = self.conv_1.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
deeplearning2020/self
|
BatchDHCN
| false
| 1,830
|
[
"MIT"
] | 0
|
cf0e6f9acdcfe17906c6327042d25ac9c8894885
|
https://github.com/deeplearning2020/self/tree/cf0e6f9acdcfe17906c6327042d25ac9c8894885
|
DenseSAGEConv
|
import math
import torch
import torch.nn.functional as F
import torch.utils.data
from torch.nn import Parameter
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class DenseSAGEConv(torch.nn.Module):
def __init__(self, in_channels, out_channels, norm=True, norm_embed=
True, bias=True):
super(DenseSAGEConv, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.norm = norm
self.norm_embed = norm_embed
self.weight = Parameter(torch.Tensor(self.in_channels, out_channels))
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
uniform(self.in_channels, self.weight)
uniform(self.in_channels, self.bias)
def forward(self, x, adj):
x = x.unsqueeze(0) if x.dim() == 2 else x
adj = adj.unsqueeze(0) if adj.dim() == 2 else adj
out = torch.matmul(adj, x)
if self.norm:
out = out / adj.sum(dim=-1, keepdim=True)
out = torch.matmul(out, self.weight)
if self.bias is not None:
out = out + self.bias
if self.norm_embed:
out = F.normalize(out, p=2, dim=-1)
return out
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.
in_channels, self.out_channels)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import math
import torch.utils.data
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_div_sum_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
x1 = xindex // 4
tmp0 = tl.load(in_out_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(in_out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_add_clamp_min_linalg_vector_norm_1(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp5 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + 1)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + 2)
tmp13 = tl.broadcast_to(tmp12, [XBLOCK])
tmp17 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr1 + 3)
tmp19 = tl.broadcast_to(tmp18, [XBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tmp3 * tmp3
tmp8 = tmp5 + tmp7
tmp9 = tmp8 * tmp8
tmp10 = tmp4 + tmp9
tmp14 = tmp11 + tmp13
tmp15 = tmp14 * tmp14
tmp16 = tmp10 + tmp15
tmp20 = tmp17 + tmp19
tmp21 = tmp20 * tmp20
tmp22 = tmp16 + tmp21
tmp23 = libdevice.sqrt(tmp22)
tmp24 = 1e-12
tmp25 = triton_helpers.maximum(tmp23, tmp24)
tl.store(out_ptr0 + x0, tmp25, xmask)
@triton.jit
def triton_poi_fused_add_div_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
x0 = xindex % 4
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 / tmp3
tl.store(out_ptr0 + x2, 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, (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((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_2, (16, 4, 4), (16, 4,
1), 0), reinterpret_tensor(primals_1, (16, 4, 4), (16, 4, 1), 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_div_sum_0[grid(256)](buf1, primals_2, 256, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
primals_3, out=buf2)
del primals_3
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused_add_clamp_min_linalg_vector_norm_1[grid(64)](buf2,
primals_4, 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_add_div_2[grid(256)](buf2, primals_4, buf3, buf4,
256, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
return buf4, primals_4, buf2, reinterpret_tensor(buf1, (4, 64), (1, 4), 0)
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
class DenseSAGEConvNew(torch.nn.Module):
def __init__(self, in_channels, out_channels, norm=True, norm_embed=
True, bias=True):
super(DenseSAGEConvNew, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.norm = norm
self.norm_embed = norm_embed
self.weight = Parameter(torch.Tensor(self.in_channels, out_channels))
if bias:
self.bias = Parameter(torch.Tensor(out_channels))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
uniform(self.in_channels, self.weight)
uniform(self.in_channels, self.bias)
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.
in_channels, self.out_channels)
def forward(self, input_0, input_1):
primals_3 = self.weight
primals_4 = self.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
dendisuhubdy/pytorch_geometric
|
DenseSAGEConv
| false
| 1,831
|
[
"MIT"
] | 0
|
a0592f61aef617c0c8ff61b3d822d04901054c22
|
https://github.com/dendisuhubdy/pytorch_geometric/tree/a0592f61aef617c0c8ff61b3d822d04901054c22
|
MaskedMSE
|
import torch
import torch.nn as nn
class MaskedMSE(nn.Module):
def __init__(self):
super(MaskedMSE, self).__init__()
self.criterion = nn.MSELoss()
def forward(self, input, target, gamma=2.0):
mask = gamma * target / (target + 1e-07)
self.loss = self.criterion(input * mask, target * mask)
return self.loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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,
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 = 2.0
tmp3 = tmp1 * tmp2
tmp4 = 1e-07
tmp5 = tmp1 + tmp4
tmp6 = tmp3 / tmp5
tmp7 = tmp0 * tmp6
tmp8 = tmp1 * tmp6
tmp9 = tmp7 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tl.broadcast_to(tmp10, [RBLOCK])
tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0))
tmp14 = 256.0
tmp15 = tmp13 / tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_div_mse_loss_mul_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 MaskedMSENew(nn.Module):
def __init__(self):
super(MaskedMSENew, self).__init__()
self.criterion = nn.MSELoss()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dhruvramani/AccentTransfer
|
MaskedMSE
| false
| 1,832
|
[
"MIT"
] | 0
|
63a35b4aa37bc41c1f66dfb4bae76e2924183d7c
|
https://github.com/dhruvramani/AccentTransfer/tree/63a35b4aa37bc41c1f66dfb4bae76e2924183d7c
|
adaILN
|
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class adaILN(nn.Module):
def __init__(self, num_features, eps=1e-05):
super(adaILN, self).__init__()
self.eps = eps
self.rho = Parameter(torch.Tensor(1, num_features, 1, 1))
self.rho.data.fill_(0.9)
def forward(self, input, gamma, beta):
in_mean, in_var = torch.mean(input, dim=[2, 3], keepdim=True
), torch.var(input, dim=[2, 3], keepdim=True)
out_in = (input - in_mean) / torch.sqrt(in_var + self.eps)
ln_mean, ln_var = torch.mean(input, dim=[1, 2, 3], keepdim=True
), torch.var(input, dim=[1, 2, 3], keepdim=True)
out_ln = (input - ln_mean) / torch.sqrt(ln_var + self.eps)
out = self.rho.expand(input.shape[0], -1, -1, -1) * out_in + (1 -
self.rho.expand(input.shape[0], -1, -1, -1)) * out_ln
out = out * gamma.unsqueeze(2).unsqueeze(3) + beta.unsqueeze(2
).unsqueeze(3)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_features': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn.parameter import Parameter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_add_mean_sqrt_var_0(in_out_ptr0, in_out_ptr1, in_ptr0,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 64.0
tmp20 = tmp4 / tmp19
tmp21 = 63.0
tmp22 = tmp18 / tmp21
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.sqrt(tmp24)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp25, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_rsub_sqrt_sub_var_1(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
x2 = xindex % 4
x3 = xindex // 4
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp26 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp32 = tl.load(in_ptr2 + x3, xmask, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr3 + x3, xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, 0)
tmp4 = tl.sum(tmp3, 1)[:, None]
tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tmp10 = tl.full([XBLOCK, 1], 16, tl.int32)
tmp11 = tmp10.to(tl.float32)
tmp12 = tmp9 / tmp11
tmp13 = tmp1 - tmp12
tmp14 = tmp13 * tmp13
tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK])
tmp17 = tl.where(xmask, tmp15, 0)
tmp18 = tl.sum(tmp17, 1)[:, None]
tmp19 = 16.0
tmp20 = tmp4 / tmp19
tmp21 = 15.0
tmp22 = tmp18 / tmp21
tmp23 = 1e-05
tmp24 = tmp22 + tmp23
tmp25 = libdevice.sqrt(tmp24)
tmp27 = tmp0 - tmp20
tmp28 = tmp27 / tmp25
tmp29 = tmp26 * tmp28
tmp30 = 1.0
tmp31 = tmp30 - tmp26
tmp33 = tmp0 - tmp32
tmp35 = tmp33 / tmp34
tmp36 = tmp31 * tmp35
tmp37 = tmp29 + tmp36
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, xmask)
tl.debug_barrier()
tl.store(in_out_ptr1 + x0, tmp25, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp37, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_rsub_sub_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex % 256
x0 = xindex % 16
x2 = xindex // 256
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (x0 + 16 * x2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr2 + (x0 + 16 * x2), None, eviction_policy='evict_last'
)
tmp2 = tmp0 * tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + x4, tmp4, None)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (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)
buf6 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf9 = empty_strided_cuda((4, 1, 1, 1), (1, 4, 4, 4), torch.float32)
buf7 = reinterpret_tensor(buf6, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf6
buf11 = reinterpret_tensor(buf9, (4, 1, 1, 1), (1, 1, 1, 1), 0)
del buf9
get_raw_stream(0)
triton_per_fused_add_mean_sqrt_var_0[grid(4)](buf7, buf11,
primals_1, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf0
buf5 = reinterpret_tensor(buf3, (4, 4, 1, 1), (4, 1, 1, 1), 0)
del buf3
buf12 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_per_fused_add_div_mean_mul_rsub_sqrt_sub_var_1[grid(16)](buf1,
buf5, primals_1, primals_2, buf7, buf11, buf12, 16, 16, XBLOCK=
8, num_warps=2, num_stages=1)
del primals_2
buf13 = empty_strided_cuda((4, 4, 4, 4, 4, 4), (1024, 256, 64, 16,
4, 1), torch.float32)
triton_poi_fused_add_div_mul_rsub_sub_2[grid(4096)](buf12,
primals_3, primals_4, buf13, 4096, XBLOCK=256, num_warps=4,
num_stages=1)
del buf12
del primals_4
return buf13, primals_1, primals_3, buf1, buf5, buf7, buf11
class adaILNNew(nn.Module):
def __init__(self, num_features, eps=1e-05):
super(adaILNNew, self).__init__()
self.eps = eps
self.rho = Parameter(torch.Tensor(1, num_features, 1, 1))
self.rho.data.fill_(0.9)
def forward(self, input_0, input_1, input_2):
primals_2 = self.rho
primals_1 = input_0
primals_3 = input_1
primals_4 = input_2
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
denny3388/Conditional-UGATIT
|
adaILN
| false
| 1,833
|
[
"MIT"
] | 0
|
86ad35f05aaa105a814dec031d37370f44b71d5b
|
https://github.com/denny3388/Conditional-UGATIT/tree/86ad35f05aaa105a814dec031d37370f44b71d5b
|
MaskedTemporalPooling
|
import torch
import torch.utils.data
from typing import Optional
import torch.nn
class MaskedTemporalPooling(torch.nn.Module):
"""
Applies temporal pooling operations on masked inputs. For each pooling operation
all masked values are ignored.
"""
def __init__(self, method: 'str'):
"""
method (str): the method of pooling to use. Options:
'max': reduces temporal dimension to each valid max value.
'avg': averages valid values in the temporal dimension.
'sum': sums valid values in the temporal dimension.
Note if all batch row elements are invalid, the temporal dimension is
pooled to 0 values.
"""
super().__init__()
assert method in ('max', 'avg', 'sum')
self._method = method
def forward(self, x: 'torch.Tensor', mask: 'Optional[torch.Tensor]'=None
) ->torch.Tensor:
"""
Args:
x (torch.Tensor): tensor with shape (batch_size, seq_len, feature_dim)
mask (torch.Tensor): bool tensor with shape (batch_size, seq_len).
Sequence elements that are False are invalid.
Returns:
Tensor with shape (batch_size, feature_dim)
"""
assert x.dim(
) == 3, 'Requires x shape (batch_size x seq_len x feature_dim)'
b, t = x.shape[0], x.shape[1]
if mask is None:
mask = torch.ones((b, t), dtype=torch.bool)
if self._method == 'max':
x[~mask, :] = float('-inf')
invalid_first_dim = ~mask.view(b, -1).any(dim=-1)
x[invalid_first_dim, :] = 0
x = torch.max(x, dim=1)[0]
elif self._method == 'avg':
x = x * mask.unsqueeze(-1).float()
mask = mask.view(b, t, -1).any(dim=-1)
valid_lengths = mask.float().sum(dim=-1).int()
x = x.sum(dim=1)
x = x.div(valid_lengths.clamp(min=1).unsqueeze(-1).expand(x.
size()).float())
elif self._method == 'sum':
x = x * mask.unsqueeze(-1).float()
x = x.sum(dim=1)
else:
raise NotImplementedError(
f"{self._method} not available options are: 'max', 'avg', 'sum'"
)
return x
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'method': 'max'}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_index_put_lift_fresh_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], False, tl.int1)
tmp2 = float('-inf')
tmp3 = tl.where(tmp1, tmp2, tmp0)
tl.store(out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_index_put_lift_fresh_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp5 = tl.load(in_ptr0 + x0, xmask)
tmp0 = tl.full([1], True, tl.int1)
tmp1 = tmp0 | tmp0
tmp2 = tmp1 | tmp0
tmp3 = tmp2 | tmp0
tmp4 = tmp3 == 0
tmp6 = 0.0
tmp7 = tl.where(tmp4, tmp6, tmp5)
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_poi_fused_max_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp4 = triton_helpers.maximum(tmp2, tmp3)
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
get_raw_stream(0)
triton_poi_fused_index_put_lift_fresh_0[grid(64)](arg0_1, arg0_1,
64, XBLOCK=64, num_warps=1, num_stages=1)
triton_poi_fused_index_put_lift_fresh_1[grid(64)](arg0_1, arg0_1,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_max_2[grid(16)](arg0_1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg0_1
return buf2,
class MaskedTemporalPoolingNew(torch.nn.Module):
"""
Applies temporal pooling operations on masked inputs. For each pooling operation
all masked values are ignored.
"""
def __init__(self, method: 'str'):
"""
method (str): the method of pooling to use. Options:
'max': reduces temporal dimension to each valid max value.
'avg': averages valid values in the temporal dimension.
'sum': sums valid values in the temporal dimension.
Note if all batch row elements are invalid, the temporal dimension is
pooled to 0 values.
"""
super().__init__()
assert method in ('max', 'avg', 'sum')
self._method = method
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
denred0/pytorchvideo
|
MaskedTemporalPooling
| false
| 1,834
|
[
"Apache-2.0"
] | 0
|
d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
https://github.com/denred0/pytorchvideo/tree/d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
TemporalConvNet
|
import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x, pad_right=True):
return x[:, :, :-self.chomp_size].contiguous() if pad_right else x[
:, :, self.chomp_size:]
class TemporalBlock(nn.Module):
def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation,
padding, dropout):
super(TemporalBlock, self).__init__()
self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size,
stride=stride, padding=padding, dilation=dilation))
self.chomp1 = Chomp1d(padding)
self.relu1 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout1 = nn.Dropout(dropout)
self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs,
kernel_size, stride=stride, padding=padding, dilation=dilation))
self.chomp2 = Chomp1d(padding)
self.relu2 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout2 = nn.Dropout(dropout)
self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.
dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2)
self.downsample = nn.Conv1d(n_inputs, n_outputs, 1
) if n_inputs != n_outputs else None
self.relu = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.init_weights()
def init_weights(self):
self.conv1.weight.data.normal_(0, 0.01)
self.conv2.weight.data.normal_(0, 0.01)
if self.downsample is not None:
self.downsample.weight.data.normal_(0, 0.01)
def forward(self, x):
out = self.net(x)
res = x if self.downsample is None else self.downsample(x)
return self.relu(out + res)
class TemporalConvNet(nn.Module):
def __init__(self, num_inputs, num_channels, kernel_size, stride, dropout):
super(TemporalConvNet, self).__init__()
self.network = nn.Sequential()
for i, nch in enumerate(num_channels):
dilation = 2 ** i
in_channels = num_inputs if i == 0 else num_channels[i - 1]
out_channels = num_channels[i]
padding = (kernel_size - 1) * dilation
self.network.add_module('tblock' + str(i), TemporalBlock(
n_inputs=in_channels, n_outputs=out_channels, kernel_size=
kernel_size, stride=stride, dilation=dilation, padding=
padding, dropout=dropout))
def forward(self, x):
return self.network(x)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'num_channels': [4, 4], 'kernel_size': 4,
'stride': 1, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn.utils import weight_norm
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__weight_norm_interface_0(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp7 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = libdevice.sqrt(tmp5)
tmp8 = tmp7 / tmp6
tmp9 = tmp0 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp9, xmask)
@triton.jit
def triton_poi_fused_clone_leaky_relu_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 % 4
x3 = xindex // 4
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 7 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_add_clone_leaky_relu_2(in_ptr0, in_ptr1, in_ptr2,
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
x3 = xindex // 4
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 7 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + x4, xmask)
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp9 = tmp7 + tmp8
tmp10 = tmp9 > tmp3
tmp11 = tmp9 * tmp5
tmp12 = tl.where(tmp10, tmp9, tmp11)
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp10, xmask)
tl.store(out_ptr2 + x4, tmp12, xmask)
@triton.jit
def triton_poi_fused_clone_leaky_relu_3(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 % 4
x3 = xindex // 4
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 10 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_add_clone_leaky_relu_4(in_ptr0, in_ptr1, in_ptr2,
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
x3 = xindex // 4
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 10 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + x4, xmask)
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tmp9 = tmp7 + tmp8
tmp10 = tmp9 > tmp3
tmp11 = tmp9 * tmp5
tmp12 = tl.where(tmp10, tmp9, tmp11)
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp10, xmask)
tl.store(out_ptr2 + x4, tmp12, 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, 1, 1), (1, 1, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 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, 1, 1), (1, 1, 1))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_12, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 1, 1), (1, 1, 1), 0)
del buf0
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__weight_norm_interface_0[grid(4)](buf1, primals_2,
primals_1, buf2, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = extern_kernels.convolution(primals_4, buf2, stride=(1,),
padding=(3,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 7), (28, 7, 1))
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_leaky_relu_1[grid(64)](buf3, primals_3, buf4,
buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf3
del primals_3
buf6 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf7 = reinterpret_tensor(buf6, (4, 1, 1), (1, 1, 1), 0)
del buf6
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused__weight_norm_interface_0[grid(4)](buf7, primals_6,
primals_5, buf8, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf9 = extern_kernels.convolution(buf5, buf8, stride=(1,), padding=
(3,), dilation=(1,), transposed=False, output_padding=(0,),
groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 7), (28, 7, 1))
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_clone_leaky_relu_2[grid(64)](buf9, primals_7,
primals_4, buf10, buf11, buf12, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf9
del primals_7
buf13 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf14 = reinterpret_tensor(buf13, (4, 1, 1), (1, 1, 1), 0)
del buf13
buf15 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused__weight_norm_interface_0[grid(4)](buf14, primals_9,
primals_8, buf15, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf16 = extern_kernels.convolution(buf12, buf15, stride=(1,),
padding=(6,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf16, (4, 4, 10), (40, 10, 1))
buf17 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_leaky_relu_3[grid(64)](buf16, primals_10,
buf17, buf18, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf16
del primals_10
buf19 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf20 = reinterpret_tensor(buf19, (4, 1, 1), (1, 1, 1), 0)
del buf19
buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused__weight_norm_interface_0[grid(4)](buf20,
primals_12, primals_11, buf21, 4, 16, XBLOCK=1, num_warps=2,
num_stages=1)
buf22 = extern_kernels.convolution(buf18, buf21, stride=(1,),
padding=(6,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf22, (4, 4, 10), (40, 10, 1))
buf23 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf24 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf25 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_clone_leaky_relu_4[grid(64)](buf22, primals_13,
buf12, buf23, buf24, buf25, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf22
del primals_13
return (buf25, buf2, buf8, buf15, buf21, primals_1, primals_2,
primals_4, primals_5, primals_6, primals_8, primals_9, primals_11,
primals_12, buf1, buf2, buf4, buf5, buf7, buf8, buf10, buf11, buf12,
buf14, buf15, buf17, buf18, buf20, buf21, buf23, buf24)
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x, pad_right=True):
return x[:, :, :-self.chomp_size].contiguous() if pad_right else x[
:, :, self.chomp_size:]
class TemporalBlock(nn.Module):
def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation,
padding, dropout):
super(TemporalBlock, self).__init__()
self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size,
stride=stride, padding=padding, dilation=dilation))
self.chomp1 = Chomp1d(padding)
self.relu1 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout1 = nn.Dropout(dropout)
self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs,
kernel_size, stride=stride, padding=padding, dilation=dilation))
self.chomp2 = Chomp1d(padding)
self.relu2 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout2 = nn.Dropout(dropout)
self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.
dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2)
self.downsample = nn.Conv1d(n_inputs, n_outputs, 1
) if n_inputs != n_outputs else None
self.relu = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.init_weights()
def init_weights(self):
self.conv1.weight.data.normal_(0, 0.01)
self.conv2.weight.data.normal_(0, 0.01)
if self.downsample is not None:
self.downsample.weight.data.normal_(0, 0.01)
def forward(self, x):
out = self.net(x)
res = x if self.downsample is None else self.downsample(x)
return self.relu(out + res)
class TemporalConvNetNew(nn.Module):
def __init__(self, num_inputs, num_channels, kernel_size, stride, dropout):
super(TemporalConvNetNew, self).__init__()
self.network = nn.Sequential()
for i, nch in enumerate(num_channels):
dilation = 2 ** i
in_channels = num_inputs if i == 0 else num_channels[i - 1]
out_channels = num_channels[i]
padding = (kernel_size - 1) * dilation
self.network.add_module('tblock' + str(i), TemporalBlock(
n_inputs=in_channels, n_outputs=out_channels, kernel_size=
kernel_size, stride=stride, dilation=dilation, padding=
padding, dropout=dropout))
def forward(self, input_0):
primals_3 = self.network.tblock0.conv1.bias
primals_1 = self.network.tblock0.conv1.weight_g
primals_2 = self.network.tblock0.conv1.weight_v
primals_7 = self.network.tblock0.conv2.bias
primals_5 = self.network.tblock0.conv2.weight_g
primals_4 = self.network.tblock0.conv2.weight_v
primals_10 = self.network.tblock1.conv1.bias
primals_8 = self.network.tblock1.conv1.weight_g
primals_6 = self.network.tblock1.conv1.weight_v
primals_13 = self.network.tblock1.conv2.bias
primals_11 = self.network.tblock1.conv2.weight_g
primals_9 = self.network.tblock1.conv2.weight_v
primals_12 = 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]
|
ddcas/singing-language-identification
|
TemporalConvNet
| false
| 1,835
|
[
"MIT"
] | 0
|
d104419b196d56d4de37cff47c32e88e28c58690
|
https://github.com/ddcas/singing-language-identification/tree/d104419b196d56d4de37cff47c32e88e28c58690
|
NaiveTorchNet
|
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.autograd
import torch.optim as optim
class NaiveTorchNet(nn.Module):
"""A reimplementation of from-scratch NaiveNet using PyTorch"""
def __init__(self, input_nodes, hidden_nodes, output_nodes, learn_rate=0.1
):
super().__init__()
self.hidden = nn.Linear(input_nodes, hidden_nodes, bias=False)
self.output = nn.Linear(hidden_nodes, output_nodes, bias=False)
self.lr = learn_rate
self.activation_function = nn.Sigmoid()
self.optimizer = optim.SGD(self.parameters(), lr=learn_rate)
self.loss_function = nn.MSELoss()
def forward(self, x):
"""Overrides the built in"""
x = self.activation_function(self.hidden(x))
x = self.activation_function(self.output(x))
return x
def query(self, inputs):
"""Takes an input to the net and returns an output via forward computation"""
if type(inputs) != torch.autograd.variable.Variable:
inputs = Variable(torch.Tensor(inputs))
return {'i': inputs, 'fo': self.forward(inputs)}
def learn(self, targets, input_layers):
if type(targets) != torch.autograd.variable.Variable:
targets = Variable(torch.Tensor(targets))
final_outputs = input_layers['fo']
output_errors = self.loss_function(final_outputs, targets)
self.optimizer.zero_grad()
output_errors.backward()
self.optimizer.step()
return output_errors, final_outputs
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_nodes': 4, 'hidden_nodes': 4, 'output_nodes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch.autograd import Variable
import torch.nn as nn
import torch.autograd
import torch.optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_sigmoid_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.sigmoid(tmp0)
tl.store(in_out_ptr0 + x0, tmp1, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (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, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_sigmoid_0[grid(256)](buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_sigmoid_0[grid(256)](buf3, 256, XBLOCK=128,
num_warps=4, num_stages=1)
return buf3, reinterpret_tensor(primals_2, (64, 4), (4, 1), 0
), buf1, buf3, primals_3
class NaiveTorchNetNew(nn.Module):
"""A reimplementation of from-scratch NaiveNet using PyTorch"""
def __init__(self, input_nodes, hidden_nodes, output_nodes, learn_rate=0.1
):
super().__init__()
self.hidden = nn.Linear(input_nodes, hidden_nodes, bias=False)
self.output = nn.Linear(hidden_nodes, output_nodes, bias=False)
self.lr = learn_rate
self.activation_function = nn.Sigmoid()
self.optimizer = optim.SGD(self.parameters(), lr=learn_rate)
self.loss_function = nn.MSELoss()
def query(self, inputs):
"""Takes an input to the net and returns an output via forward computation"""
if type(inputs) != torch.autograd.variable.Variable:
inputs = Variable(torch.Tensor(inputs))
return {'i': inputs, 'fo': self.forward(inputs)}
def learn(self, targets, input_layers):
if type(targets) != torch.autograd.variable.Variable:
targets = Variable(torch.Tensor(targets))
final_outputs = input_layers['fo']
output_errors = self.loss_function(final_outputs, targets)
self.optimizer.zero_grad()
output_errors.backward()
self.optimizer.step()
return output_errors, final_outputs
def forward(self, input_0):
primals_1 = self.hidden.weight
primals_3 = self.output.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
deo1/deo1
|
NaiveTorchNet
| false
| 1,836
|
[
"MIT"
] | 0
|
36671f12269d3bd662d746e8b9f66c22255c9df7
|
https://github.com/deo1/deo1/tree/36671f12269d3bd662d746e8b9f66c22255c9df7
|
Attn
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attn(nn.Module):
def __init__(self, hidden_size, batch_size=1, method='dot'):
super(Attn, self).__init__()
self.method = method
self.hidden_size = hidden_size
self.batch_size = batch_size
if self.method == 'general':
self.attn = nn.Linear(self.hidden_size, hidden_size, bias=False)
elif self.method == 'concat':
self.attn = nn.Linear(self.hidden_size * 2, hidden_size, bias=False
)
self.v = nn.Parameter(torch.FloatTensor(batch_size, 1, hidden_size)
)
def forward(self, hidden, encoder_outputs):
attn_energies = self.score(hidden, encoder_outputs)
return F.softmax(attn_energies, dim=2)
def score(self, hidden, encoder_output):
if self.method == 'general':
energy = self.attn(encoder_output)
energy = energy.transpose(2, 1)
energy = hidden.bmm(energy)
return energy
elif self.method == 'concat':
hidden = hidden * encoder_output.new_ones(encoder_output.size())
energy = self.attn(torch.cat((hidden, encoder_output), -1))
energy = energy.transpose(2, 1)
energy = self.v.bmm(energy)
return energy
else:
encoder_output = encoder_output.transpose(2, 1)
energy = hidden.bmm(encoder_output)
return energy
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(arg1_1, reinterpret_tensor(arg0_1, (4, 4, 4), (
16, 1, 4), 0), out=buf0)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = buf0
del buf0
triton_poi_fused__softmax_1[grid(64)](buf1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf1
return buf2,
class AttnNew(nn.Module):
def __init__(self, hidden_size, batch_size=1, method='dot'):
super(AttnNew, self).__init__()
self.method = method
self.hidden_size = hidden_size
self.batch_size = batch_size
if self.method == 'general':
self.attn = nn.Linear(self.hidden_size, hidden_size, bias=False)
elif self.method == 'concat':
self.attn = nn.Linear(self.hidden_size * 2, hidden_size, bias=False
)
self.v = nn.Parameter(torch.FloatTensor(batch_size, 1, hidden_size)
)
def score(self, hidden, encoder_output):
if self.method == 'general':
energy = self.attn(encoder_output)
energy = energy.transpose(2, 1)
energy = hidden.bmm(energy)
return energy
elif self.method == 'concat':
hidden = hidden * encoder_output.new_ones(encoder_output.size())
energy = self.attn(torch.cat((hidden, encoder_output), -1))
energy = energy.transpose(2, 1)
energy = self.v.bmm(energy)
return energy
else:
encoder_output = encoder_output.transpose(2, 1)
energy = hidden.bmm(encoder_output)
return energy
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dhpollack/mgc
|
Attn
| false
| 1,837
|
[
"MIT"
] | 0
|
ed1b8fb512f0b42cb8121a2809def65f232dc154
|
https://github.com/dhpollack/mgc/tree/ed1b8fb512f0b42cb8121a2809def65f232dc154
|
PositiveLinear
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class PositiveLinear(nn.Linear):
"""Applies a transformation to the incoming data of the following form: :math:`y_i = xlog(exp(A)+1)^T`
where log and exp are elementwise operations.
Args:
in_features: size of each input sample
out_features: size of each output sample
bias: If set to False, the layer will not learn an additive bias.
Default: ``True``
Shape:
- Input: :math:`(N, *, in\\_features)` where :math:`*` means any number of
additional dimensions
- Output: :math:`(N, *, out\\_features)` where all but the last dimension
are the same shape as the input.
Attributes:
weight: the learnable weights of the module of shape
`(out_features x in_features)`
bias: the learnable bias of the module of shape `(out_features)`
Examples::
>>> m = nn.PositiveLinear(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
"""
def forward(self, input):
transformed_weight = torch.clamp(self.weight, min=0)
torch.clamp(self.bias, min=0)
return F.linear(input, transformed_weight, self.bias)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'out_features': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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_clamp_ge_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 + x0, xmask)
tmp1 = 0.0
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tmp0 >= tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_clamp_ge_0[grid(16)](primals_1, buf0, buf2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf1)
del buf0
del primals_2
return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf2
class PositiveLinearNew(nn.Linear):
"""Applies a transformation to the incoming data of the following form: :math:`y_i = xlog(exp(A)+1)^T`
where log and exp are elementwise operations.
Args:
in_features: size of each input sample
out_features: size of each output sample
bias: If set to False, the layer will not learn an additive bias.
Default: ``True``
Shape:
- Input: :math:`(N, *, in\\_features)` where :math:`*` means any number of
additional dimensions
- Output: :math:`(N, *, out\\_features)` where all but the last dimension
are the same shape as the input.
Attributes:
weight: the learnable weights of the module of shape
`(out_features x in_features)`
bias: the learnable bias of the module of shape `(out_features)`
Examples::
>>> m = nn.PositiveLinear(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
"""
def forward(self, input_0):
primals_1 = self.weight
primals_2 = self.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dfioravanti/copula_vae
|
PositiveLinear
| false
| 1,838
|
[
"MIT"
] | 0
|
4fdadfb9ca65a75367d50df4a5848942de20741f
|
https://github.com/dfioravanti/copula_vae/tree/4fdadfb9ca65a75367d50df4a5848942de20741f
|
PrimaryCaps
|
import torch
import torch.nn as nn
class PrimaryCaps(nn.Module):
"""
输入:(B,C,H,W)=(B,256,20,20)
输出:(B,C_N,C_L)=(B,32*6*6, 8)=(B,1152,8)
C_N:capsule_num,胶囊的个数
C_L:capsule_length,每个胶囊的长度
"""
def __init__(self, capsule_length=8, in_channels=256, out_channels=32,
capsule_num=32 * 6 * 6, kernel_size=9, stride=2, padding=0):
super(PrimaryCaps, self).__init__()
self.capsule_length = capsule_length
self.capsule_num = capsule_num
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels * capsule_length, kernel_size=kernel_size, stride=
stride, padding=padding)
def forward(self, x):
"""
:param x: (B,C,H,W) -> (B,256,20,20)
:return: (B,C_N,C_L) -> (100,32*6*6,8) = (100,1152,8)
"""
x = self.conv(x)
x = self.toCapsules(x)
return x
def toCapsules(self, x):
B = x.size(0)
x.size(1)
H = x.size(2)
W = x.size(3)
x = x.reshape(B, self.capsule_length, -1, H, W)
x = x.reshape(B, self.capsule_length, -1)
x = self.squash(x)
x = x.permute(0, 2, 1)
return x
def squash(self, input_tensor):
"""
input_tensor: (B, 1, 10, 16)
return: output_tensor: (B, 1, 10, 16)
"""
squared_norm = (input_tensor ** 2).sum(-1, keepdim=True)
output_tensor = squared_norm * input_tensor / ((1.0 + squared_norm) *
torch.sqrt(squared_norm))
return output_tensor
def get_inputs():
return [torch.rand([4, 256, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.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_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 81
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 + 81 * y3), xmask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 256 * x2 + 20736 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 256 * x2 + 1048576 * y1), tmp0, None)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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
tl.store(in_out_ptr0 + x2, tmp2, None)
@triton.jit
def triton_red_fused_pow_sum_3(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 6272
rnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex % 8
x1 = xindex // 8 % 196
x2 = xindex // 1568
_tmp3 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x4 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r3 = rindex
tmp0 = tl.load(in_ptr0 + (32 * x0 + 256 * ((r3 + 128 * x1) % 784) +
200704 * x2 + (r3 + 128 * x1) // 784), rmask & xmask,
eviction_policy='evict_last', other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = _tmp3 + tmp2
_tmp3 = tl.where(rmask & xmask, tmp4, _tmp3)
tmp3 = tl.sum(_tmp3, 1)[:, None]
tl.store(out_ptr0 + x4, tmp3, xmask)
@triton.jit
def triton_red_fused_pow_sum_4(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK:
tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 32
rnumel = 196
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex % 8
x1 = xindex // 8
_tmp2 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x3 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 8 * r2 + 1568 * x1), rmask & xmask,
eviction_policy='evict_first', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = _tmp2 + tmp1
_tmp2 = tl.where(rmask & xmask, tmp3, _tmp2)
tmp2 = tl.sum(_tmp2, 1)[:, None]
tl.store(out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_sqrt_5(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex // 25088
x0 = xindex % 25088
x1 = xindex // 25088 % 8
x2 = xindex // 200704
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (32 * x1 + 256 * (x0 % 784) + 200704 * x2 + x0 //
784), None, eviction_policy='evict_last')
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp0 + tmp3
tmp5 = libdevice.sqrt(tmp0)
tmp6 = tmp4 * tmp5
tmp7 = tmp2 / tmp6
tl.store(out_ptr0 + x4, tmp7, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (256, 256, 9, 9), (20736, 81, 9, 1))
assert_size_stride(primals_2, (256,), (1,))
assert_size_stride(primals_3, (4, 256, 64, 64), (1048576, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((256, 256, 9, 9), (20736, 1, 2304, 256),
torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(65536, 81)](primals_1, buf0, 65536, 81,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 256, 64, 64), (1048576, 1, 16384, 256
), torch.float32)
triton_poi_fused_1[grid(1024, 4096)](primals_3, buf1, 1024, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(buf1, buf0, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 256, 28, 28), (200704, 1, 7168, 256))
buf3 = buf2
del buf2
triton_poi_fused_convolution_2[grid(802816)](buf3, primals_2,
802816, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf4 = empty_strided_cuda((4, 8, 1, 196), (1568, 1, 6272, 8), torch
.float32)
triton_red_fused_pow_sum_3[grid(6272)](buf3, buf4, 6272, 128,
XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1)
buf5 = empty_strided_cuda((4, 8, 1), (8, 1, 1), torch.float32)
triton_red_fused_pow_sum_4[grid(32)](buf4, buf5, 32, 196, XBLOCK=2,
RBLOCK=256, num_warps=4, num_stages=1)
del buf4
buf6 = empty_strided_cuda((4, 8, 25088), (200704, 25088, 1), torch.
float32)
triton_poi_fused_add_div_mul_sqrt_5[grid(802816)](buf5, buf3, buf6,
802816, XBLOCK=1024, num_warps=4, num_stages=1)
return reinterpret_tensor(buf6, (4, 25088, 8), (200704, 1, 25088), 0
), buf0, buf1, buf3, buf5
class PrimaryCapsNew(nn.Module):
"""
输入:(B,C,H,W)=(B,256,20,20)
输出:(B,C_N,C_L)=(B,32*6*6, 8)=(B,1152,8)
C_N:capsule_num,胶囊的个数
C_L:capsule_length,每个胶囊的长度
"""
def __init__(self, capsule_length=8, in_channels=256, out_channels=32,
capsule_num=32 * 6 * 6, kernel_size=9, stride=2, padding=0):
super(PrimaryCapsNew, self).__init__()
self.capsule_length = capsule_length
self.capsule_num = capsule_num
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels * capsule_length, kernel_size=kernel_size, stride=
stride, padding=padding)
def toCapsules(self, x):
B = x.size(0)
x.size(1)
H = x.size(2)
W = x.size(3)
x = x.reshape(B, self.capsule_length, -1, H, W)
x = x.reshape(B, self.capsule_length, -1)
x = self.squash(x)
x = x.permute(0, 2, 1)
return x
def squash(self, input_tensor):
"""
input_tensor: (B, 1, 10, 16)
return: output_tensor: (B, 1, 10, 16)
"""
squared_norm = (input_tensor ** 2).sum(-1, keepdim=True)
output_tensor = squared_norm * input_tensor / ((1.0 + squared_norm) *
torch.sqrt(squared_norm))
return output_tensor
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]
|
daxiongpro/pytorch-tutorial
|
PrimaryCaps
| false
| 1,839
|
[
"MIT"
] | 0
|
abafc32f7ee1092024085f703e4ced51ce358a1b
|
https://github.com/daxiongpro/pytorch-tutorial/tree/abafc32f7ee1092024085f703e4ced51ce358a1b
|
LearnMaskedDefault
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.nn
class LearnMaskedDefault(nn.Module):
"""
Learns default values to fill invalid entries within input tensors. The
invalid entries are represented by a mask which is passed into forward alongside
the input tensor. Note the default value is only used if all entries in the batch row are
invalid rather than just a portion of invalid entries within each batch row.
"""
def __init__(self, feature_dim: 'int', init_method: 'str'='gaussian',
freeze: 'bool'=False):
"""
Args:
feature_dim (int): the size of the default value parameter, this must match the
input tensor size.
init_method (str): the initial default value parameter. Options:
'guassian'
'zeros'
freeze (bool): If True, the learned default parameter weights are frozen.
"""
super().__init__()
if init_method == 'zeros':
self._learned_defaults = nn.Parameter(torch.zeros(feature_dim),
requires_grad=not freeze)
elif init_method == 'gaussian':
self._learned_defaults = nn.Parameter(torch.Tensor(feature_dim),
requires_grad=not freeze)
nn.init.normal_(self._learned_defaults)
else:
raise NotImplementedError(
f"{init_method} not available. Options are: 'zeros' or 'gaussian'"
)
def forward(self, x: 'torch.Tensor', mask: 'torch.Tensor') ->torch.Tensor:
"""
Args:
x (torch.Tensor): tensor of shape (batch_size, feature_dim).
mask (torch.Tensor): bool tensor of shape (batch_size, seq_len) If all elements
in the batch dimension are False the learned default parameter is used for
that batch element.
Returns:
Tensor with shape (batch_size, feature_dim)
"""
mask = mask.view(mask.shape[0], -1).any(dim=-1)
for i in range(1, x.dim()):
mask = mask.unsqueeze(i)
x = x * mask.float() + self._learned_defaults * (1 - mask.float())
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'feature_dim': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.utils.data
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_per_fused__to_copy_add_any_mul_rsub_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
r2 = rindex % 4
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp6 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp9 = tl.load(in_ptr2 + r2, None, eviction_policy='evict_last')
tmp1 = tmp0 != 0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = triton_helpers.any(tmp4, 1)[:, None]
tmp7 = tmp5.to(tl.float32)
tmp8 = tmp6 * tmp7
tmp10 = 1.0
tmp11 = tmp10 - tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tl.store(out_ptr1 + (r1 + 64 * x0), tmp13, xmask)
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.bool)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__to_copy_add_any_mul_rsub_0[grid(4)](primals_1,
primals_2, primals_3, buf0, buf1, 4, 64, XBLOCK=1, num_warps=2,
num_stages=1)
del primals_1
del primals_2
del primals_3
return buf1, reinterpret_tensor(buf0, (4, 1, 1, 1), (1, 1, 1, 1), 0)
class LearnMaskedDefaultNew(nn.Module):
"""
Learns default values to fill invalid entries within input tensors. The
invalid entries are represented by a mask which is passed into forward alongside
the input tensor. Note the default value is only used if all entries in the batch row are
invalid rather than just a portion of invalid entries within each batch row.
"""
def __init__(self, feature_dim: 'int', init_method: 'str'='gaussian',
freeze: 'bool'=False):
"""
Args:
feature_dim (int): the size of the default value parameter, this must match the
input tensor size.
init_method (str): the initial default value parameter. Options:
'guassian'
'zeros'
freeze (bool): If True, the learned default parameter weights are frozen.
"""
super().__init__()
if init_method == 'zeros':
self._learned_defaults = nn.Parameter(torch.zeros(feature_dim),
requires_grad=not freeze)
elif init_method == 'gaussian':
self._learned_defaults = nn.Parameter(torch.Tensor(feature_dim),
requires_grad=not freeze)
nn.init.normal_(self._learned_defaults)
else:
raise NotImplementedError(
f"{init_method} not available. Options are: 'zeros' or 'gaussian'"
)
def forward(self, input_0, input_1):
primals_3 = self._learned_defaults
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
denred0/pytorchvideo
|
LearnMaskedDefault
| false
| 1,840
|
[
"Apache-2.0"
] | 0
|
d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
https://github.com/denred0/pytorchvideo/tree/d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
SynthWide
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SynthWide(nn.Module):
def __init__(self, num_c=10, f=1):
super(SynthWide, self).__init__()
self.pool = nn.MaxPool2d(2, 2)
self.conv1 = nn.Conv2d(3, 32 * f, 3, padding=1)
self.conv2 = nn.Conv2d(32 * f, 64 * f, 3, padding=1)
self.conv3 = nn.Conv2d(64 * f, 128 * f, 3, padding=1)
self.conv4 = nn.Conv2d(128 * f, 256, 3, padding=1)
self.fc1 = nn.Linear(256 * 4 * 4, num_c)
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 * 4 * 4)
x = self.fc1(x)
return x
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 96
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_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 12
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 12288 * y1), tmp0, ymask)
@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 32
y1 = yindex // 32
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 32 * x2 + 288 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_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_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 32
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_6(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32 % 32
x2 = xindex // 1024
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1 + 4096 * x2), None)
tmp1 = tl.load(in_ptr0 + (32 + x0 + 64 * x1 + 4096 * x2), None)
tmp3 = tl.load(in_ptr0 + (2048 + x0 + 64 * x1 + 4096 * x2), None)
tmp5 = tl.load(in_ptr0 + (2080 + x0 + 64 * x1 + 4096 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_7(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_8(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 64
x1 = xindex // 64 % 16
x2 = xindex // 1024
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x1 + 4096 * x2), None)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 128 * x1 + 4096 * x2), None)
tmp3 = tl.load(in_ptr0 + (2048 + x0 + 128 * x1 + 4096 * x2), None)
tmp5 = tl.load(in_ptr0 + (2112 + x0 + 128 * x1 + 4096 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_9(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 128
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_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 % 128
x1 = xindex // 128 % 8
x2 = xindex // 1024
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * x1 + 4096 * x2), None)
tmp1 = tl.load(in_ptr0 + (128 + x0 + 256 * x1 + 4096 * x2), None)
tmp3 = tl.load(in_ptr0 + (2048 + x0 + 256 * x1 + 4096 * x2), None)
tmp5 = tl.load(in_ptr0 + (2176 + x0 + 256 * x1 + 4096 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_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 = 64
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 % 4
y1 = yindex // 4
y5 = yindex
y4 = yindex // 16
y6 = yindex % 16
tmp0 = tl.load(in_ptr0 + (x2 + 512 * y0 + 4096 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (256 + x2 + 512 * y0 + 4096 * y1), xmask &
ymask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2048 + x2 + 512 * y0 + 4096 * y1), xmask &
ymask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2304 + x2 + 512 * y0 + 4096 * 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 + 16 * x2 + 4096 * y4), tmp16, xmask & ymask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (32, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (64, 32, 3, 3), (288, 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, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_9, (256,), (1,))
assert_size_stride(primals_10, (10, 4096), (4096, 1))
assert_size_stride(primals_11, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((32, 3, 3, 3), (27, 1, 9, 3), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(96, 9)](primals_1, buf0, 96, 9, XBLOCK=16,
YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 3, 64, 64), (12288, 1, 192, 3), torch
.float32)
triton_poi_fused_1[grid(12, 4096)](primals_3, buf1, 12, 4096,
XBLOCK=64, YBLOCK=16, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((64, 32, 3, 3), (288, 1, 96, 32), torch.
float32)
triton_poi_fused_2[grid(2048, 9)](primals_4, buf2, 2048, 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((256, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_4[grid(32768, 9)](primals_8, buf4, 32768, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf5 = extern_kernels.convolution(buf1, buf0, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 32, 64, 64), (131072, 1, 2048, 32))
buf6 = buf5
del buf5
triton_poi_fused_convolution_relu_5[grid(524288)](buf6, primals_2,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf7 = empty_strided_cuda((4, 32, 32, 32), (32768, 1, 1024, 32),
torch.float32)
buf8 = empty_strided_cuda((4, 32, 32, 32), (32768, 1, 1024, 32),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_6[grid(131072)](buf6, buf7,
buf8, 131072, XBLOCK=1024, num_warps=4, num_stages=1)
buf9 = extern_kernels.convolution(buf7, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 64, 32, 32), (65536, 1, 2048, 64))
buf10 = buf9
del buf9
triton_poi_fused_convolution_relu_7[grid(262144)](buf10, primals_5,
262144, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf11 = empty_strided_cuda((4, 64, 16, 16), (16384, 1, 1024, 64),
torch.float32)
buf12 = empty_strided_cuda((4, 64, 16, 16), (16384, 1, 1024, 64),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_8[grid(65536)](buf10,
buf11, buf12, 65536, XBLOCK=256, num_warps=4, num_stages=1)
buf13 = extern_kernels.convolution(buf11, buf3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (4, 128, 16, 16), (32768, 1, 2048, 128))
buf14 = buf13
del buf13
triton_poi_fused_convolution_relu_9[grid(131072)](buf14, primals_7,
131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf15 = empty_strided_cuda((4, 128, 8, 8), (8192, 1, 1024, 128),
torch.float32)
buf16 = empty_strided_cuda((4, 128, 8, 8), (8192, 1, 1024, 128),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_10[grid(32768)](buf14,
buf15, buf16, 32768, XBLOCK=128, num_warps=4, num_stages=1)
buf17 = extern_kernels.convolution(buf15, buf4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 256, 8, 8), (16384, 1, 2048, 256))
buf18 = buf17
del buf17
triton_poi_fused_convolution_relu_11[grid(65536)](buf18, primals_9,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_9
buf19 = empty_strided_cuda((4, 256, 4, 4), (4096, 1, 1024, 256),
torch.int8)
buf20 = empty_strided_cuda((4, 256, 4, 4), (4096, 16, 4, 1), torch.
float32)
triton_poi_fused_max_pool2d_with_indices_12[grid(64, 256)](buf18,
buf19, buf20, 64, 256, XBLOCK=256, YBLOCK=1, num_warps=4,
num_stages=1)
buf21 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf20, (4, 4096
), (4096, 1), 0), reinterpret_tensor(primals_10, (4096, 10), (1,
4096), 0), alpha=1, beta=1, out=buf21)
del primals_11
return (buf21, buf0, buf1, buf2, buf3, buf4, buf6, buf7, buf8, buf10,
buf11, buf12, buf14, buf15, buf16, buf18, buf19, reinterpret_tensor
(buf20, (4, 4096), (4096, 1), 0), primals_10)
class SynthWideNew(nn.Module):
def __init__(self, num_c=10, f=1):
super(SynthWideNew, self).__init__()
self.pool = nn.MaxPool2d(2, 2)
self.conv1 = nn.Conv2d(3, 32 * f, 3, padding=1)
self.conv2 = nn.Conv2d(32 * f, 64 * f, 3, padding=1)
self.conv3 = nn.Conv2d(64 * f, 128 * f, 3, padding=1)
self.conv4 = nn.Conv2d(128 * f, 256, 3, padding=1)
self.fc1 = nn.Linear(256 * 4 * 4, num_c)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.fc1.weight
primals_11 = self.fc1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
dengliming/iotnets
|
SynthWide
| false
| 1,842
|
[
"MIT"
] | 0
|
db744e56769c799dbf765a27fc5aa91e3edeaaa3
|
https://github.com/dengliming/iotnets/tree/db744e56769c799dbf765a27fc5aa91e3edeaaa3
|
TCN_SLID
|
import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x, pad_right=True):
return x[:, :, :-self.chomp_size].contiguous() if pad_right else x[
:, :, self.chomp_size:]
class TemporalBlock(nn.Module):
def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation,
padding, dropout):
super(TemporalBlock, self).__init__()
self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size,
stride=stride, padding=padding, dilation=dilation))
self.chomp1 = Chomp1d(padding)
self.relu1 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout1 = nn.Dropout(dropout)
self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs,
kernel_size, stride=stride, padding=padding, dilation=dilation))
self.chomp2 = Chomp1d(padding)
self.relu2 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout2 = nn.Dropout(dropout)
self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.
dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2)
self.downsample = nn.Conv1d(n_inputs, n_outputs, 1
) if n_inputs != n_outputs else None
self.relu = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.init_weights()
def init_weights(self):
self.conv1.weight.data.normal_(0, 0.01)
self.conv2.weight.data.normal_(0, 0.01)
if self.downsample is not None:
self.downsample.weight.data.normal_(0, 0.01)
def forward(self, x):
out = self.net(x)
res = x if self.downsample is None else self.downsample(x)
return self.relu(out + res)
class TemporalConvNet(nn.Module):
def __init__(self, num_inputs, num_channels, kernel_size, stride, dropout):
super(TemporalConvNet, self).__init__()
self.network = nn.Sequential()
for i, nch in enumerate(num_channels):
dilation = 2 ** i
in_channels = num_inputs if i == 0 else num_channels[i - 1]
out_channels = num_channels[i]
padding = (kernel_size - 1) * dilation
self.network.add_module('tblock' + str(i), TemporalBlock(
n_inputs=in_channels, n_outputs=out_channels, kernel_size=
kernel_size, stride=stride, dilation=dilation, padding=
padding, dropout=dropout))
def forward(self, x):
return self.network(x)
class TCN_SLID(nn.Module):
def __init__(self, size_in, size_out, list_conv_depths, size_kernel,
stride, dropout):
super(TCN_SLID, self).__init__()
self.tcn = TemporalConvNet(num_inputs=size_in, num_channels=
list_conv_depths, kernel_size=size_kernel, stride=stride,
dropout=dropout)
self.linear1 = nn.Linear(list_conv_depths[-1], list_conv_depths[-1] //
2)
self.linear2 = nn.Linear(list_conv_depths[-1] // 2,
list_conv_depths[-1] // 4)
self.linear3 = nn.Linear(list_conv_depths[-1] // 4, size_out)
self.softmax = nn.Softmax(dim=2)
def forward(self, x):
output = self.tcn(x.transpose(1, 2))
output = self.linear1(output.transpose(1, 2))
output = self.linear2(output)
output = self.linear3(output)
output = self.softmax(output)
return output.transpose(1, 2)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'size_in': 4, 'size_out': 4, 'list_conv_depths': [4, 4],
'size_kernel': 4, 'stride': 1, 'dropout': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
from torch.nn.utils import weight_norm
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__weight_norm_interface_0(in_out_ptr0, in_ptr0, in_ptr1,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp7 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(xmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp6 = libdevice.sqrt(tmp5)
tmp8 = tmp7 / tmp6
tmp9 = tmp0 * tmp8
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr0 + (r1 + 16 * x0), tmp9, xmask)
@triton.jit
def triton_poi_fused_convolution_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_clone_leaky_relu_2(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 % 4
x3 = xindex // 4
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 7 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_add_clone_leaky_relu_3(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, out_ptr2, ynumel, xnumel, YBLOCK: tl.constexpr,
XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 7 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
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)
tmp9 = tmp7 + tmp8
tmp10 = tmp9 > tmp3
tmp11 = tmp9 * tmp5
tmp12 = tl.where(tmp10, tmp9, tmp11)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
tl.store(out_ptr1 + (x2 + 4 * y3), tmp10, xmask & ymask)
tl.store(out_ptr2 + (x2 + 4 * y3), tmp12, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_leaky_relu_4(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 % 4
x3 = xindex // 4
x1 = xindex // 4 % 4
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 10 * x3), xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.01
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x4, tmp4, xmask)
tl.store(out_ptr1 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_add_clone_leaky_relu_5(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, out_ptr1, out_ptr2, ynumel, xnumel, YBLOCK: tl.constexpr,
XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 10 * y3), xmask & ymask, eviction_policy
='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + (x2 + 4 * y3), xmask & ymask, 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)
tmp9 = tmp7 + tmp8
tmp10 = tmp9 > tmp3
tmp11 = tmp9 * tmp5
tmp12 = tl.where(tmp10, tmp9, tmp11)
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
tl.store(out_ptr1 + (x2 + 4 * y3), tmp10, xmask & ymask)
tl.store(out_ptr2 + (y0 + 4 * x2 + 16 * y1), tmp12, xmask & ymask)
@triton.jit
def triton_poi_fused_add_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
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__softmax_7(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_8(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
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) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 1, 1), (1, 1, 1))
assert_size_stride(primals_12, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_13, (4,), (1,))
assert_size_stride(primals_14, (2, 4), (4, 1))
assert_size_stride(primals_15, (2,), (1,))
assert_size_stride(primals_16, (1, 2), (2, 1))
assert_size_stride(primals_17, (1,), (1,))
assert_size_stride(primals_18, (4, 1), (1, 1))
assert_size_stride(primals_19, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 1, 1), (1, 1, 1), 0)
del buf0
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused__weight_norm_interface_0[grid(4)](buf1, primals_3,
primals_2, buf2, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_convolution_1[grid(16, 4)](primals_1, buf3, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf4 = extern_kernels.convolution(buf3, buf2, stride=(1,), padding=
(3,), dilation=(1,), transposed=False, output_padding=(0,),
groups=1, bias=None)
assert_size_stride(buf4, (4, 4, 7), (28, 7, 1))
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf6 = buf3
del buf3
triton_poi_fused_clone_leaky_relu_2[grid(64)](buf4, primals_4, buf5,
buf6, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf4
del primals_4
buf7 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf8 = reinterpret_tensor(buf7, (4, 1, 1), (1, 1, 1), 0)
del buf7
buf9 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused__weight_norm_interface_0[grid(4)](buf8, primals_6,
primals_5, buf9, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf10 = extern_kernels.convolution(buf6, buf9, stride=(1,), padding
=(3,), dilation=(1,), transposed=False, output_padding=(0,),
groups=1, bias=None)
assert_size_stride(buf10, (4, 4, 7), (28, 7, 1))
buf11 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf13 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_clone_leaky_relu_3[grid(16, 4)](buf10,
primals_7, primals_1, buf11, buf12, buf13, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf10
del primals_7
buf14 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf15 = reinterpret_tensor(buf14, (4, 1, 1), (1, 1, 1), 0)
del buf14
buf16 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused__weight_norm_interface_0[grid(4)](buf15, primals_9,
primals_8, buf16, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
buf17 = extern_kernels.convolution(buf13, buf16, stride=(1,),
padding=(6,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf17, (4, 4, 10), (40, 10, 1))
buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf19 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_leaky_relu_4[grid(64)](buf17, primals_10,
buf18, buf19, 64, XBLOCK=64, num_warps=1, num_stages=1)
del buf17
del primals_10
buf20 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf21 = reinterpret_tensor(buf20, (4, 1, 1), (1, 1, 1), 0)
del buf20
buf22 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_per_fused__weight_norm_interface_0[grid(4)](buf21,
primals_12, primals_11, buf22, 4, 16, XBLOCK=1, num_warps=2,
num_stages=1)
buf23 = extern_kernels.convolution(buf19, buf22, stride=(1,),
padding=(6,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf23, (4, 4, 10), (40, 10, 1))
buf24 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf25 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
buf26 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_clone_leaky_relu_5[grid(16, 4)](buf23,
primals_13, buf13, buf24, buf25, buf26, 16, 4, XBLOCK=4, YBLOCK
=16, num_warps=1, num_stages=1)
del buf23
del primals_13
buf27 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf26, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_14, (4, 2), (1, 4), 0), out=buf27)
buf28 = reinterpret_tensor(buf27, (4, 4, 2), (8, 2, 1), 0)
del buf27
triton_poi_fused_add_6[grid(32)](buf28, primals_15, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del primals_15
buf30 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_17, reinterpret_tensor(buf28, (16, 2),
(2, 1), 0), reinterpret_tensor(primals_16, (2, 1), (1, 2), 0),
alpha=1, beta=1, out=buf30)
del primals_17
buf31 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_19, buf30, reinterpret_tensor(
primals_18, (1, 4), (1, 1), 0), alpha=1, beta=1, out=buf31)
del primals_19
buf32 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_7[grid(64)](buf31, buf32, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf33 = reinterpret_tensor(buf31, (4, 4, 4), (16, 4, 1), 0)
del buf31
triton_poi_fused__softmax_8[grid(64)](buf32, buf33, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf32
return (reinterpret_tensor(buf33, (4, 4, 4), (16, 1, 4), 0), buf2, buf9,
buf16, buf22, primals_2, primals_3, primals_5, primals_6, primals_8,
primals_9, primals_11, primals_12, reinterpret_tensor(primals_1, (4,
4, 4), (16, 1, 4), 0), buf1, buf2, buf5, buf6, buf8, buf9, buf11,
buf12, buf13, buf15, buf16, buf18, buf19, buf21, buf22, buf24,
buf25, reinterpret_tensor(buf26, (16, 4), (4, 1), 0),
reinterpret_tensor(buf28, (16, 2), (2, 1), 0), buf30, buf33,
primals_18, primals_16, primals_14)
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x, pad_right=True):
return x[:, :, :-self.chomp_size].contiguous() if pad_right else x[
:, :, self.chomp_size:]
class TemporalBlock(nn.Module):
def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation,
padding, dropout):
super(TemporalBlock, self).__init__()
self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size,
stride=stride, padding=padding, dilation=dilation))
self.chomp1 = Chomp1d(padding)
self.relu1 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout1 = nn.Dropout(dropout)
self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs,
kernel_size, stride=stride, padding=padding, dilation=dilation))
self.chomp2 = Chomp1d(padding)
self.relu2 = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.dropout2 = nn.Dropout(dropout)
self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.
dropout1, self.conv2, self.chomp2, self.relu2, self.dropout2)
self.downsample = nn.Conv1d(n_inputs, n_outputs, 1
) if n_inputs != n_outputs else None
self.relu = nn.LeakyReLU(negative_slope=0.01, inplace=False)
self.init_weights()
def init_weights(self):
self.conv1.weight.data.normal_(0, 0.01)
self.conv2.weight.data.normal_(0, 0.01)
if self.downsample is not None:
self.downsample.weight.data.normal_(0, 0.01)
def forward(self, x):
out = self.net(x)
res = x if self.downsample is None else self.downsample(x)
return self.relu(out + res)
class TemporalConvNet(nn.Module):
def __init__(self, num_inputs, num_channels, kernel_size, stride, dropout):
super(TemporalConvNet, self).__init__()
self.network = nn.Sequential()
for i, nch in enumerate(num_channels):
dilation = 2 ** i
in_channels = num_inputs if i == 0 else num_channels[i - 1]
out_channels = num_channels[i]
padding = (kernel_size - 1) * dilation
self.network.add_module('tblock' + str(i), TemporalBlock(
n_inputs=in_channels, n_outputs=out_channels, kernel_size=
kernel_size, stride=stride, dilation=dilation, padding=
padding, dropout=dropout))
def forward(self, x):
return self.network(x)
class TCN_SLIDNew(nn.Module):
def __init__(self, size_in, size_out, list_conv_depths, size_kernel,
stride, dropout):
super(TCN_SLIDNew, self).__init__()
self.tcn = TemporalConvNet(num_inputs=size_in, num_channels=
list_conv_depths, kernel_size=size_kernel, stride=stride,
dropout=dropout)
self.linear1 = nn.Linear(list_conv_depths[-1], list_conv_depths[-1] //
2)
self.linear2 = nn.Linear(list_conv_depths[-1] // 2,
list_conv_depths[-1] // 4)
self.linear3 = nn.Linear(list_conv_depths[-1] // 4, size_out)
self.softmax = nn.Softmax(dim=2)
def forward(self, input_0):
primals_4 = self.tcn.network.tblock0.conv1.bias
primals_2 = self.tcn.network.tblock0.conv1.weight_g
primals_1 = self.tcn.network.tblock0.conv1.weight_v
primals_7 = self.tcn.network.tblock0.conv2.bias
primals_5 = self.tcn.network.tblock0.conv2.weight_g
primals_3 = self.tcn.network.tblock0.conv2.weight_v
primals_10 = self.tcn.network.tblock1.conv1.bias
primals_8 = self.tcn.network.tblock1.conv1.weight_g
primals_6 = self.tcn.network.tblock1.conv1.weight_v
primals_13 = self.tcn.network.tblock1.conv2.bias
primals_11 = self.tcn.network.tblock1.conv2.weight_g
primals_9 = self.tcn.network.tblock1.conv2.weight_v
primals_14 = self.linear1.weight
primals_15 = self.linear1.bias
primals_16 = self.linear2.weight
primals_17 = self.linear2.bias
primals_18 = self.linear3.weight
primals_19 = self.linear3.bias
primals_12 = 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])
return output[0]
|
ddcas/singing-language-identification
|
TCN_SLID
| false
| 1,843
|
[
"MIT"
] | 0
|
d104419b196d56d4de37cff47c32e88e28c58690
|
https://github.com/ddcas/singing-language-identification/tree/d104419b196d56d4de37cff47c32e88e28c58690
|
HearthstoneNet
|
import torch
from torch import nn
import torch.nn.functional as F
class HearthstoneNet(nn.Module):
def __init__(self):
super(HearthstoneNet, self).__init__()
self.conv1 = nn.Conv2d(1, 64, kernel_size=(3, 3), padding=1)
self.conv2 = nn.Conv2d(64, 64, kernel_size=(3, 3), padding=1)
self.max_pool = nn.MaxPool2d(2, 2)
self.global_pool = nn.AvgPool2d(7)
self.fc1 = nn.Linear(64, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = self.max_pool(x)
x = F.relu(self.conv2(x))
x = F.relu(self.conv2(x))
x = self.max_pool(x)
x = F.relu(self.conv2(x))
x = F.relu(self.conv2(x))
x = self.global_pool(x)
x = x.view(-1, 64)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = F.log_softmax(x)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 32
x1 = xindex // 32
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1), None, eviction_policy
='evict_last')
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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_relu_5(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
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_per_fused__log_softmax_6(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 16
rnumel = 10
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 10 * x0), rmask & xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(rmask & xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(rmask & xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tl_math.log(tmp10)
tmp12 = tmp5 - tmp11
tl.store(out_ptr2 + (r1 + 10 * x0), tmp12, rmask & xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (64, 1, 3, 3), (9, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (64, 64), (64, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (10, 64), (64, 1))
assert_size_stride(primals_9, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(1048576)](buf1, primals_2,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(1048576)](buf3, primals_5,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
buf4 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.float32)
buf5 = empty_strided_cuda((4, 64, 32, 32), (65536, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(262144)](buf3, buf4,
buf5, 262144, XBLOCK=512, num_warps=8, num_stages=1)
buf6 = extern_kernels.convolution(buf4, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_2[grid(262144)](buf7, primals_5,
262144, XBLOCK=512, num_warps=8, num_stages=1)
buf8 = extern_kernels.convolution(buf7, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 64, 32, 32), (65536, 1024, 32, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_2[grid(262144)](buf9, primals_5,
262144, XBLOCK=512, num_warps=8, num_stages=1)
buf10 = empty_strided_cuda((4, 64, 16, 16), (16384, 256, 16, 1),
torch.float32)
buf11 = empty_strided_cuda((4, 64, 16, 16), (16384, 256, 16, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(65536)](buf9, buf10,
buf11, 65536, XBLOCK=256, num_warps=4, num_stages=1)
buf12 = extern_kernels.convolution(buf10, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 64, 16, 16), (16384, 256, 16, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_4[grid(65536)](buf13, primals_5,
65536, XBLOCK=512, num_warps=4, num_stages=1)
buf14 = extern_kernels.convolution(buf13, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 64, 16, 16), (16384, 256, 16, 1))
buf15 = buf14
del buf14
triton_poi_fused_convolution_relu_4[grid(65536)](buf15, primals_5,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_5
buf16 = torch.ops.aten.avg_pool2d.default(buf15, [7, 7], [7, 7], [0,
0], False, True, None)
buf17 = buf16
del buf16
buf18 = empty_strided_cuda((16, 64), (64, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf17, (16, 64), (64, 1), 0),
reinterpret_tensor(primals_6, (64, 64), (1, 64), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_relu_5[grid(1024)](buf19, primals_7, 1024, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_7
buf20 = empty_strided_cuda((16, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_9, buf19, reinterpret_tensor(primals_8,
(64, 10), (1, 64), 0), alpha=1, beta=1, out=buf20)
del primals_9
buf23 = empty_strided_cuda((16, 10), (10, 1), torch.float32)
triton_per_fused__log_softmax_6[grid(16)](buf20, buf23, 16, 10,
XBLOCK=1, num_warps=2, num_stages=1)
del buf20
return (buf23, primals_1, primals_3, primals_4, buf1, buf3, buf4, buf5,
buf7, buf9, buf10, buf11, buf13, buf15, reinterpret_tensor(buf17, (
16, 64), (64, 1), 0), buf19, buf23, primals_8, primals_6)
class HearthstoneNetNew(nn.Module):
def __init__(self):
super(HearthstoneNetNew, self).__init__()
self.conv1 = nn.Conv2d(1, 64, kernel_size=(3, 3), padding=1)
self.conv2 = nn.Conv2d(64, 64, kernel_size=(3, 3), padding=1)
self.max_pool = nn.MaxPool2d(2, 2)
self.global_pool = nn.AvgPool2d(7)
self.fc1 = nn.Linear(64, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
dianarvp/stone_ground_hearth_battles
|
HearthstoneNet
| false
| 1,844
|
[
"Apache-2.0"
] | 0
|
450e70eaef21b543be579a6d696676fb148a99b0
|
https://github.com/dianarvp/stone_ground_hearth_battles/tree/450e70eaef21b543be579a6d696676fb148a99b0
|
AttnBertPooler
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch import nn
class AttnBertPooler(nn.Module):
def __init__(self, config):
super(AttnBertPooler, self).__init__()
self.dense = nn.Linear(config.hidden_size * 2, config.hidden_size * 2)
self.activation = nn.Tanh()
self.hidden_size = config.hidden_size
def forward(self, hidden_states):
first_token_tensor = hidden_states[:, 0].view(len(hidden_states), -1, 1
)
scores = torch.matmul(hidden_states[:, 1:], first_token_tensor
) / math.sqrt(self.hidden_size)
attn_token_tensor = torch.matmul(hidden_states[:, 1:].view(
hidden_states.size(0), self.hidden_size, -1), scores)
attn_token_tensor = attn_token_tensor.view(attn_token_tensor.size(0
), self.hidden_size)
first_token_tensor = first_token_tensor.squeeze(2)
pooled_token_tensor = torch.cat((attn_token_tensor,
first_token_tensor), dim=-1)
pooled_output = self.dense(pooled_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_bmm_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_div_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 12
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (16 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_tanh_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 8
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (8, 8), (8, 1))
assert_size_stride(primals_3, (8,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 3, 1), (3, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (4, 3, 4), (16, 4,
1), 4), reinterpret_tensor(primals_1, (4, 4, 1), (16, 1, 0), 0),
out=buf0)
buf1 = empty_strided_cuda((4, 4, 3), (12, 3, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_bmm_div_0[grid(48)](primals_1, buf1, 48, XBLOCK=64,
num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 3, 1), (3, 1, 12), 0)
del buf0
triton_poi_fused_div_1[grid(12)](buf2, 12, XBLOCK=16, num_warps=1,
num_stages=1)
buf3 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf1, buf2, out=buf3)
del buf1
del buf2
buf4 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
triton_poi_fused_cat_2[grid(32)](buf3, primals_1, buf4, 32, XBLOCK=
32, num_warps=1, num_stages=1)
del buf3
del primals_1
buf5 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_2, (8, 8), (1, 8
), 0), out=buf5)
del primals_2
buf6 = buf5
del buf5
triton_poi_fused_tanh_3[grid(32)](buf6, primals_3, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del primals_3
return buf6, buf4, buf6
class AttnBertPoolerNew(nn.Module):
def __init__(self, config):
super(AttnBertPoolerNew, self).__init__()
self.dense = nn.Linear(config.hidden_size * 2, config.hidden_size * 2)
self.activation = nn.Tanh()
self.hidden_size = config.hidden_size
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
AnonymousAuthor2013/PostRec
|
AttnBertPooler
| false
| 1,845
|
[
"MIT"
] | 0
|
a1461f716d177e28b96ca29d1398f96b5717c1e1
|
https://github.com/AnonymousAuthor2013/PostRec/tree/a1461f716d177e28b96ca29d1398f96b5717c1e1
|
TestNet
|
import torch
import torch.nn as nn
class ScaleLayer(nn.Module):
def __init__(self, init_value=0.001):
super().__init__()
self.scale = nn.Parameter(torch.FloatTensor([init_value]))
def forward(self, input):
return input * self.scale
class TestNet(nn.Module):
def __init__(self):
super(TestNet, self).__init__()
self.scaler1 = ScaleLayer(init_value=torch.tensor(2.0))
self.scaler2 = ScaleLayer(init_value=torch.tensor(2.0))
self.scaler3 = ScaleLayer(init_value=torch.tensor(2.0))
def forward(self, x):
x = self.scaler1(x)
x = self.scaler2(x)
x = self.scaler3(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + 0)
tmp5 = tl.broadcast_to(tmp4, [XBLOCK])
tmp7 = tl.load(in_ptr3 + 0)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp3 = tmp0 * tmp2
tmp6 = tmp3 * tmp5
tmp9 = tmp6 * tmp8
tl.store(out_ptr0 + x0, tmp9, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (1,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (1,), (1,))
assert_size_stride(primals_4, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_2, primals_1, primals_3,
primals_4, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
return buf0, primals_1, primals_2, primals_3, primals_4
class ScaleLayer(nn.Module):
def __init__(self, init_value=0.001):
super().__init__()
self.scale = nn.Parameter(torch.FloatTensor([init_value]))
def forward(self, input):
return input * self.scale
class TestNetNew(nn.Module):
def __init__(self):
super(TestNetNew, self).__init__()
self.scaler1 = ScaleLayer(init_value=torch.tensor(2.0))
self.scaler2 = ScaleLayer(init_value=torch.tensor(2.0))
self.scaler3 = ScaleLayer(init_value=torch.tensor(2.0))
def forward(self, input_0):
primals_1 = self.scaler1.scale
primals_3 = self.scaler2.scale
primals_4 = self.scaler3.scale
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
dizzyvn/torch-tcav
|
TestNet
| false
| 1,846
|
[
"Apache-2.0"
] | 0
|
c9795e817d1104923ef7422f5575607e6b835abc
|
https://github.com/dizzyvn/torch-tcav/tree/c9795e817d1104923ef7422f5575607e6b835abc
|
BertPooler
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class BertPooler(nn.Module):
def __init__(self, config):
super(BertPooler, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states):
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused_add_tanh_1[grid(64)](buf2, primals_3, 64, XBLOCK=
64, num_warps=1, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf2
class BertPoolerNew(nn.Module):
def __init__(self, config):
super(BertPoolerNew, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
Andr3wis2Cool4School/AI-pro
|
BertPooler
| false
| 1,847
|
[
"MIT"
] | 0
|
dfe5f5959bc187d899a86f13b84158c66f64d1cc
|
https://github.com/Andr3wis2Cool4School/AI-pro/tree/dfe5f5959bc187d899a86f13b84158c66f64d1cc
|
BatchNorm
|
import torch
import numpy as np
from torch import tensor
import torch.nn as nn
import numpy.random as rng
class BaseFlow(nn.Module):
""" """
def __init__(self, n_inputs, **kwargs):
super(BaseFlow, self).__init__()
self.n_inputs = n_inputs
def forward(self, x, **kwargs):
raise NotImplementedError
def generate_samples(self, n_samples=1, u=None, **kwargs):
raise NotImplementedError
def log_likelihood(self, x, **kwargs):
""" Calculates log p(x) with a Gaussian base density """
u, logdet_dudx = self.forward(x, **kwargs)
constant = float(-0.5 * self.n_inputs * np.log(2.0 * np.pi))
log_likelihood = constant - 0.5 * torch.sum(u ** 2, dim=1
) + logdet_dudx
return u, log_likelihood
def log_likelihood_and_score(self, x, **kwargs):
""" Calculates log p(x) and t(x) with a Gaussian base density """
u, log_likelihood = self.log_likelihood(x, **kwargs)
return u, log_likelihood, None
class BatchNorm(BaseFlow):
"""BatchNorm implementation"""
def __init__(self, n_inputs, alpha=0.1, eps=1e-05):
super(BatchNorm, self).__init__(n_inputs)
self.n_inputs = n_inputs
self.alpha = alpha
self.eps = eps
self.calculated_running_mean = False
self.running_mean = torch.zeros(self.n_inputs)
self.running_var = torch.zeros(self.n_inputs)
def forward(self, x, fixed_params=False):
"""Calculates x -> u(x) (batch norming)"""
if fixed_params:
mean = self.running_mean
var = self.running_var
else:
mean = torch.mean(x, dim=0)
var = torch.mean((x - mean) ** 2, dim=0) + self.eps
if not self.calculated_running_mean:
self.running_mean = mean
self.running_var = var
else:
self.running_mean = (1.0 - self.alpha
) * self.running_mean + self.alpha * mean
self.running_var = (1.0 - self.alpha
) * self.running_var + self.alpha * var
self.calculated_running_mean = True
u = (x - mean) / torch.sqrt(var)
logdet = -0.5 * torch.sum(torch.log(var))
return u, logdet
def inverse(self, u):
"""Calculates u -> x(u) (the approximate inverse transformation based on running mean and variance)"""
x = torch.sqrt(self.running_var) * u + self.running_mean
return x
def generate_samples(self, n_samples=1, u=None, **kwargs):
if u is None:
u = tensor(rng.randn(n_samples, self.n_inputs))
x = torch.sqrt(self.running_var) * u + self.running_mean
return x
def to(self, *args, **kwargs):
logger.debug('Transforming BatchNorm to %s', args)
self = super()
self.running_mean = self.running_mean
self.running_var = self.running_var
return self
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_inputs': 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
import numpy as np
from torch import tensor
import torch.nn as nn
import numpy.random as rng
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_log_mean_mul_pow_sub_sum_0(in_out_ptr0, in_ptr0,
out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr0 + (64 + r0), None)
tmp3 = tl.load(in_ptr0 + (128 + r0), None)
tmp5 = tl.load(in_ptr0 + (192 + r0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-05
tmp22 = tmp20 + tmp21
tmp23 = tl_math.log(tmp22)
tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
tmp26 = tl.sum(tmp24, 1)[:, None]
tmp27 = -0.5
tmp28 = tmp26 * tmp27
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp8, None)
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp22, None)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp28, None)
@triton.jit
def triton_poi_fused_div_sqrt_sub_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = libdevice.sqrt(tmp3)
tmp5 = tmp2 / tmp4
tl.store(out_ptr0 + x2, tmp5, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = buf3
del buf3
get_raw_stream(0)
triton_per_fused_add_log_mean_mul_pow_sub_sum_0[grid(1)](buf4,
arg0_1, buf0, buf1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_div_sqrt_sub_1[grid(256)](arg0_1, buf0, buf1, buf2,
256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf2, buf4, buf1, buf0
class BaseFlow(nn.Module):
""" """
def __init__(self, n_inputs, **kwargs):
super(BaseFlow, self).__init__()
self.n_inputs = n_inputs
def forward(self, x, **kwargs):
raise NotImplementedError
def generate_samples(self, n_samples=1, u=None, **kwargs):
raise NotImplementedError
def log_likelihood(self, x, **kwargs):
""" Calculates log p(x) with a Gaussian base density """
u, logdet_dudx = self.forward(x, **kwargs)
constant = float(-0.5 * self.n_inputs * np.log(2.0 * np.pi))
log_likelihood = constant - 0.5 * torch.sum(u ** 2, dim=1
) + logdet_dudx
return u, log_likelihood
def log_likelihood_and_score(self, x, **kwargs):
""" Calculates log p(x) and t(x) with a Gaussian base density """
u, log_likelihood = self.log_likelihood(x, **kwargs)
return u, log_likelihood, None
class BatchNormNew(BaseFlow):
"""BatchNorm implementation"""
def __init__(self, n_inputs, alpha=0.1, eps=1e-05):
super(BatchNormNew, self).__init__(n_inputs)
self.n_inputs = n_inputs
self.alpha = alpha
self.eps = eps
self.calculated_running_mean = False
self.running_mean = torch.zeros(self.n_inputs)
self.running_var = torch.zeros(self.n_inputs)
def inverse(self, u):
"""Calculates u -> x(u) (the approximate inverse transformation based on running mean and variance)"""
x = torch.sqrt(self.running_var) * u + self.running_mean
return x
def generate_samples(self, n_samples=1, u=None, **kwargs):
if u is None:
u = tensor(rng.randn(n_samples, self.n_inputs))
x = torch.sqrt(self.running_var) * u + self.running_mean
return x
def to(self, *args, **kwargs):
logger.debug('Transforming BatchNorm to %s', args)
self = super()
self.running_mean = self.running_mean
self.running_var = self.running_var
return self
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1]
|
dlvp/madminer
|
BatchNorm
| false
| 1,848
|
[
"MIT"
] | 0
|
4ae7d9b73452848a6c9d1b81b50ef316ff7a054f
|
https://github.com/dlvp/madminer/tree/4ae7d9b73452848a6c9d1b81b50ef316ff7a054f
|
Critic
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, num_inputs, args):
super(Critic, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)
self.fc3 = nn.Linear(args.hidden_size, 1)
self.fc3.weight.data.mul_(0.1)
self.fc3.bias.data.mul_(0.0)
def forward(self, x):
x = F.tanh(self.fc1(x))
x = F.tanh(self.fc2(x))
v = self.fc3(x)
return v
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_inputs': 4, 'args': _mock_config(hidden_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (1, 4), (4, 1))
assert_size_stride(primals_7, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_tanh_0[grid(256)](buf1, primals_2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_tanh_0[grid(256)](buf3, primals_5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf5)
del primals_7
return reinterpret_tensor(buf5, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1, buf3, primals_6, primals_4
class CriticNew(nn.Module):
def __init__(self, num_inputs, args):
super(CriticNew, self).__init__()
self.fc1 = nn.Linear(num_inputs, args.hidden_size)
self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)
self.fc3 = nn.Linear(args.hidden_size, 1)
self.fc3.weight.data.mul_(0.1)
self.fc3.bias.data.mul_(0.0)
def forward(self, input_0):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_6 = self.fc3.weight
primals_7 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
dlrudco/pg_travel
|
Critic
| false
| 1,849
|
[
"MIT"
] | 0
|
33733b624894095096af8201f7597c3244d3480d
|
https://github.com/dlrudco/pg_travel/tree/33733b624894095096af8201f7597c3244d3480d
|
MetapathAggrLayer
|
import torch
from torch.nn import functional as F
from torch import nn
class MetapathAggrLayer(nn.Module):
"""
metapath attention layer.
"""
def __init__(self, in_features, nmeta, dropout, alpha):
super(MetapathAggrLayer, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.alpha = alpha
self.n_meta = nmeta
self.a = nn.Parameter(torch.zeros(size=(in_features, 1)))
nn.init.xavier_uniform_(self.a.data, gain=1.414)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, input):
input = input.transpose(0, 1)
N = input.size()[0]
a_input = input
e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))
e = F.softmax(e, dim=1)
output = [torch.matmul(e[i], input[i]).unsqueeze(0) for i in range(N)]
output = torch.cat(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, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'nmeta': 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._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__unsafe_view_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * (x1 // 4) + 16 * (x1 % 4)), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused__softmax_leaky_relu_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)
tmp6 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 4.0
tmp4 = tmp0 * tmp3
tmp5 = tl.where(tmp2, tmp0, tmp4)
tmp7 = tmp6 > tmp1
tmp8 = tmp6 * tmp3
tmp9 = tl.where(tmp7, tmp6, tmp8)
tmp11 = tmp10 > tmp1
tmp12 = tmp10 * tmp3
tmp13 = tl.where(tmp11, tmp10, tmp12)
tmp14 = triton_helpers.maximum(tmp9, tmp13)
tmp16 = tmp15 > tmp1
tmp17 = tmp15 * tmp3
tmp18 = tl.where(tmp16, tmp15, tmp17)
tmp19 = triton_helpers.maximum(tmp14, tmp18)
tmp21 = tmp20 > tmp1
tmp22 = tmp20 * tmp3
tmp23 = tl.where(tmp21, tmp20, tmp22)
tmp24 = triton_helpers.maximum(tmp19, tmp23)
tmp25 = tmp5 - tmp24
tmp26 = tl_math.exp(tmp25)
tl.store(out_ptr0 + x2, tmp26, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_cat_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x0 = xindex % 4
x2 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + x0, tmp4 & xmask, eviction_policy='evict_last',
other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 2, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + x0, tmp9 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 3, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr2 + x0, tmp14 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp16 = tmp0 >= tmp12
tl.full([1], 4, tl.int64)
tmp19 = tl.load(in_ptr3 + x0, tmp16 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = tl.where(tmp14, tmp15, tmp19)
tmp21 = tl.where(tmp9, tmp10, tmp20)
tmp22 = tl.where(tmp4, tmp5, tmp21)
tl.store(out_ptr0 + x2, tmp22, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__unsafe_view_clone_0[grid(64)](primals_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf0, primals_2, out=buf1)
del primals_2
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_leaky_relu_1[grid(16)](buf1, buf2, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf2
buf4 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (1, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (16, 1), 0), out=buf4)
buf5 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (1, 4), (4, 1), 4),
reinterpret_tensor(primals_1, (4, 4), (16, 1), 4), out=buf5)
buf6 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (1, 4), (4, 1), 8),
reinterpret_tensor(primals_1, (4, 4), (16, 1), 8), out=buf6)
buf7 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (1, 4), (4, 1), 12),
reinterpret_tensor(primals_1, (4, 4), (16, 1), 12), out=buf7)
buf8 = buf3
del buf3
triton_poi_fused_cat_3[grid(16)](buf4, buf5, buf6, buf7, buf8, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf4
del buf5
del buf6
del buf7
return buf8, buf1, reinterpret_tensor(primals_1, (4, 4), (1, 16), 12
), reinterpret_tensor(primals_1, (4, 4), (1, 16), 8
), reinterpret_tensor(primals_1, (4, 4), (1, 16), 4
), reinterpret_tensor(primals_1, (4, 4), (1, 16), 0
), reinterpret_tensor(buf0, (4, 16), (1, 4), 0)
class MetapathAggrLayerNew(nn.Module):
"""
metapath attention layer.
"""
def __init__(self, in_features, nmeta, dropout, alpha):
super(MetapathAggrLayerNew, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.alpha = alpha
self.n_meta = nmeta
self.a = nn.Parameter(torch.zeros(size=(in_features, 1)))
nn.init.xavier_uniform_(self.a.data, gain=1.414)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
def forward(self, input_0):
primals_2 = self.a
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
dingdanhao110/HINGCN
|
MetapathAggrLayer
| false
| 1,850
|
[
"MIT"
] | 0
|
281b73c03bd3b00e35bce4c5e1c27076233555e4
|
https://github.com/dingdanhao110/HINGCN/tree/281b73c03bd3b00e35bce4c5e1c27076233555e4
|
SoftDiceLossSquared
|
import torch
import torch.nn as nn
import torch._C
import torch.serialization
class SoftDiceLossSquared(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0):
"""
squares the terms in the denominator as proposed by Milletari et al.
"""
super(SoftDiceLossSquared, self).__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
def forward(self, x, y, loss_mask=None):
shp_x = x.shape
shp_y = y.shape
if self.batch_dice:
axes = [0] + list(range(2, len(shp_x)))
else:
axes = list(range(2, len(shp_x)))
if self.apply_nonlin is not None:
x = self.apply_nonlin(x)
with torch.no_grad():
if len(shp_x) != len(shp_y):
y = y.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(x.shape, y.shape)]):
y_onehot = y
else:
y = y.long()
y_onehot = torch.zeros(shp_x)
if x.device.type == 'cuda':
y_onehot = y_onehot
y_onehot.scatter_(1, y, 1).float()
intersect = x * y_onehot
denominator = x ** 2 + y_onehot ** 2
intersect = intersect.sum(axes, False) + self.smooth
denominator = denominator.sum(axes, False) + self.smooth
dc = 2 * intersect / denominator
if not self.do_bg:
if self.batch_dice:
dc = dc[1:]
else:
dc = dc[:, 1:]
dc = dc.mean()
return -dc
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch._C
import torch.serialization
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_mul_pow_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
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]
tmp7 = tmp0 * tmp0
tmp8 = tmp1 * tmp1
tmp9 = tmp7 + tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_neg_1(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp5 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 + tmp1
tmp3 = 2.0
tmp4 = tmp2 * tmp3
tmp6 = tmp5 + tmp1
tmp7 = tmp4 / tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.sum(tmp8, 1)[:, None]
tmp11 = 16.0
tmp12 = tmp10 / tmp11
tmp13 = -tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1 = 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, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_add_mul_pow_sum_0[grid(16)](arg0_1, arg1_1, buf0,
buf1, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused_add_div_mean_mul_neg_1[grid(1)](buf3, buf0, buf1,
1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
return buf3,
class SoftDiceLossSquaredNew(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0):
"""
squares the terms in the denominator as proposed by Milletari et al.
"""
super(SoftDiceLossSquaredNew, self).__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dkswxd/Swin-Transformer-Semantic-Segmentation
|
SoftDiceLossSquared
| false
| 1,851
|
[
"Apache-2.0"
] | 0
|
6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
https://github.com/dkswxd/Swin-Transformer-Semantic-Segmentation/tree/6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
CBDNet
|
import torch
import torch.nn as nn
class CBDNet(nn.Module):
def __init__(self):
super(CBDNet, self).__init__()
self.relu = nn.ReLU(inplace=True)
self.E01 = nn.Conv2d(3, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E02 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E03 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E04 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E05 = nn.Conv2d(32, 3, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.DS01_layer00 = nn.Conv2d(6, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer02 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer03 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS02 = nn.Conv2d(64, 256, kernel_size=[2, 2], stride=(2, 2))
self.DS02_layer00_cf = nn.Conv2d(256, 128, kernel_size=[1, 1],
stride=(1, 1))
self.DS02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer02 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03 = nn.Conv2d(128, 512, kernel_size=[2, 2], stride=(2, 2))
self.DS03_layer00_cf = nn.Conv2d(512, 256, kernel_size=[1, 1],
stride=(1, 1))
self.DS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.UPS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer03 = nn.Conv2d(256, 512, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.USP02 = nn.ConvTranspose2d(512, 128, kernel_size=[2, 2],
stride=(2, 2), bias=False)
self.US02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer02 = nn.Conv2d(128, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.USP01 = nn.ConvTranspose2d(256, 64, kernel_size=[2, 2], stride
=(2, 2), bias=False)
self.US01_layer00 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer02 = nn.Conv2d(64, 3, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
def forward(self, input):
x = self.E01(input)
self.relu(x)
x = self.E02(x)
self.relu(x)
x = self.E03(x)
self.relu(x)
x = self.E04(x)
self.relu(x)
x = self.E05(x)
self.relu(x)
noise_level = x
x = torch.cat((input, noise_level), dim=1)
x = self.DS01_layer00(x)
self.relu(x)
x = self.DS01_layer01(x)
self.relu(x)
x = self.DS01_layer02(x)
self.relu(x)
x = self.DS01_layer03(x)
self.relu(x)
down1_result = x
x = self.DS02(down1_result)
x = self.DS02_layer00_cf(x)
x = self.DS02_layer00(x)
self.relu(x)
x = self.DS02_layer01(x)
self.relu(x)
x = self.DS02_layer02(x)
self.relu(x)
down2_result = x
x = self.DS03(down2_result)
x = self.DS03_layer00_cf(x)
x = self.DS03_layer00(x)
self.relu(x)
x = self.DS03_layer01(x)
self.relu(x)
x = self.DS03_layer02(x)
self.relu(x)
x = self.UPS03_layer00(x)
self.relu(x)
x = self.UPS03_layer01(x)
self.relu(x)
x = self.UPS03_layer02(x)
self.relu(x)
x = self.UPS03_layer03(x)
self.relu(x)
x = self.USP02(x)
x = torch.add(x, 1, down2_result)
del down2_result
x = self.US02_layer00(x)
self.relu(x)
x = self.US02_layer01(x)
self.relu(x)
x = self.US02_layer02(x)
self.relu(x)
x = self.USP01(x)
x = torch.add(x, 1, down1_result)
del down1_result
x = self.US01_layer00(x)
self.relu(x)
x = self.US01_layer01(x)
self.relu(x)
x = self.US01_layer02(x)
y = torch.add(input, 1, x)
del x
return noise_level, y
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_1(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, None)
tl.store(out_ptr0 + x3, tmp6, None)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 6
x0 = xindex % 4096
x2 = xindex // 24576
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 3, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 12288 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 6, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 4096 * (-3 + x1) + 12288 * x2), tmp6,
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, None)
@triton.jit
def triton_poi_fused_convolution_relu_3(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_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)
x3 = xindex
x1 = xindex // 1024 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 512
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_8(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_relu_9(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_10(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 512
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_add_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)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + x0, None)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_relu_12(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_add_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)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + x0, None)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, None)
@triton.jit
def triton_poi_fused_add_convolution_14(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_out_ptr0 + x3, None)
tmp2 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tl.store(in_out_ptr0 + x3, tmp4, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47,
primals_48, primals_49, primals_50, primals_51, primals_52,
primals_53, primals_54, primals_55, primals_56, primals_57,
primals_58, primals_59, primals_60, primals_61) = args
args.clear()
assert_size_stride(primals_1, (32, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (3, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_11, (3,), (1,))
assert_size_stride(primals_12, (64, 6, 3, 3), (54, 9, 3, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_15, (64,), (1,))
assert_size_stride(primals_16, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_17, (64,), (1,))
assert_size_stride(primals_18, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_19, (64,), (1,))
assert_size_stride(primals_20, (256, 64, 2, 2), (256, 4, 2, 1))
assert_size_stride(primals_21, (256,), (1,))
assert_size_stride(primals_22, (128, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_23, (128,), (1,))
assert_size_stride(primals_24, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_25, (128,), (1,))
assert_size_stride(primals_26, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_27, (128,), (1,))
assert_size_stride(primals_28, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_29, (128,), (1,))
assert_size_stride(primals_30, (512, 128, 2, 2), (512, 4, 2, 1))
assert_size_stride(primals_31, (512,), (1,))
assert_size_stride(primals_32, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_33, (256,), (1,))
assert_size_stride(primals_34, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_35, (256,), (1,))
assert_size_stride(primals_36, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_37, (256,), (1,))
assert_size_stride(primals_38, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_39, (256,), (1,))
assert_size_stride(primals_40, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_41, (256,), (1,))
assert_size_stride(primals_42, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_43, (256,), (1,))
assert_size_stride(primals_44, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_45, (256,), (1,))
assert_size_stride(primals_46, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_47, (512,), (1,))
assert_size_stride(primals_48, (512, 128, 2, 2), (512, 4, 2, 1))
assert_size_stride(primals_49, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_50, (128,), (1,))
assert_size_stride(primals_51, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_52, (128,), (1,))
assert_size_stride(primals_53, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_54, (256,), (1,))
assert_size_stride(primals_55, (256, 64, 2, 2), (256, 4, 2, 1))
assert_size_stride(primals_56, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_57, (64,), (1,))
assert_size_stride(primals_58, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_59, (64,), (1,))
assert_size_stride(primals_60, (3, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_61, (3,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(524288)](buf1, primals_2,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(524288)](buf3, primals_5,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_0[grid(524288)](buf5, primals_7,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_0[grid(524288)](buf7, primals_9,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_9
buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf9 = buf8
del buf8
buf63 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_1[grid(49152)](
buf9, primals_11, buf63, 49152, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_11
buf10 = empty_strided_cuda((4, 6, 64, 64), (24576, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_2[grid(98304)](primals_3, buf9, buf10, 98304,
XBLOCK=1024, num_warps=4, num_stages=1)
buf11 = extern_kernels.convolution(buf10, primals_12, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf11, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf12 = buf11
del buf11
triton_poi_fused_convolution_relu_3[grid(1048576)](buf12,
primals_13, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf13 = extern_kernels.convolution(buf12, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf13, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf14 = buf13
del buf13
triton_poi_fused_convolution_relu_3[grid(1048576)](buf14,
primals_15, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_15
buf15 = extern_kernels.convolution(buf14, primals_16, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf15, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf16 = buf15
del buf15
triton_poi_fused_convolution_relu_3[grid(1048576)](buf16,
primals_17, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_17
buf17 = extern_kernels.convolution(buf16, primals_18, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf18 = buf17
del buf17
triton_poi_fused_convolution_relu_3[grid(1048576)](buf18,
primals_19, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_19
buf19 = extern_kernels.convolution(buf18, primals_20, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 256, 32, 32), (262144, 1024, 32, 1))
buf20 = buf19
del buf19
triton_poi_fused_convolution_4[grid(1048576)](buf20, primals_21,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_21
buf21 = extern_kernels.convolution(buf20, primals_22, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf21, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf22 = buf21
del buf21
triton_poi_fused_convolution_5[grid(524288)](buf22, primals_23,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_23
buf23 = extern_kernels.convolution(buf22, primals_24, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf23, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf24 = buf23
del buf23
triton_poi_fused_convolution_relu_6[grid(524288)](buf24, primals_25,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_25
buf25 = extern_kernels.convolution(buf24, primals_26, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf25, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf26 = buf25
del buf25
triton_poi_fused_convolution_relu_6[grid(524288)](buf26, primals_27,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_27
buf27 = extern_kernels.convolution(buf26, primals_28, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf28 = buf27
del buf27
triton_poi_fused_convolution_relu_6[grid(524288)](buf28, primals_29,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_29
buf29 = extern_kernels.convolution(buf28, primals_30, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf29, (4, 512, 16, 16), (131072, 256, 16, 1))
buf30 = buf29
del buf29
triton_poi_fused_convolution_7[grid(524288)](buf30, primals_31,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_31
buf31 = extern_kernels.convolution(buf30, primals_32, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf31, (4, 256, 16, 16), (65536, 256, 16, 1))
buf32 = buf31
del buf31
triton_poi_fused_convolution_8[grid(262144)](buf32, primals_33,
262144, XBLOCK=512, num_warps=8, num_stages=1)
del primals_33
buf33 = extern_kernels.convolution(buf32, primals_34, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf33, (4, 256, 16, 16), (65536, 256, 16, 1))
buf34 = buf33
del buf33
triton_poi_fused_convolution_relu_9[grid(262144)](buf34, primals_35,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_35
buf35 = extern_kernels.convolution(buf34, primals_36, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf35, (4, 256, 16, 16), (65536, 256, 16, 1))
buf36 = buf35
del buf35
triton_poi_fused_convolution_relu_9[grid(262144)](buf36, primals_37,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_37
buf37 = extern_kernels.convolution(buf36, primals_38, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf37, (4, 256, 16, 16), (65536, 256, 16, 1))
buf38 = buf37
del buf37
triton_poi_fused_convolution_relu_9[grid(262144)](buf38, primals_39,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_39
buf39 = extern_kernels.convolution(buf38, primals_40, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf39, (4, 256, 16, 16), (65536, 256, 16, 1))
buf40 = buf39
del buf39
triton_poi_fused_convolution_relu_9[grid(262144)](buf40, primals_41,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_41
buf41 = extern_kernels.convolution(buf40, primals_42, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf41, (4, 256, 16, 16), (65536, 256, 16, 1))
buf42 = buf41
del buf41
triton_poi_fused_convolution_relu_9[grid(262144)](buf42, primals_43,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_43
buf43 = extern_kernels.convolution(buf42, primals_44, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf43, (4, 256, 16, 16), (65536, 256, 16, 1))
buf44 = buf43
del buf43
triton_poi_fused_convolution_relu_9[grid(262144)](buf44, primals_45,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_45
buf45 = extern_kernels.convolution(buf44, primals_46, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf45, (4, 512, 16, 16), (131072, 256, 16, 1))
buf46 = buf45
del buf45
triton_poi_fused_convolution_relu_10[grid(524288)](buf46,
primals_47, 524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_47
buf47 = extern_kernels.convolution(buf46, primals_48, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf47, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf48 = buf47
del buf47
triton_poi_fused_add_11[grid(524288)](buf48, buf28, 524288, XBLOCK=
1024, num_warps=4, num_stages=1)
buf49 = extern_kernels.convolution(buf48, primals_49, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf49, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf50 = buf49
del buf49
triton_poi_fused_convolution_relu_6[grid(524288)](buf50, primals_50,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_50
buf51 = extern_kernels.convolution(buf50, primals_51, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf51, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf52 = buf51
del buf51
triton_poi_fused_convolution_relu_6[grid(524288)](buf52, primals_52,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_52
buf53 = extern_kernels.convolution(buf52, primals_53, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf53, (4, 256, 32, 32), (262144, 1024, 32, 1))
buf54 = buf53
del buf53
triton_poi_fused_convolution_relu_12[grid(1048576)](buf54,
primals_54, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_54
buf55 = extern_kernels.convolution(buf54, primals_55, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf55, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf56 = buf55
del buf55
triton_poi_fused_add_13[grid(1048576)](buf56, buf18, 1048576,
XBLOCK=1024, num_warps=4, num_stages=1)
buf57 = extern_kernels.convolution(buf56, primals_56, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf57, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf58 = buf57
del buf57
triton_poi_fused_convolution_relu_3[grid(1048576)](buf58,
primals_57, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_57
buf59 = extern_kernels.convolution(buf58, primals_58, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf59, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf60 = buf59
del buf59
triton_poi_fused_convolution_relu_3[grid(1048576)](buf60,
primals_59, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_59
buf61 = extern_kernels.convolution(buf60, primals_60, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf61, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf62 = buf61
del buf61
triton_poi_fused_add_convolution_14[grid(49152)](buf62, primals_3,
primals_61, 49152, XBLOCK=512, num_warps=4, num_stages=1)
del primals_61
return (buf9, buf62, 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,
primals_48, primals_49, primals_51, primals_53, primals_55,
primals_56, primals_58, primals_60, buf1, buf3, buf5, buf7, buf10,
buf12, buf14, buf16, buf18, buf20, buf22, buf24, buf26, buf28,
buf30, buf32, buf34, buf36, buf38, buf40, buf42, buf44, buf46,
buf48, buf50, buf52, buf54, buf56, buf58, buf60, buf63)
class CBDNetNew(nn.Module):
def __init__(self):
super(CBDNetNew, self).__init__()
self.relu = nn.ReLU(inplace=True)
self.E01 = nn.Conv2d(3, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E02 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E03 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E04 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E05 = nn.Conv2d(32, 3, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.DS01_layer00 = nn.Conv2d(6, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer02 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer03 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS02 = nn.Conv2d(64, 256, kernel_size=[2, 2], stride=(2, 2))
self.DS02_layer00_cf = nn.Conv2d(256, 128, kernel_size=[1, 1],
stride=(1, 1))
self.DS02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer02 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03 = nn.Conv2d(128, 512, kernel_size=[2, 2], stride=(2, 2))
self.DS03_layer00_cf = nn.Conv2d(512, 256, kernel_size=[1, 1],
stride=(1, 1))
self.DS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.UPS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer03 = nn.Conv2d(256, 512, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.USP02 = nn.ConvTranspose2d(512, 128, kernel_size=[2, 2],
stride=(2, 2), bias=False)
self.US02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer02 = nn.Conv2d(128, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.USP01 = nn.ConvTranspose2d(256, 64, kernel_size=[2, 2], stride
=(2, 2), bias=False)
self.US01_layer00 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer02 = nn.Conv2d(64, 3, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
def forward(self, input_0):
primals_1 = self.E01.weight
primals_2 = self.E01.bias
primals_4 = self.E02.weight
primals_5 = self.E02.bias
primals_6 = self.E03.weight
primals_7 = self.E03.bias
primals_8 = self.E04.weight
primals_9 = self.E04.bias
primals_10 = self.E05.weight
primals_11 = self.E05.bias
primals_12 = self.DS01_layer00.weight
primals_13 = self.DS01_layer00.bias
primals_14 = self.DS01_layer01.weight
primals_15 = self.DS01_layer01.bias
primals_16 = self.DS01_layer02.weight
primals_17 = self.DS01_layer02.bias
primals_18 = self.DS01_layer03.weight
primals_19 = self.DS01_layer03.bias
primals_20 = self.DS02.weight
primals_21 = self.DS02.bias
primals_22 = self.DS02_layer00_cf.weight
primals_23 = self.DS02_layer00_cf.bias
primals_24 = self.DS02_layer00.weight
primals_25 = self.DS02_layer00.bias
primals_26 = self.DS02_layer01.weight
primals_27 = self.DS02_layer01.bias
primals_28 = self.DS02_layer02.weight
primals_29 = self.DS02_layer02.bias
primals_30 = self.DS03.weight
primals_31 = self.DS03.bias
primals_32 = self.DS03_layer00_cf.weight
primals_33 = self.DS03_layer00_cf.bias
primals_34 = self.DS03_layer00.weight
primals_35 = self.DS03_layer00.bias
primals_36 = self.DS03_layer01.weight
primals_37 = self.DS03_layer01.bias
primals_38 = self.DS03_layer02.weight
primals_39 = self.DS03_layer02.bias
primals_40 = self.UPS03_layer00.weight
primals_41 = self.UPS03_layer00.bias
primals_42 = self.UPS03_layer01.weight
primals_43 = self.UPS03_layer01.bias
primals_44 = self.UPS03_layer02.weight
primals_45 = self.UPS03_layer02.bias
primals_46 = self.UPS03_layer03.weight
primals_47 = self.UPS03_layer03.bias
primals_48 = self.USP02.weight
primals_49 = self.US02_layer00.weight
primals_50 = self.US02_layer00.bias
primals_51 = self.US02_layer01.weight
primals_52 = self.US02_layer01.bias
primals_53 = self.US02_layer02.weight
primals_54 = self.US02_layer02.bias
primals_55 = self.USP01.weight
primals_56 = self.US01_layer00.weight
primals_57 = self.US01_layer00.bias
primals_58 = self.US01_layer01.weight
primals_59 = self.US01_layer01.bias
primals_60 = self.US01_layer02.weight
primals_61 = self.US01_layer02.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
primals_40, primals_41, primals_42, primals_43, primals_44,
primals_45, primals_46, primals_47, primals_48, primals_49,
primals_50, primals_51, primals_52, primals_53, primals_54,
primals_55, primals_56, primals_57, primals_58, primals_59,
primals_60, primals_61])
return output[0], output[1]
|
delldu/ImageClean
|
CBDNet
| false
| 1,852
|
[
"MIT"
] | 0
|
ffa5b180d36afb3840c6b36c08a767c520068498
|
https://github.com/delldu/ImageClean/tree/ffa5b180d36afb3840c6b36c08a767c520068498
|
LinearThreeDeep
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearThreeDeep(nn.Module):
def __init__(self, inputSize, hiddenSize1, hiddenSize2, hiddenSize3,
outputSize):
super().__init__()
self.inputLinear = nn.Linear(inputSize, hiddenSize1)
self.hiddenLinear1 = nn.Linear(hiddenSize1, hiddenSize2)
self.hiddenLinear2 = nn.Linear(hiddenSize2, hiddenSize3)
self.outputLinear = nn.Linear(hiddenSize3, outputSize)
def forward(self, inputNodes):
hiddenNodesL1 = F.relu(self.inputLinear(inputNodes))
hiddenNodesL2 = F.relu(self.hiddenLinear1(hiddenNodesL1))
hiddenNodesL3 = F.relu(self.hiddenLinear2(hiddenNodesL2))
outputNodes = F.softmax(self.outputLinear(hiddenNodesL3))
return outputNodes
def getParameters(self):
return tuple(self.parameters())
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inputSize': 4, 'hiddenSize1': 4, 'hiddenSize2': 4,
'hiddenSize3': 4, 'outputSize': 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_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x3, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
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, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1,
primals_2, buf11, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3,
primals_5, buf10, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf5,
primals_7, buf9, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf6)
del primals_9
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf6, buf7, 256, XBLOCK=256,
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_2[grid(256)](buf7, buf8, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf7
return buf8, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(
buf3, (64, 4), (4, 1), 0), reinterpret_tensor(buf5, (64, 4), (4, 1), 0
), buf8, primals_8, buf9, primals_6, buf10, primals_4, buf11
class LinearThreeDeepNew(nn.Module):
def __init__(self, inputSize, hiddenSize1, hiddenSize2, hiddenSize3,
outputSize):
super().__init__()
self.inputLinear = nn.Linear(inputSize, hiddenSize1)
self.hiddenLinear1 = nn.Linear(hiddenSize1, hiddenSize2)
self.hiddenLinear2 = nn.Linear(hiddenSize2, hiddenSize3)
self.outputLinear = nn.Linear(hiddenSize3, outputSize)
def getParameters(self):
return tuple(self.parameters())
def forward(self, input_0):
primals_1 = self.inputLinear.weight
primals_2 = self.inputLinear.bias
primals_4 = self.hiddenLinear1.weight
primals_5 = self.hiddenLinear1.bias
primals_6 = self.hiddenLinear2.weight
primals_7 = self.hiddenLinear2.bias
primals_8 = self.outputLinear.weight
primals_9 = self.outputLinear.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
dmechea/PyTorch-CartPole
|
LinearThreeDeep
| false
| 1,853
|
[
"MIT"
] | 0
|
9f49ac7b2ae59882e5ea66cc8f43f0354a120c49
|
https://github.com/dmechea/PyTorch-CartPole/tree/9f49ac7b2ae59882e5ea66cc8f43f0354a120c49
|
SoftDiceLoss
|
import torch
import torch.nn as nn
import torch._C
import torch.serialization
def get_tp_fp_fn_tn(net_output, gt, axes=None, mask=None, square=False):
"""
net_output must be (b, c, x, y(, z)))
gt must be a label map (shape (b, 1, x, y(, z)) OR shape (b, x, y(, z))) or one hot encoding (b, c, x, y(, z))
if mask is provided it must have shape (b, 1, x, y(, z)))
:param net_output:
:param gt:
:param axes: can be (, ) = no summation
:param mask: mask must be 1 for valid pixels and 0 for invalid pixels
:param square: if True then fp, tp and fn will be squared before summation
:return:
"""
if axes is None:
axes = tuple(range(2, len(net_output.size())))
shp_x = net_output.shape
shp_y = gt.shape
with torch.no_grad():
if len(shp_x) != len(shp_y):
gt = gt.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(net_output.shape, gt.shape)]):
y_onehot = gt
else:
gt = gt.long()
y_onehot = torch.zeros(shp_x, device=net_output.device)
y_onehot.scatter_(1, gt, 1)
tp = net_output * y_onehot
fp = net_output * (1 - y_onehot)
fn = (1 - net_output) * y_onehot
tn = (1 - net_output) * (1 - y_onehot)
if mask is not None:
tp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tp,
dim=1)), dim=1)
fp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fp,
dim=1)), dim=1)
fn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fn,
dim=1)), dim=1)
tn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tn,
dim=1)), dim=1)
if square:
tp = tp ** 2
fp = fp ** 2
fn = fn ** 2
tn = tn ** 2
if len(axes) > 0:
tp = tp.sum(axes, keepdim=False)
fp = fp.sum(axes, keepdim=False)
fn = fn.sum(axes, keepdim=False)
tn = tn.sum(axes, keepdim=False)
return tp, fp, fn, tn
class SoftDiceLoss(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0):
"""
"""
super(SoftDiceLoss, self).__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
def forward(self, x, y, loss_mask=None):
shp_x = x.shape
if self.batch_dice:
axes = [0] + list(range(2, len(shp_x)))
else:
axes = list(range(2, len(shp_x)))
if self.apply_nonlin is not None:
x = self.apply_nonlin(x)
tp, fp, fn, _ = get_tp_fp_fn_tn(x, y, axes, loss_mask, False)
nominator = 2 * tp + self.smooth
denominator = 2 * tp + fp + fn + self.smooth
dc = nominator / (denominator + 1e-08)
if not self.do_bg:
if self.batch_dice:
dc = dc[1:]
else:
dc = dc[:, 1:]
dc = dc.mean()
return -dc
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch._C
import torch.serialization
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_rsub_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = 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]
tmp7 = 1.0
tmp8 = tmp7 - tmp1
tmp9 = tmp0 * tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tmp14 = tmp7 - tmp0
tmp15 = tmp14 * tmp1
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.where(xmask, tmp16, 0)
tmp19 = tl.sum(tmp18, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
tl.store(out_ptr2 + x0, tmp19, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_neg_1(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp5 = tl.load(in_ptr1 + r0, None)
tmp7 = tl.load(in_ptr2 + r0, None)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tmp3 = 1.0
tmp4 = tmp2 + tmp3
tmp6 = tmp2 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = tmp8 + tmp3
tmp10 = 1e-08
tmp11 = tmp9 + tmp10
tmp12 = tmp4 / tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.sum(tmp13, 1)[:, None]
tmp16 = 16.0
tmp17 = tmp15 / tmp16
tmp18 = -tmp17
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 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((4, 4), (4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_rsub_sum_0[grid(16)](arg0_1, arg1_1, buf0,
buf1, buf2, 16, 16, XBLOCK=8, 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_mean_mul_neg_1[grid(1)](buf4, buf0, buf1,
buf2, 1, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf2
return buf4,
def get_tp_fp_fn_tn(net_output, gt, axes=None, mask=None, square=False):
"""
net_output must be (b, c, x, y(, z)))
gt must be a label map (shape (b, 1, x, y(, z)) OR shape (b, x, y(, z))) or one hot encoding (b, c, x, y(, z))
if mask is provided it must have shape (b, 1, x, y(, z)))
:param net_output:
:param gt:
:param axes: can be (, ) = no summation
:param mask: mask must be 1 for valid pixels and 0 for invalid pixels
:param square: if True then fp, tp and fn will be squared before summation
:return:
"""
if axes is None:
axes = tuple(range(2, len(net_output.size())))
shp_x = net_output.shape
shp_y = gt.shape
with torch.no_grad():
if len(shp_x) != len(shp_y):
gt = gt.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(net_output.shape, gt.shape)]):
y_onehot = gt
else:
gt = gt.long()
y_onehot = torch.zeros(shp_x, device=net_output.device)
y_onehot.scatter_(1, gt, 1)
tp = net_output * y_onehot
fp = net_output * (1 - y_onehot)
fn = (1 - net_output) * y_onehot
tn = (1 - net_output) * (1 - y_onehot)
if mask is not None:
tp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tp,
dim=1)), dim=1)
fp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fp,
dim=1)), dim=1)
fn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fn,
dim=1)), dim=1)
tn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tn,
dim=1)), dim=1)
if square:
tp = tp ** 2
fp = fp ** 2
fn = fn ** 2
tn = tn ** 2
if len(axes) > 0:
tp = tp.sum(axes, keepdim=False)
fp = fp.sum(axes, keepdim=False)
fn = fn.sum(axes, keepdim=False)
tn = tn.sum(axes, keepdim=False)
return tp, fp, fn, tn
class SoftDiceLossNew(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0):
"""
"""
super(SoftDiceLossNew, self).__init__()
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dkswxd/Swin-Transformer-Semantic-Segmentation
|
SoftDiceLoss
| false
| 1,855
|
[
"Apache-2.0"
] | 0
|
6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
https://github.com/dkswxd/Swin-Transformer-Semantic-Segmentation/tree/6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
GCNLayer
|
import torch
import torch.nn as nn
class GCNLayer(nn.Module):
def __init__(self, c_in, c_out):
super().__init__()
self.projection = nn.Linear(c_in, c_out)
def forward(self, nodes_feats, adj_matrix):
num_neighbors = adj_matrix.sum(dim=-1, keepdims=True)
node_feats = self.projection(nodes_feats)
node_feats = torch.bmm(adj_matrix, node_feats)
node_feats = node_feats / num_neighbors
return node_feats
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'c_in': 4, 'c_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_div_sum_0(in_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
x1 = xindex // 4
tmp0 = tl.load(in_out_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(in_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), (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))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, reinterpret_tensor(primals_4, (16,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(primals_1, reinterpret_tensor(buf0, (4, 4, 4), (
16, 4, 1), 0), out=buf1)
del buf0
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_div_sum_0[grid(64)](buf2, primals_1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf2, primals_1, reinterpret_tensor(primals_4, (16, 4), (4, 1), 0)
class GCNLayerNew(nn.Module):
def __init__(self, c_in, c_out):
super().__init__()
self.projection = nn.Linear(c_in, c_out)
def forward(self, input_0, input_1):
primals_2 = self.projection.weight
primals_3 = self.projection.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
dogeplusplus/sandbox
|
GCNLayer
| false
| 1,856
|
[
"MIT"
] | 0
|
c9041c06da9454f6c3cec622abbbf918c9f13bdc
|
https://github.com/dogeplusplus/sandbox/tree/c9041c06da9454f6c3cec622abbbf918c9f13bdc
|
DilateConv
|
import torch
import torch.nn as nn
class DilateConv(nn.Module):
"""
d_rate: dilation rate
H_{out} = floor((H_{in} + 2 * padding[0] - dilation[0] * (kernel\\_size[0] - 1) - 1) / stride[0] + 1)
set kernel size to 3, stride to 1, padding==d_rate ==> spatial size kept
"""
def __init__(self, d_rate, in_ch, out_ch):
super(DilateConv, self).__init__()
self.d_conv = nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1,
padding=d_rate, dilation=d_rate)
def forward(self, x):
return self.d_conv(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_rate': 4, 'in_ch': 4, 'out_ch': 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
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(4, 4), dilation=(4, 4), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(256)](buf1, primals_2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return buf1, primals_1, primals_3
class DilateConvNew(nn.Module):
"""
d_rate: dilation rate
H_{out} = floor((H_{in} + 2 * padding[0] - dilation[0] * (kernel\\_size[0] - 1) - 1) / stride[0] + 1)
set kernel size to 3, stride to 1, padding==d_rate ==> spatial size kept
"""
def __init__(self, d_rate, in_ch, out_ch):
super(DilateConvNew, self).__init__()
self.d_conv = nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=1,
padding=d_rate, dilation=d_rate)
def forward(self, input_0):
primals_1 = self.d_conv.weight
primals_2 = self.d_conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
donghaW/RCF-pytorch
|
DilateConv
| false
| 1,857
|
[
"MIT"
] | 0
|
6380209ef747abefa87637e60d33369ba423814d
|
https://github.com/donghaW/RCF-pytorch/tree/6380209ef747abefa87637e60d33369ba423814d
|
GDL
|
import torch
import torch.nn as nn
import torch._C
import torch.serialization
def get_tp_fp_fn_tn(net_output, gt, axes=None, mask=None, square=False):
"""
net_output must be (b, c, x, y(, z)))
gt must be a label map (shape (b, 1, x, y(, z)) OR shape (b, x, y(, z))) or one hot encoding (b, c, x, y(, z))
if mask is provided it must have shape (b, 1, x, y(, z)))
:param net_output:
:param gt:
:param axes: can be (, ) = no summation
:param mask: mask must be 1 for valid pixels and 0 for invalid pixels
:param square: if True then fp, tp and fn will be squared before summation
:return:
"""
if axes is None:
axes = tuple(range(2, len(net_output.size())))
shp_x = net_output.shape
shp_y = gt.shape
with torch.no_grad():
if len(shp_x) != len(shp_y):
gt = gt.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(net_output.shape, gt.shape)]):
y_onehot = gt
else:
gt = gt.long()
y_onehot = torch.zeros(shp_x, device=net_output.device)
y_onehot.scatter_(1, gt, 1)
tp = net_output * y_onehot
fp = net_output * (1 - y_onehot)
fn = (1 - net_output) * y_onehot
tn = (1 - net_output) * (1 - y_onehot)
if mask is not None:
tp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tp,
dim=1)), dim=1)
fp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fp,
dim=1)), dim=1)
fn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fn,
dim=1)), dim=1)
tn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tn,
dim=1)), dim=1)
if square:
tp = tp ** 2
fp = fp ** 2
fn = fn ** 2
tn = tn ** 2
if len(axes) > 0:
tp = tp.sum(axes, keepdim=False)
fp = fp.sum(axes, keepdim=False)
fn = fn.sum(axes, keepdim=False)
tn = tn.sum(axes, keepdim=False)
return tp, fp, fn, tn
class GDL(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0, square=False, square_volumes=False, loss_weight=1.0):
"""
square_volumes will square the weight term. The paper recommends square_volumes=True; I don't (just an intuition)
"""
super(GDL, self).__init__()
self.square_volumes = square_volumes
self.square = square
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
self.loss_weight = loss_weight
def forward(self, x, y, loss_mask=None):
shp_x = x.shape
shp_y = y.shape
if self.batch_dice:
axes = [0] + list(range(2, len(shp_x)))
else:
axes = list(range(2, len(shp_x)))
if len(shp_x) != len(shp_y):
y = y.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(x.shape, y.shape)]):
y_onehot = y
else:
gt = y.long()
y_onehot = torch.zeros(shp_x)
if x.device.type == 'cuda':
y_onehot = y_onehot
y_onehot.scatter_(1, gt, 1)
if self.apply_nonlin is not None:
x = self.apply_nonlin(x)
if not self.do_bg:
x = x[:, 1:]
y_onehot = y_onehot[:, 1:]
tp, fp, fn, _ = get_tp_fp_fn_tn(x, y_onehot, axes, loss_mask, self.
square)
volumes = y_onehot.sum(axes) + 1e-06
if self.square_volumes:
volumes = volumes ** 2
tp = tp / volumes
fp = fp / volumes
fn = fn / volumes
if self.batch_dice:
axis = 0
else:
axis = 1
tp = tp.sum(axis, keepdim=False)
fp = fp.sum(axis, keepdim=False)
fn = fn.sum(axis, keepdim=False)
dc = (2 * tp + self.smooth) / (2 * tp + fp + fn + self.smooth)
dc = dc.mean()
return -dc * self.loss_weight
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch._C
import torch.serialization
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_rsub_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
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.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]
tmp7 = 1.0
tmp8 = tmp7 - tmp1
tmp9 = tmp0 * tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.where(xmask, tmp10, 0)
tmp13 = tl.sum(tmp12, 1)[:, None]
tmp14 = tmp7 - tmp0
tmp15 = tmp14 * tmp1
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp18 = tl.where(xmask, tmp16, 0)
tmp19 = tl.sum(tmp18, 1)[:, None]
tmp20 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp22 = tl.where(xmask, tmp20, 0)
tmp23 = tl.sum(tmp22, 1)[:, None]
tl.store(out_ptr0 + x0, tmp6, xmask)
tl.store(out_ptr1 + x0, tmp13, xmask)
tl.store(out_ptr2 + x0, tmp19, xmask)
tl.store(out_ptr3 + x0, tmp23, xmask)
@triton.jit
def triton_per_fused_add_div_mean_mul_neg_sum_1(in_out_ptr1, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, 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')
tmp5 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr2 + 4 * r0, None, eviction_policy='evict_last')
tmp24 = tl.load(in_ptr2 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr2 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp34 = tl.load(in_ptr3 + 4 * r0, None, eviction_policy='evict_last')
tmp36 = tl.load(in_ptr3 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp39 = tl.load(in_ptr3 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp42 = tl.load(in_ptr3 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp2 = 1e-06
tmp3 = tmp1 + tmp2
tmp4 = tmp0 / tmp3
tmp7 = tmp6 + tmp2
tmp8 = tmp5 / tmp7
tmp9 = tmp4 + tmp8
tmp12 = tmp11 + tmp2
tmp13 = tmp10 / tmp12
tmp14 = tmp9 + tmp13
tmp17 = tmp16 + tmp2
tmp18 = tmp15 / tmp17
tmp19 = tmp14 + tmp18
tmp20 = 2.0
tmp21 = tmp19 * tmp20
tmp23 = tmp22 / tmp3
tmp25 = tmp24 / tmp7
tmp26 = tmp23 + tmp25
tmp28 = tmp27 / tmp12
tmp29 = tmp26 + tmp28
tmp31 = tmp30 / tmp17
tmp32 = tmp29 + tmp31
tmp33 = tmp21 + tmp32
tmp35 = tmp34 / tmp3
tmp37 = tmp36 / tmp7
tmp38 = tmp35 + tmp37
tmp40 = tmp39 / tmp12
tmp41 = tmp38 + tmp40
tmp43 = tmp42 / tmp17
tmp44 = tmp41 + tmp43
tmp45 = tmp33 + tmp44
tmp46 = 1.0
tmp47 = tmp21 + tmp46
tmp48 = tmp45 + tmp46
tmp49 = tmp47 / tmp48
tmp50 = tl.broadcast_to(tmp49, [XBLOCK, RBLOCK])
tmp52 = tl.sum(tmp50, 1)[:, None]
tmp53 = 4.0
tmp54 = tmp52 / tmp53
tmp55 = -tmp54
tmp56 = tmp55 * tmp46
tl.debug_barrier()
tl.store(in_out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp56, 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, 1), torch.float32)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_mul_rsub_sum_0[grid(16)](arg0_1, arg1_1, buf0,
buf3, buf5, buf1, 16, 16, XBLOCK=8, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf7 = empty_strided_cuda((), (), torch.float32)
buf8 = buf7
del buf7
triton_per_fused_add_div_mean_mul_neg_sum_1[grid(1)](buf8, buf0,
buf1, buf3, buf5, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del buf1
del buf3
del buf5
return buf8,
def get_tp_fp_fn_tn(net_output, gt, axes=None, mask=None, square=False):
"""
net_output must be (b, c, x, y(, z)))
gt must be a label map (shape (b, 1, x, y(, z)) OR shape (b, x, y(, z))) or one hot encoding (b, c, x, y(, z))
if mask is provided it must have shape (b, 1, x, y(, z)))
:param net_output:
:param gt:
:param axes: can be (, ) = no summation
:param mask: mask must be 1 for valid pixels and 0 for invalid pixels
:param square: if True then fp, tp and fn will be squared before summation
:return:
"""
if axes is None:
axes = tuple(range(2, len(net_output.size())))
shp_x = net_output.shape
shp_y = gt.shape
with torch.no_grad():
if len(shp_x) != len(shp_y):
gt = gt.view((shp_y[0], 1, *shp_y[1:]))
if all([(i == j) for i, j in zip(net_output.shape, gt.shape)]):
y_onehot = gt
else:
gt = gt.long()
y_onehot = torch.zeros(shp_x, device=net_output.device)
y_onehot.scatter_(1, gt, 1)
tp = net_output * y_onehot
fp = net_output * (1 - y_onehot)
fn = (1 - net_output) * y_onehot
tn = (1 - net_output) * (1 - y_onehot)
if mask is not None:
tp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tp,
dim=1)), dim=1)
fp = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fp,
dim=1)), dim=1)
fn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(fn,
dim=1)), dim=1)
tn = torch.stack(tuple(x_i * mask[:, 0] for x_i in torch.unbind(tn,
dim=1)), dim=1)
if square:
tp = tp ** 2
fp = fp ** 2
fn = fn ** 2
tn = tn ** 2
if len(axes) > 0:
tp = tp.sum(axes, keepdim=False)
fp = fp.sum(axes, keepdim=False)
fn = fn.sum(axes, keepdim=False)
tn = tn.sum(axes, keepdim=False)
return tp, fp, fn, tn
class GDLNew(nn.Module):
def __init__(self, apply_nonlin=None, batch_dice=False, do_bg=True,
smooth=1.0, square=False, square_volumes=False, loss_weight=1.0):
"""
square_volumes will square the weight term. The paper recommends square_volumes=True; I don't (just an intuition)
"""
super(GDLNew, self).__init__()
self.square_volumes = square_volumes
self.square = square
self.do_bg = do_bg
self.batch_dice = batch_dice
self.apply_nonlin = apply_nonlin
self.smooth = smooth
self.loss_weight = loss_weight
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
dkswxd/Swin-Transformer-Semantic-Segmentation
|
GDL
| false
| 1,858
|
[
"Apache-2.0"
] | 0
|
6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
https://github.com/dkswxd/Swin-Transformer-Semantic-Segmentation/tree/6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
ImageCleanModel
|
import torch
import torch.nn as nn
class ImageCleanModel(nn.Module):
"""ImageClean Model."""
def __init__(self):
"""Init model."""
super(ImageCleanModel, self).__init__()
self.relu = nn.ReLU(inplace=True)
self.E01 = nn.Conv2d(3, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E02 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E03 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E04 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E05 = nn.Conv2d(32, 3, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.DS01_layer00 = nn.Conv2d(6, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer02 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer03 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS02 = nn.Conv2d(64, 256, kernel_size=[2, 2], stride=(2, 2))
self.DS02_layer00_cf = nn.Conv2d(256, 128, kernel_size=[1, 1],
stride=(1, 1))
self.DS02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer02 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03 = nn.Conv2d(128, 512, kernel_size=[2, 2], stride=(2, 2))
self.DS03_layer00_cf = nn.Conv2d(512, 256, kernel_size=[1, 1],
stride=(1, 1))
self.DS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.UPS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer03 = nn.Conv2d(256, 512, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.USP02 = nn.ConvTranspose2d(512, 128, kernel_size=[2, 2],
stride=(2, 2), bias=False)
self.US02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer02 = nn.Conv2d(128, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.USP01 = nn.ConvTranspose2d(256, 64, kernel_size=[2, 2], stride
=(2, 2), bias=False)
self.US01_layer00 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer02 = nn.Conv2d(64, 3, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
def forward(self, input):
x = self.relu(self.E01(input))
x = self.relu(self.E02(x))
x = self.relu(self.E03(x))
x = self.relu(self.E04(x))
x = self.relu(self.E05(x))
noise_level = x
x = torch.cat((input, noise_level), dim=1)
x = self.relu(self.DS01_layer00(x))
x = self.relu(self.DS01_layer01(x))
x = self.relu(self.DS01_layer02(x))
x = self.relu(self.DS01_layer03(x))
down1_result = x
x = self.DS02(down1_result)
x = self.DS02_layer00_cf(x)
x = self.relu(self.DS02_layer00(x))
x = self.relu(self.DS02_layer01(x))
x = self.relu(self.DS02_layer02(x))
down2_result = x
x = self.DS03(down2_result)
x = self.DS03_layer00_cf(x)
x = self.relu(self.DS03_layer00(x))
x = self.relu(self.DS03_layer01(x))
x = self.relu(self.DS03_layer02(x))
x = self.relu(self.UPS03_layer00(x))
x = self.relu(self.UPS03_layer01(x))
x = self.relu(self.UPS03_layer02(x))
x = self.relu(self.UPS03_layer03(x))
x = self.USP02(x)
x = torch.add(x, down2_result, alpha=1)
del down2_result
x = self.relu(self.US02_layer00(x))
x = self.relu(self.US02_layer01(x))
x = self.relu(self.US02_layer02(x))
x = self.USP01(x)
x = torch.add(x, down1_result, alpha=1)
del down1_result
x = self.relu(self.US01_layer00(x))
x = self.relu(self.US01_layer01(x))
x = self.US01_layer02(x)
y = torch.add(input, x, alpha=1)
del x
return y.clamp(0.0, 1.0)
def get_inputs():
return [torch.rand([4, 3, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_cat_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 4096 % 6
x0 = xindex % 4096
x2 = xindex // 24576
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 3, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 12288 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 6, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 4096 * (-3 + x1) + 12288 * x2), tmp6,
other=0.0)
tmp10 = tl.load(in_ptr2 + (-3 + x1), tmp6, eviction_policy='evict_last',
other=0.0)
tmp11 = tmp9 + tmp10
tmp12 = tl.full([1], 0, tl.int32)
tmp13 = triton_helpers.maximum(tmp12, tmp11)
tmp14 = tl.full(tmp13.shape, 0.0, tmp13.dtype)
tmp15 = tl.where(tmp6, tmp13, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 1024 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 512
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_relu_8(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_9(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 512
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_add_10(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, None)
tmp1 = tl.load(in_ptr0 + x0, None)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, 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)
x3 = xindex
x1 = xindex // 1024 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_add_12(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 + x0, None)
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x0, tmp2, None)
@triton.jit
def triton_poi_fused_add_clamp_convolution_ge_le_logical_and_13(in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x3, None)
tmp2 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp4 = tmp0 + tmp3
tmp5 = 0.0
tmp6 = triton_helpers.maximum(tmp4, tmp5)
tmp7 = 1.0
tmp8 = triton_helpers.minimum(tmp6, tmp7)
tmp9 = tmp4 >= tmp5
tmp10 = tmp4 <= tmp7
tmp11 = tmp9 & tmp10
tl.store(out_ptr0 + x3, tmp8, None)
tl.store(out_ptr1 + x3, tmp11, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_14(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 3
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(out_ptr0 + x3, tmp6, None)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47,
primals_48, primals_49, primals_50, primals_51, primals_52,
primals_53, primals_54, primals_55, primals_56, primals_57,
primals_58, primals_59, primals_60, primals_61) = args
args.clear()
assert_size_stride(primals_1, (32, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1))
assert_size_stride(primals_4, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_7, (32,), (1,))
assert_size_stride(primals_8, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (3, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_11, (3,), (1,))
assert_size_stride(primals_12, (64, 6, 3, 3), (54, 9, 3, 1))
assert_size_stride(primals_13, (64,), (1,))
assert_size_stride(primals_14, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_15, (64,), (1,))
assert_size_stride(primals_16, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_17, (64,), (1,))
assert_size_stride(primals_18, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_19, (64,), (1,))
assert_size_stride(primals_20, (256, 64, 2, 2), (256, 4, 2, 1))
assert_size_stride(primals_21, (256,), (1,))
assert_size_stride(primals_22, (128, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_23, (128,), (1,))
assert_size_stride(primals_24, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_25, (128,), (1,))
assert_size_stride(primals_26, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_27, (128,), (1,))
assert_size_stride(primals_28, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_29, (128,), (1,))
assert_size_stride(primals_30, (512, 128, 2, 2), (512, 4, 2, 1))
assert_size_stride(primals_31, (512,), (1,))
assert_size_stride(primals_32, (256, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_33, (256,), (1,))
assert_size_stride(primals_34, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_35, (256,), (1,))
assert_size_stride(primals_36, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_37, (256,), (1,))
assert_size_stride(primals_38, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_39, (256,), (1,))
assert_size_stride(primals_40, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_41, (256,), (1,))
assert_size_stride(primals_42, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_43, (256,), (1,))
assert_size_stride(primals_44, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_45, (256,), (1,))
assert_size_stride(primals_46, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_47, (512,), (1,))
assert_size_stride(primals_48, (512, 128, 2, 2), (512, 4, 2, 1))
assert_size_stride(primals_49, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_50, (128,), (1,))
assert_size_stride(primals_51, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_52, (128,), (1,))
assert_size_stride(primals_53, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_54, (256,), (1,))
assert_size_stride(primals_55, (256, 64, 2, 2), (256, 4, 2, 1))
assert_size_stride(primals_56, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_57, (64,), (1,))
assert_size_stride(primals_58, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_59, (64,), (1,))
assert_size_stride(primals_60, (3, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_61, (3,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(524288)](buf1, primals_2,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(524288)](buf3, primals_5,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_0[grid(524288)](buf5, primals_7,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 32, 64, 64), (131072, 4096, 64, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_0[grid(524288)](buf7, primals_9,
524288, XBLOCK=512, num_warps=8, num_stages=1)
del primals_9
buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf9 = empty_strided_cuda((4, 6, 64, 64), (24576, 4096, 64, 1),
torch.float32)
triton_poi_fused_cat_1[grid(98304)](primals_3, buf8, primals_11,
buf9, 98304, XBLOCK=512, num_warps=8, num_stages=1)
buf10 = extern_kernels.convolution(buf9, primals_12, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_relu_2[grid(1048576)](buf11,
primals_13, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf12 = extern_kernels.convolution(buf11, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_2[grid(1048576)](buf13,
primals_15, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_15
buf14 = extern_kernels.convolution(buf13, primals_16, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf15 = buf14
del buf14
triton_poi_fused_convolution_relu_2[grid(1048576)](buf15,
primals_17, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_17
buf16 = extern_kernels.convolution(buf15, primals_18, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf17 = buf16
del buf16
triton_poi_fused_convolution_relu_2[grid(1048576)](buf17,
primals_19, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_19
buf18 = extern_kernels.convolution(buf17, primals_20, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf18, (4, 256, 32, 32), (262144, 1024, 32, 1))
buf19 = buf18
del buf18
triton_poi_fused_convolution_3[grid(1048576)](buf19, primals_21,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_21
buf20 = extern_kernels.convolution(buf19, primals_22, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf20, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf21 = buf20
del buf20
triton_poi_fused_convolution_4[grid(524288)](buf21, primals_23,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_23
buf22 = extern_kernels.convolution(buf21, primals_24, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf22, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf23 = buf22
del buf22
triton_poi_fused_convolution_relu_5[grid(524288)](buf23, primals_25,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_25
buf24 = extern_kernels.convolution(buf23, primals_26, 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, 32, 32), (131072, 1024, 32, 1))
buf25 = buf24
del buf24
triton_poi_fused_convolution_relu_5[grid(524288)](buf25, primals_27,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_27
buf26 = extern_kernels.convolution(buf25, primals_28, 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, 32, 32), (131072, 1024, 32, 1))
buf27 = buf26
del buf26
triton_poi_fused_convolution_relu_5[grid(524288)](buf27, primals_29,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_29
buf28 = extern_kernels.convolution(buf27, primals_30, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf28, (4, 512, 16, 16), (131072, 256, 16, 1))
buf29 = buf28
del buf28
triton_poi_fused_convolution_6[grid(524288)](buf29, primals_31,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_31
buf30 = extern_kernels.convolution(buf29, primals_32, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf30, (4, 256, 16, 16), (65536, 256, 16, 1))
buf31 = buf30
del buf30
triton_poi_fused_convolution_7[grid(262144)](buf31, primals_33,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_33
buf32 = extern_kernels.convolution(buf31, primals_34, 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, 16, 16), (65536, 256, 16, 1))
buf33 = buf32
del buf32
triton_poi_fused_convolution_relu_8[grid(262144)](buf33, primals_35,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_35
buf34 = extern_kernels.convolution(buf33, primals_36, 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, 16, 16), (65536, 256, 16, 1))
buf35 = buf34
del buf34
triton_poi_fused_convolution_relu_8[grid(262144)](buf35, primals_37,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_37
buf36 = extern_kernels.convolution(buf35, primals_38, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf36, (4, 256, 16, 16), (65536, 256, 16, 1))
buf37 = buf36
del buf36
triton_poi_fused_convolution_relu_8[grid(262144)](buf37, primals_39,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_39
buf38 = extern_kernels.convolution(buf37, primals_40, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf38, (4, 256, 16, 16), (65536, 256, 16, 1))
buf39 = buf38
del buf38
triton_poi_fused_convolution_relu_8[grid(262144)](buf39, primals_41,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_41
buf40 = extern_kernels.convolution(buf39, primals_42, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf40, (4, 256, 16, 16), (65536, 256, 16, 1))
buf41 = buf40
del buf40
triton_poi_fused_convolution_relu_8[grid(262144)](buf41, primals_43,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_43
buf42 = extern_kernels.convolution(buf41, primals_44, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf42, (4, 256, 16, 16), (65536, 256, 16, 1))
buf43 = buf42
del buf42
triton_poi_fused_convolution_relu_8[grid(262144)](buf43, primals_45,
262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_45
buf44 = extern_kernels.convolution(buf43, primals_46, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf44, (4, 512, 16, 16), (131072, 256, 16, 1))
buf45 = buf44
del buf44
triton_poi_fused_convolution_relu_9[grid(524288)](buf45, primals_47,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_47
buf46 = extern_kernels.convolution(buf45, primals_48, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf46, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf47 = buf46
del buf46
triton_poi_fused_add_10[grid(524288)](buf47, buf27, 524288, XBLOCK=
512, num_warps=8, num_stages=1)
buf48 = extern_kernels.convolution(buf47, primals_49, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf48, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf49 = buf48
del buf48
triton_poi_fused_convolution_relu_5[grid(524288)](buf49, primals_50,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_50
buf50 = extern_kernels.convolution(buf49, primals_51, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf50, (4, 128, 32, 32), (131072, 1024, 32, 1))
buf51 = buf50
del buf50
triton_poi_fused_convolution_relu_5[grid(524288)](buf51, primals_52,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_52
buf52 = extern_kernels.convolution(buf51, primals_53, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf52, (4, 256, 32, 32), (262144, 1024, 32, 1))
buf53 = buf52
del buf52
triton_poi_fused_convolution_relu_11[grid(1048576)](buf53,
primals_54, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_54
buf54 = extern_kernels.convolution(buf53, primals_55, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=True,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf54, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf55 = buf54
del buf54
triton_poi_fused_add_12[grid(1048576)](buf55, buf17, 1048576,
XBLOCK=1024, num_warps=4, num_stages=1)
buf56 = extern_kernels.convolution(buf55, primals_56, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf56, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf57 = buf56
del buf56
triton_poi_fused_convolution_relu_2[grid(1048576)](buf57,
primals_57, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_57
buf58 = extern_kernels.convolution(buf57, primals_58, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf58, (4, 64, 64, 64), (262144, 4096, 64, 1))
buf59 = buf58
del buf58
triton_poi_fused_convolution_relu_2[grid(1048576)](buf59,
primals_59, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_59
buf60 = extern_kernels.convolution(buf59, primals_60, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf60, (4, 3, 64, 64), (12288, 4096, 64, 1))
buf61 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.float32)
buf62 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_add_clamp_convolution_ge_le_logical_and_13[grid(49152)
](primals_3, buf60, primals_61, buf61, buf62, 49152, XBLOCK=256,
num_warps=4, num_stages=1)
del buf60
del primals_61
buf63 = empty_strided_cuda((4, 3, 64, 64), (12288, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_14[grid(49152)](
buf8, primals_11, buf63, 49152, XBLOCK=256, num_warps=4,
num_stages=1)
del buf8
del primals_11
return (buf61, 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, primals_48,
primals_49, primals_51, primals_53, primals_55, primals_56,
primals_58, primals_60, buf1, buf3, buf5, buf7, buf9, buf11, buf13,
buf15, buf17, buf19, buf21, buf23, buf25, buf27, buf29, buf31,
buf33, buf35, buf37, buf39, buf41, buf43, buf45, buf47, buf49,
buf51, buf53, buf55, buf57, buf59, buf62, buf63)
class ImageCleanModelNew(nn.Module):
"""ImageClean Model."""
def __init__(self):
"""Init model."""
super(ImageCleanModelNew, self).__init__()
self.relu = nn.ReLU(inplace=True)
self.E01 = nn.Conv2d(3, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E02 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E03 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E04 = nn.Conv2d(32, 32, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.E05 = nn.Conv2d(32, 3, kernel_size=[3, 3], stride=(1, 1),
padding=(1, 1))
self.DS01_layer00 = nn.Conv2d(6, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer02 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS01_layer03 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.DS02 = nn.Conv2d(64, 256, kernel_size=[2, 2], stride=(2, 2))
self.DS02_layer00_cf = nn.Conv2d(256, 128, kernel_size=[1, 1],
stride=(1, 1))
self.DS02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS02_layer02 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03 = nn.Conv2d(128, 512, kernel_size=[2, 2], stride=(2, 2))
self.DS03_layer00_cf = nn.Conv2d(512, 256, kernel_size=[1, 1],
stride=(1, 1))
self.DS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.DS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.UPS03_layer00 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer01 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer02 = nn.Conv2d(256, 256, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.UPS03_layer03 = nn.Conv2d(256, 512, kernel_size=[3, 3], stride
=(1, 1), padding=(1, 1))
self.USP02 = nn.ConvTranspose2d(512, 128, kernel_size=[2, 2],
stride=(2, 2), bias=False)
self.US02_layer00 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer01 = nn.Conv2d(128, 128, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.US02_layer02 = nn.Conv2d(128, 256, kernel_size=[3, 3], stride=
(1, 1), padding=(1, 1))
self.USP01 = nn.ConvTranspose2d(256, 64, kernel_size=[2, 2], stride
=(2, 2), bias=False)
self.US01_layer00 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer01 = nn.Conv2d(64, 64, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
self.US01_layer02 = nn.Conv2d(64, 3, kernel_size=[3, 3], stride=(1,
1), padding=(1, 1))
def forward(self, input_0):
primals_1 = self.E01.weight
primals_2 = self.E01.bias
primals_4 = self.E02.weight
primals_5 = self.E02.bias
primals_6 = self.E03.weight
primals_7 = self.E03.bias
primals_8 = self.E04.weight
primals_9 = self.E04.bias
primals_10 = self.E05.weight
primals_11 = self.E05.bias
primals_12 = self.DS01_layer00.weight
primals_13 = self.DS01_layer00.bias
primals_14 = self.DS01_layer01.weight
primals_15 = self.DS01_layer01.bias
primals_16 = self.DS01_layer02.weight
primals_17 = self.DS01_layer02.bias
primals_18 = self.DS01_layer03.weight
primals_19 = self.DS01_layer03.bias
primals_20 = self.DS02.weight
primals_21 = self.DS02.bias
primals_22 = self.DS02_layer00_cf.weight
primals_23 = self.DS02_layer00_cf.bias
primals_24 = self.DS02_layer00.weight
primals_25 = self.DS02_layer00.bias
primals_26 = self.DS02_layer01.weight
primals_27 = self.DS02_layer01.bias
primals_28 = self.DS02_layer02.weight
primals_29 = self.DS02_layer02.bias
primals_30 = self.DS03.weight
primals_31 = self.DS03.bias
primals_32 = self.DS03_layer00_cf.weight
primals_33 = self.DS03_layer00_cf.bias
primals_34 = self.DS03_layer00.weight
primals_35 = self.DS03_layer00.bias
primals_36 = self.DS03_layer01.weight
primals_37 = self.DS03_layer01.bias
primals_38 = self.DS03_layer02.weight
primals_39 = self.DS03_layer02.bias
primals_40 = self.UPS03_layer00.weight
primals_41 = self.UPS03_layer00.bias
primals_42 = self.UPS03_layer01.weight
primals_43 = self.UPS03_layer01.bias
primals_44 = self.UPS03_layer02.weight
primals_45 = self.UPS03_layer02.bias
primals_46 = self.UPS03_layer03.weight
primals_47 = self.UPS03_layer03.bias
primals_48 = self.USP02.weight
primals_49 = self.US02_layer00.weight
primals_50 = self.US02_layer00.bias
primals_51 = self.US02_layer01.weight
primals_52 = self.US02_layer01.bias
primals_53 = self.US02_layer02.weight
primals_54 = self.US02_layer02.bias
primals_55 = self.USP01.weight
primals_56 = self.US01_layer00.weight
primals_57 = self.US01_layer00.bias
primals_58 = self.US01_layer01.weight
primals_59 = self.US01_layer01.bias
primals_60 = self.US01_layer02.weight
primals_61 = self.US01_layer02.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18, primals_19,
primals_20, primals_21, primals_22, primals_23, primals_24,
primals_25, primals_26, primals_27, primals_28, primals_29,
primals_30, primals_31, primals_32, primals_33, primals_34,
primals_35, primals_36, primals_37, primals_38, primals_39,
primals_40, primals_41, primals_42, primals_43, primals_44,
primals_45, primals_46, primals_47, primals_48, primals_49,
primals_50, primals_51, primals_52, primals_53, primals_54,
primals_55, primals_56, primals_57, primals_58, primals_59,
primals_60, primals_61])
return output[0]
|
delldu/ImageClean
|
ImageCleanModel
| false
| 1,859
|
[
"MIT"
] | 0
|
ffa5b180d36afb3840c6b36c08a767c520068498
|
https://github.com/delldu/ImageClean/tree/ffa5b180d36afb3840c6b36c08a767c520068498
|
NeuralGasEnergy
|
import torch
class NeuralGasEnergy(torch.nn.Module):
def __init__(self, lm):
super().__init__()
self.lm = lm
def forward(self, d):
order = torch.argsort(d, dim=1)
ranks = torch.argsort(order, dim=1)
cost = torch.sum(self._nghood_fn(ranks, self.lm) * d)
return cost, order
def extra_repr(self):
return f'lambda: {self.lm}'
@staticmethod
def _nghood_fn(rankings, lm):
return torch.exp(-rankings / lm)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'lm': 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
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_sort_0(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = r2
tmp2 = tmp1.to(tl.int16)
tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp4 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
_tmp5, tmp6 = triton_helpers.sort_with_index(tmp3, tmp4, None, 1,
stable=False, descending=False)
tl.store(out_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp6, xmask)
@triton.jit
def triton_poi_fused_sort_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.to(tl.int64)
tl.store(out_ptr0 + x0, tmp1, xmask)
@triton.jit
def triton_per_fused_sort_2(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x0 = xindex % 16
x1 = xindex // 16
tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 64 * x1), xmask, other=0.0)
tmp1 = r2
tmp2 = tmp1.to(tl.int16)
tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp4 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
_tmp5, tmp6 = triton_helpers.sort_with_index(tmp3, tmp4, None, 1,
stable=False, descending=False)
tl.store(out_ptr0 + (x0 + 16 * r2 + 64 * x1), tmp6, xmask)
@triton.jit
def triton_per_fused_div_exp_mul_neg_sort_sum_3(in_ptr0, in_ptr1, out_ptr0,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp7 = tl.load(in_ptr1 + r0, None)
tmp1 = tmp0.to(tl.int64)
tmp2 = -tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = 0.25
tmp5 = tmp3 * tmp4
tmp6 = tl_math.exp(tmp5)
tmp8 = tmp6 * tmp7
tmp9 = tl.broadcast_to(tmp8, [RBLOCK])
tmp11 = triton_helpers.promote_to_tensor(tl.sum(tmp9, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp11, None)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int16)
get_raw_stream(0)
triton_per_fused_sort_0[grid(64)](arg0_1, buf1, 64, 4, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.int64)
triton_poi_fused_sort_1[grid(256)](buf1, buf2, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = buf1
del buf1
triton_per_fused_sort_2[grid(64)](buf2, buf4, 64, 4, XBLOCK=32,
num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_div_exp_mul_neg_sort_sum_3[grid(1)](buf4, arg0_1,
buf5, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf4
return buf5, buf2
class NeuralGasEnergyNew(torch.nn.Module):
def __init__(self, lm):
super().__init__()
self.lm = lm
def extra_repr(self):
return f'lambda: {self.lm}'
@staticmethod
def _nghood_fn(rankings, lm):
return torch.exp(-rankings / lm)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0], output[1]
|
dmoebius-dm/prototorch
|
NeuralGasEnergy
| false
| 1,860
|
[
"MIT"
] | 0
|
088429a16a820f31367bb7b780dce0e368633fb2
|
https://github.com/dmoebius-dm/prototorch/tree/088429a16a820f31367bb7b780dce0e368633fb2
|
PatchEmbed
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch._C
import torch.serialization
class PatchEmbed(nn.Module):
""" Image to Patch Embedding
Args:
patch_size (tuple[int]): Patch token size. Default: (4, 4, 4).
in_chans (int): Number of input image channels. Default: 1.
embed_dim (int): Number of linear projection output channels. Default: 96.
norm_layer (nn.Module, optional): Normalization layer. Default: None
"""
def __init__(self, patch_size=(4, 4, 4), in_chans=1, embed_dim=96,
norm_layer=None, use_spectral_aggregation='None'):
super().__init__()
self._patch_size = patch_size
self.in_chans = in_chans
self.embed_dim = embed_dim
self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size,
stride=patch_size)
if norm_layer is not None:
self.norm = norm_layer(embed_dim)
else:
self.norm = None
self.use_spectral_aggregation = use_spectral_aggregation
if self.use_spectral_aggregation == 'token':
self.spectral_aggregation_token = nn.Parameter(data=torch.empty
(embed_dim), requires_grad=True)
trunc_normal_(self.spectral_aggregation_token, std=0.02)
def forward(self, x):
"""Forward function."""
if self.use_spectral_aggregation != 'None':
x = F.instance_norm(x)
x = torch.unsqueeze(x, 1)
_, _, S, H, W = x.size()
if W % self._patch_size[2] != 0:
x = F.pad(x, [0, self._patch_size[2] - W % self._patch_size[2]])
if H % self._patch_size[1] != 0:
x = F.pad(x, [0, 0, 0, self._patch_size[1] - H % self.
_patch_size[1]])
if S % self._patch_size[0] != 0:
x = F.pad(x, [0, 0, 0, 0, 0, self._patch_size[0] - S % self.
_patch_size[0]])
x = self.proj(x)
if self.use_spectral_aggregation == 'token':
_b, _c, _s, _h, _w = x.shape
token = self.spectral_aggregation_token.view(1, -1, 1, 1, 1
).repeat(_b, 1, 1, _h, _w)
x = torch.cat((token, x), dim=2)
if self.norm is not None:
Ws, Wh, Ww = x.size(2), x.size(3), x.size(4)
x = x.flatten(2).transpose(1, 2)
x = self.norm(x)
x = x.transpose(1, 2).view(-1, self.embed_dim, Ws, Wh, Ww)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch._C
import torch.serialization
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 96
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, None)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 64, 64, 64), (262144, 262144, 4096,
64, 1))
assert_size_stride(primals_2, (96, 1, 4, 4, 4), (64, 64, 16, 4, 1))
assert_size_stride(primals_3, (96,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(4,
4, 4), padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 96, 16, 16, 16), (393216, 4096, 256,
16, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(1572864)](buf1, primals_3,
1572864, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_3
return buf1, primals_1, primals_2
class PatchEmbedNew(nn.Module):
""" Image to Patch Embedding
Args:
patch_size (tuple[int]): Patch token size. Default: (4, 4, 4).
in_chans (int): Number of input image channels. Default: 1.
embed_dim (int): Number of linear projection output channels. Default: 96.
norm_layer (nn.Module, optional): Normalization layer. Default: None
"""
def __init__(self, patch_size=(4, 4, 4), in_chans=1, embed_dim=96,
norm_layer=None, use_spectral_aggregation='None'):
super().__init__()
self._patch_size = patch_size
self.in_chans = in_chans
self.embed_dim = embed_dim
self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size,
stride=patch_size)
if norm_layer is not None:
self.norm = norm_layer(embed_dim)
else:
self.norm = None
self.use_spectral_aggregation = use_spectral_aggregation
if self.use_spectral_aggregation == 'token':
self.spectral_aggregation_token = nn.Parameter(data=torch.empty
(embed_dim), requires_grad=True)
trunc_normal_(self.spectral_aggregation_token, std=0.02)
def forward(self, input_0):
primals_2 = self.proj.weight
primals_3 = self.proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dkswxd/Swin-Transformer-Semantic-Segmentation
|
PatchEmbed
| false
| 1,861
|
[
"Apache-2.0"
] | 0
|
6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
https://github.com/dkswxd/Swin-Transformer-Semantic-Segmentation/tree/6af19736e5492a01d8952d4ee86a6d59b21c2ae1
|
MNISTmodel
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class Evidential_layer(nn.Module):
def __init__(self, in_dim, num_classes):
super(Evidential_layer, self).__init__()
self.num_classes = num_classes
self.fc1 = nn.Linear(in_dim, 2 * self.num_classes)
self.relu = torch.nn.ReLU()
def forward(self, x):
x = self.fc1(x)
return self.relu(x)
class MNISTmodel(nn.Module):
def __init__(self, num_classes, edl, dropout=True):
super(MNISTmodel, self).__init__()
self.use_dropout = dropout
k, m = 8, 80
km = (64 - 2 * (k - 1)) ** 2 * m
self.num_classes = num_classes
self.conv1 = nn.Conv2d(1, 20, kernel_size=k)
self.conv2 = nn.Conv2d(20, m, kernel_size=k)
self.fc1 = nn.Linear(km, 500)
if edl:
self.fc2 = Evidential_layer(500, self.num_classes)
else:
self.fc2 = nn.Linear(500, self.num_classes)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 1))
x = F.relu(F.max_pool2d(self.conv2(x), 1))
x = x.view(x.size()[0], -1)
x = F.relu(self.fc1(x))
if self.use_dropout:
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return x
def get_inputs():
return [torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {'num_classes': 4, 'edl': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 1600
xnumel = 64
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 20
y1 = yindex // 20
tmp0 = tl.load(in_ptr0 + (x2 + 64 * y3), xmask & ymask, eviction_policy
='evict_last')
tl.store(out_ptr0 + (y0 + 20 * x2 + 1280 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 80
xnumel = 3249
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 % 20
y1 = yindex // 20
tmp0 = tl.load(in_ptr0 + (x2 + 3249 * y3), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (y0 + 20 * x2 + 64980 * y1), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_2(in_ptr0, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 259920
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.int8)
tmp2 = tl.full([1], 0, tl.int32)
tmp3 = triton_helpers.maximum(tmp2, tmp0)
tl.store(out_ptr0 + x0, tmp1, xmask)
tl.store(out_ptr1 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_convolution_max_pool2d_with_indices_3(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 800000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 80
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.int8)
tl.store(in_out_ptr0 + x2, tmp2, xmask)
tl.store(out_ptr0 + x2, tmp3, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_threshold_backward_4(in_ptr0,
out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
constexpr):
ynumel = 320
xnumel = 2500
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 % 80
y1 = yindex // 80
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 80 * x2 + 200000 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.full([1, 1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(out_ptr0 + (x2 + 2528 * y3), tmp2, xmask & ymask)
tl.store(out_ptr1 + (y0 + 80 * x2 + 200000 * y1), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_relu_view_5(in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 800000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 200000
x1 = xindex // 200000
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2528 * (x0 // 2500) + 202240 * x1 + x0 % 2500
), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_relu_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 2000
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 500
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_7(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 8
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (20, 1, 8, 8), (64, 64, 8, 1))
assert_size_stride(primals_2, (20,), (1,))
assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_4, (80, 20, 8, 8), (1280, 64, 8, 1))
assert_size_stride(primals_5, (80,), (1,))
assert_size_stride(primals_6, (500, 200000), (200000, 1))
assert_size_stride(primals_7, (500,), (1,))
assert_size_stride(primals_8, (8, 500), (500, 1))
assert_size_stride(primals_9, (8,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((80, 20, 8, 8), (1280, 1, 160, 20), torch
.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(1600, 64)](primals_4, buf0, 1600, 64,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_4
buf1 = 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(buf1, (4, 20, 57, 57), (64980, 3249, 57, 1))
buf2 = empty_strided_cuda((4, 20, 57, 57), (64980, 1, 1140, 20),
torch.float32)
triton_poi_fused_convolution_1[grid(80, 3249)](buf1, primals_2,
buf2, 80, 3249, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_2
buf3 = empty_strided_cuda((4, 20, 57, 57), (64980, 1, 1140, 20),
torch.int8)
buf4 = reinterpret_tensor(buf1, (4, 20, 57, 57), (64980, 1, 1140,
20), 0)
del buf1
triton_poi_fused_max_pool2d_with_indices_relu_2[grid(259920)](buf2,
buf3, buf4, 259920, XBLOCK=1024, num_warps=4, num_stages=1)
buf5 = extern_kernels.convolution(buf4, 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, 80, 50, 50), (200000, 1, 4000, 80))
buf6 = buf5
del buf5
buf7 = empty_strided_cuda((4, 80, 50, 50), (200000, 1, 4000, 80),
torch.int8)
triton_poi_fused_convolution_max_pool2d_with_indices_3[grid(800000)](
buf6, primals_5, buf7, 800000, XBLOCK=1024, num_warps=4,
num_stages=1)
del primals_5
buf8 = empty_strided_cuda((4, 80, 50, 50), (202240, 2528, 50, 1),
torch.float32)
buf15 = empty_strided_cuda((4, 80, 50, 50), (200000, 1, 4000, 80),
torch.bool)
triton_poi_fused_max_pool2d_with_indices_relu_threshold_backward_4[grid
(320, 2500)](buf6, buf8, buf15, 320, 2500, XBLOCK=32, YBLOCK=32,
num_warps=4, num_stages=1)
buf9 = empty_strided_cuda((4, 200000), (200000, 1), torch.float32)
triton_poi_fused_max_pool2d_with_indices_relu_view_5[grid(800000)](buf8
, buf9, 800000, XBLOCK=1024, num_warps=4, num_stages=1)
del buf8
buf10 = empty_strided_cuda((4, 500), (500, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_6, (200000, 500),
(1, 200000), 0), out=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_6[grid(2000)](buf11, primals_7, 2000, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_7
buf12 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(buf11, reinterpret_tensor(primals_8, (500, 8), (1,
500), 0), out=buf12)
buf13 = buf12
del buf12
buf14 = empty_strided_cuda((4, 8), (8, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_7[grid(32)](buf13,
primals_9, buf14, 32, XBLOCK=32, num_warps=1, num_stages=1)
del primals_9
return (buf13, primals_1, primals_3, buf0, buf2, buf3, buf4, buf6, buf7,
buf9, buf11, buf14, primals_8, primals_6, buf15)
class Evidential_layer(nn.Module):
def __init__(self, in_dim, num_classes):
super(Evidential_layer, self).__init__()
self.num_classes = num_classes
self.fc1 = nn.Linear(in_dim, 2 * self.num_classes)
self.relu = torch.nn.ReLU()
def forward(self, x):
x = self.fc1(x)
return self.relu(x)
class MNISTmodelNew(nn.Module):
def __init__(self, num_classes, edl, dropout=True):
super(MNISTmodelNew, self).__init__()
self.use_dropout = dropout
k, m = 8, 80
km = (64 - 2 * (k - 1)) ** 2 * m
self.num_classes = num_classes
self.conv1 = nn.Conv2d(1, 20, kernel_size=k)
self.conv2 = nn.Conv2d(20, m, kernel_size=k)
self.fc1 = nn.Linear(km, 500)
if edl:
self.fc2 = Evidential_layer(500, self.num_classes)
else:
self.fc2 = nn.Linear(500, self.num_classes)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.fc1.weight
primals_9 = self.fc2.fc1.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
caisr-hh/DEED
|
MNISTmodel
| false
| 1,862
|
[
"MIT"
] | 0
|
2a9edb1df31d99c1e8da177dec696d7c90c2e7de
|
https://github.com/caisr-hh/DEED/tree/2a9edb1df31d99c1e8da177dec696d7c90c2e7de
|
AngularLoss
|
import math
import torch
import torch.nn as nn
def calc_angular_difference(a1, a2):
distance = torch.min(torch.abs(a1 - a2), torch.tensor(2 * math.pi) -
torch.abs(a2 - a1))
diff = torch.sqrt(torch.abs(distance * distance))
return diff
class AngularLoss(nn.Module):
def __init__(self):
super(AngularLoss, self).__init__()
def forward(self, predicted, actual, mask=None):
return calc_angular_difference(predicted, actual)
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 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_abs_lift_fresh_minimum_mul_sqrt_sub_0(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tmp1 - tmp0
tmp5 = tl_math.abs(tmp4)
tmp6 = 6.2831854820251465
tmp7 = tmp6 - tmp5
tmp8 = triton_helpers.minimum(tmp3, tmp7)
tmp9 = tmp8 * tmp8
tmp10 = tl_math.abs(tmp9)
tmp11 = libdevice.sqrt(tmp10)
tl.store(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, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_abs_lift_fresh_minimum_mul_sqrt_sub_0[grid(256)](
arg0_1, arg1_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
def calc_angular_difference(a1, a2):
distance = torch.min(torch.abs(a1 - a2), torch.tensor(2 * math.pi) -
torch.abs(a2 - a1))
diff = torch.sqrt(torch.abs(distance * distance))
return diff
class AngularLossNew(nn.Module):
def __init__(self):
super(AngularLossNew, 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]
|
donikv/rgn_pytorch
|
AngularLoss
| false
| 1,863
|
[
"MIT"
] | 0
|
95f8cd36fec5655f9bfd8634fff89b06e81dc2ed
|
https://github.com/donikv/rgn_pytorch/tree/95f8cd36fec5655f9bfd8634fff89b06e81dc2ed
|
SelfAttention
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SelfAttention(nn.Module):
def __init__(self, k, heads=8):
super().__init__()
self.k = k
self.heads = heads
self.to_keys = nn.Linear(k, k * heads, bias=False)
self.to_queries = nn.Linear(k, k * heads, bias=False)
self.to_values = nn.Linear(k, k * heads, bias=False)
self.unify_heads = nn.Linear(heads * k, k)
def forward(self, x):
b, t, k = x.size()
h = self.heads
queries = self.to_queries(x).view(b, t, h, k)
keys = self.to_keys(x).view(b, t, h, k)
values = self.to_values(x).view(b, t, h, k)
keys = keys.transpose(1, 2).contiguous().view(b * h, t, k)
queries = queries.transpose(1, 2).contiguous().view(b * h, t, k)
values = values.transpose(1, 2).contiguous().view(b * h, t, k)
queries = queries / k ** (1 / 4)
keys = keys / k ** (1 / 4)
dot = torch.bmm(queries, keys.transpose(1, 2))
dot = F.softmax(dot, dim=2)
out = torch.bmm(dot, values).view(b, h, t, k)
out = out.transpose(1, 2).contiguous().view(b, t, h * k)
return self.unify_heads(out)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'k': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._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_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 32
x2 = xindex // 128
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * (x1 % 8) + 32 * x2 + 128 * (x1 // 8)
), xmask)
tmp1 = 0.7071067811865475
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_div_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * (x2 % 8) + 32 * x1 + 128 * (x2 // 8)
), xmask)
tmp1 = 0.7071067811865475
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
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 % 8
x3 = xindex // 128
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 32 * x1 + 128 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_5(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 8
x2 = xindex // 32 % 4
x3 = xindex // 128
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 128 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused_transpose_6(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 128 * x1), xmask)
tl.store(out_ptr0 + x3, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (32, 4), (4, 1))
assert_size_stride(primals_3, (32, 4), (4, 1))
assert_size_stride(primals_4, (32, 4), (4, 1))
assert_size_stride(primals_5, (4, 32), (32, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 32), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 32), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((16, 32), (32, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 32), (1, 4), 0), out=buf2)
del primals_4
buf3 = empty_strided_cuda((32, 4, 4), (4, 128, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(512)](buf0, buf3, 512, XBLOCK=128,
num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf0, (32, 4, 4), (16, 4, 1), 0)
del buf0
triton_poi_fused_div_1[grid(512)](buf1, buf4, 512, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf1, (32, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(buf3, reinterpret_tensor(buf4, (32, 4, 4), (16,
1, 4), 0), out=buf5)
buf6 = empty_strided_cuda((32, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(512)](buf5, buf6, 512, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_3[grid(512)](buf6, buf7, 512, XBLOCK=256,
num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf6, (4, 8, 4, 4), (128, 16, 4, 1), 0)
del buf6
triton_poi_fused_clone_4[grid(512)](buf2, buf8, 512, XBLOCK=256,
num_warps=4, num_stages=1)
buf9 = reinterpret_tensor(buf2, (32, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (32, 4, 4), (16,
4, 1), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 8, 4), (128, 32, 4, 1), torch.float32
)
triton_poi_fused_clone_5[grid(512)](buf9, buf10, 512, XBLOCK=256,
num_warps=4, num_stages=1)
buf11 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_6, reinterpret_tensor(buf10, (16, 32),
(32, 1), 0), reinterpret_tensor(primals_5, (32, 4), (1, 32), 0),
alpha=1, beta=1, out=buf11)
del primals_6
buf12 = reinterpret_tensor(buf9, (32, 4, 4), (16, 1, 4), 0)
del buf9
triton_poi_fused_transpose_6[grid(512)](buf3, buf12, 512, XBLOCK=
128, num_warps=4, num_stages=1)
del buf3
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 32), (32, 1), 0
), primals_5, reinterpret_tensor(buf8, (32, 4, 4), (16, 1, 4), 0
), buf12, buf4
class SelfAttentionNew(nn.Module):
def __init__(self, k, heads=8):
super().__init__()
self.k = k
self.heads = heads
self.to_keys = nn.Linear(k, k * heads, bias=False)
self.to_queries = nn.Linear(k, k * heads, bias=False)
self.to_values = nn.Linear(k, k * heads, bias=False)
self.unify_heads = nn.Linear(heads * k, k)
def forward(self, input_0):
primals_2 = self.to_keys.weight
primals_3 = self.to_queries.weight
primals_4 = self.to_values.weight
primals_5 = self.unify_heads.weight
primals_6 = self.unify_heads.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
dogeplusplus/sandbox
|
SelfAttention
| false
| 1,864
|
[
"MIT"
] | 0
|
c9041c06da9454f6c3cec622abbbf918c9f13bdc
|
https://github.com/dogeplusplus/sandbox/tree/c9041c06da9454f6c3cec622abbbf918c9f13bdc
|
GlobalWeightedAvgPool2d
|
import torch
import torch.nn as nn
import torch.nn.functional
import torch.nn.parallel
import torch.utils.data
import torch.optim
import torch.utils.data.distributed
def import_flatten_impl():
global flatten_impl, unflatten_impl, imported_flatten_impl
try:
flatten_impl = apex_C.flatten
unflatten_impl = apex_C.unflatten
except ImportError:
None
flatten_impl = torch._utils._flatten_dense_tensors
unflatten_impl = torch._utils._unflatten_dense_tensors
imported_flatten_impl = True
def flatten(bucket):
if not imported_flatten_impl:
import_flatten_impl()
return flatten_impl(bucket)
class GlobalWeightedAvgPool2d(nn.Module):
"""
Global Weighted Average Pooling from paper "Global Weighted Average
Pooling Bridges Pixel-level Localization and Image-level Classification"
"""
def __init__(self, features: 'int', flatten=False):
super().__init__()
self.conv = nn.Conv2d(features, 1, kernel_size=1, bias=True)
self.flatten = flatten
def fscore(self, x):
m = self.conv(x)
m = m.sigmoid().exp()
return m
def norm(self, x: 'torch.Tensor'):
return x / x.sum(dim=[2, 3], keepdim=True)
def forward(self, x):
input_x = x
x = self.fscore(x)
x = self.norm(x)
x = x * input_x
x = x.sum(dim=[2, 3], keepdim=not self.flatten)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'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 math as tl_math
import torch.nn as nn
import torch.nn.functional
import torch.nn.parallel
import torch.utils.data
import torch.optim
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_convolution_exp_sigmoid_sum_0(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp3 = tmp0 + tmp2
tmp4 = tl.sigmoid(tmp3)
tmp5 = tl_math.exp(tmp4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tl.store(in_out_ptr0 + (r1 + 16 * x0), tmp3, xmask)
tl.store(out_ptr0 + x0, tmp9, xmask)
@triton.jit
def triton_per_fused_div_exp_mul_sigmoid_sum_1(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x1 = xindex // 4
x3 = xindex
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x1), xmask, eviction_policy=
'evict_last', other=0.0)
tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr2 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.sigmoid(tmp0)
tmp2 = tl_math.exp(tmp1)
tmp4 = tmp2 / tmp3
tmp6 = tmp4 * tmp5
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tl.store(out_ptr0 + x3, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (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, 1, 4, 4), (16, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 1, 1, 1), (1, 1, 1, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_convolution_exp_sigmoid_sum_0[grid(4)](buf1,
primals_3, buf2, 4, 16, XBLOCK=1, num_warps=2, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
triton_per_fused_div_exp_mul_sigmoid_sum_1[grid(16)](buf1, buf2,
primals_1, buf3, 16, 16, XBLOCK=1, num_warps=2, num_stages=1)
return buf3, primals_1, primals_2, buf1, buf2
def import_flatten_impl():
global flatten_impl, unflatten_impl, imported_flatten_impl
try:
flatten_impl = apex_C.flatten
unflatten_impl = apex_C.unflatten
except ImportError:
None
flatten_impl = torch._utils._flatten_dense_tensors
unflatten_impl = torch._utils._unflatten_dense_tensors
imported_flatten_impl = True
def flatten(bucket):
if not imported_flatten_impl:
import_flatten_impl()
return flatten_impl(bucket)
class GlobalWeightedAvgPool2dNew(nn.Module):
"""
Global Weighted Average Pooling from paper "Global Weighted Average
Pooling Bridges Pixel-level Localization and Image-level Classification"
"""
def __init__(self, features: 'int', flatten=False):
super().__init__()
self.conv = nn.Conv2d(features, 1, kernel_size=1, bias=True)
self.flatten = flatten
def fscore(self, x):
m = self.conv(x)
m = m.sigmoid().exp()
return m
def norm(self, x: 'torch.Tensor'):
return x / x.sum(dim=[2, 3], keepdim=True)
def forward(self, input_0):
primals_2 = self.conv.weight
primals_3 = self.conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dong03/dfdc_deepfake_challenge
|
GlobalWeightedAvgPool2d
| false
| 1,865
|
[
"MIT"
] | 0
|
bee310d0e4f1f6c9bd8ec7c0c97a98b52667673d
|
https://github.com/dong03/dfdc_deepfake_challenge/tree/bee310d0e4f1f6c9bd8ec7c0c97a98b52667673d
|
BertTextPooler
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
class BertTextPooler(nn.Module):
def __init__(self, config):
super(BertTextPooler, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.bi_hidden_size)
self.activation = nn.ReLU()
def forward(self, hidden_states):
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, bi_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 import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_1[grid(64)](buf2,
primals_3, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return buf2, reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf3
class BertTextPoolerNew(nn.Module):
def __init__(self, config):
super(BertTextPoolerNew, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.bi_hidden_size)
self.activation = nn.ReLU()
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
eaidova/lxmert
|
BertTextPooler
| false
| 1,866
|
[
"MIT"
] | 0
|
c74616907125242112c6ee5c516b54c250168e8b
|
https://github.com/eaidova/lxmert/tree/c74616907125242112c6ee5c516b54c250168e8b
|
HeatmapLoss
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.nn.parallel
import torch.optim
import torch.utils.data.distributed
import torch.multiprocessing
class HeatmapLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, pred, gt, mask):
assert pred.size() == gt.size()
loss = (pred - gt) ** 2 * mask
loss = loss.mean(dim=3).mean(dim=2).mean(dim=1)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
import torch.nn.parallel
import torch.optim
import torch.utils.data.distributed
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mean_mul_pow_sub_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + 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')
tmp10 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
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'
)
tmp17 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
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'
)
tmp24 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp5 = tmp3 * tmp4
tmp8 = tmp6 - tmp7
tmp9 = tmp8 * tmp8
tmp11 = tmp9 * tmp10
tmp12 = tmp5 + tmp11
tmp15 = tmp13 - tmp14
tmp16 = tmp15 * tmp15
tmp18 = tmp16 * tmp17
tmp19 = tmp12 + tmp18
tmp22 = tmp20 - tmp21
tmp23 = tmp22 * tmp22
tmp25 = tmp23 * tmp24
tmp26 = tmp19 + tmp25
tmp27 = 4.0
tmp28 = tmp26 / tmp27
tl.store(out_ptr0 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_mean_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp10 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp28 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp30 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp32 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp11 = tmp9 + tmp10
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp16 = tmp15 / tmp7
tmp17 = tmp8 + tmp16
tmp20 = tmp18 + tmp19
tmp22 = tmp20 + tmp21
tmp24 = tmp22 + tmp23
tmp25 = tmp24 / tmp7
tmp26 = tmp17 + tmp25
tmp29 = tmp27 + tmp28
tmp31 = tmp29 + tmp30
tmp33 = tmp31 + tmp32
tmp34 = tmp33 / tmp7
tmp35 = tmp26 + tmp34
tmp36 = tmp35 / tmp7
tl.store(out_ptr0 + x0, tmp36, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_mul_pow_sub_0[grid(64)](arg0_1, arg1_1,
arg2_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mean_1[grid(4)](buf0, buf1, 4, XBLOCK=4, num_warps
=1, num_stages=1)
del buf0
return buf1,
class HeatmapLossNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0, input_1, input_2):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
output = call([arg0_1, arg1_1, arg2_1])
return output[0]
|
ducongju/Scale-sensitive-Heatmap
|
HeatmapLoss
| false
| 1,867
|
[
"MIT"
] | 0
|
4016610ba96a6a6645895bbf4bcdb3ff4690a2d8
|
https://github.com/ducongju/Scale-sensitive-Heatmap/tree/4016610ba96a6a6645895bbf4bcdb3ff4690a2d8
|
FocalL2Loss
|
import torch
import torch.nn as nn
import torch.utils.data
import torch.nn.parallel
import torch.optim
import torch.utils.data.distributed
import torch.multiprocessing
class FocalL2Loss(nn.Module):
"""
Compute focal l2 loss between predict and groundtruth
:param thre: the threshold to distinguish between the foreground
heatmap pixels and the background heatmap pixels
:param alpha beta: compensation factors to reduce the punishment of easy
samples (both easy foreground pixels and easy background pixels)
"""
def __init__(self, thre=0.01, alpha=0.1, beta=0.02):
super().__init__()
self.thre = thre
self.alpha = alpha
self.beta = beta
def forward(self, pred, gt, mask):
assert pred.size() == gt.size()
st = torch.where(torch.ge(gt, self.thre), pred - self.alpha, 1 -
pred - self.beta)
factor = torch.abs(1.0 - st)
loss = (pred - gt) ** 2 * factor * mask
loss = loss.mean(dim=3).mean(dim=2).mean(dim=1)
return loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
import torch.utils.data
import torch.nn.parallel
import torch.optim
import torch.utils.data.distributed
import torch.multiprocessing
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_abs_ge_mean_mul_pow_rsub_sub_where_0(in_ptr0, in_ptr1,
in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp30 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp33 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp34 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp45 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp48 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp49 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp60 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = 0.01
tmp5 = tmp1 >= tmp4
tmp6 = 0.1
tmp7 = tmp0 - tmp6
tmp8 = 1.0
tmp9 = tmp8 - tmp0
tmp10 = 0.02
tmp11 = tmp9 - tmp10
tmp12 = tl.where(tmp5, tmp7, tmp11)
tmp13 = tmp8 - tmp12
tmp14 = tl_math.abs(tmp13)
tmp15 = tmp3 * tmp14
tmp17 = tmp15 * tmp16
tmp20 = tmp18 - tmp19
tmp21 = tmp20 * tmp20
tmp22 = tmp19 >= tmp4
tmp23 = tmp18 - tmp6
tmp24 = tmp8 - tmp18
tmp25 = tmp24 - tmp10
tmp26 = tl.where(tmp22, tmp23, tmp25)
tmp27 = tmp8 - tmp26
tmp28 = tl_math.abs(tmp27)
tmp29 = tmp21 * tmp28
tmp31 = tmp29 * tmp30
tmp32 = tmp17 + tmp31
tmp35 = tmp33 - tmp34
tmp36 = tmp35 * tmp35
tmp37 = tmp34 >= tmp4
tmp38 = tmp33 - tmp6
tmp39 = tmp8 - tmp33
tmp40 = tmp39 - tmp10
tmp41 = tl.where(tmp37, tmp38, tmp40)
tmp42 = tmp8 - tmp41
tmp43 = tl_math.abs(tmp42)
tmp44 = tmp36 * tmp43
tmp46 = tmp44 * tmp45
tmp47 = tmp32 + tmp46
tmp50 = tmp48 - tmp49
tmp51 = tmp50 * tmp50
tmp52 = tmp49 >= tmp4
tmp53 = tmp48 - tmp6
tmp54 = tmp8 - tmp48
tmp55 = tmp54 - tmp10
tmp56 = tl.where(tmp52, tmp53, tmp55)
tmp57 = tmp8 - tmp56
tmp58 = tl_math.abs(tmp57)
tmp59 = tmp51 * tmp58
tmp61 = tmp59 * tmp60
tmp62 = tmp47 + tmp61
tmp63 = 4.0
tmp64 = tmp62 / tmp63
tl.store(out_ptr0 + x0, tmp64, xmask)
@triton.jit
def triton_poi_fused_mean_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last'
)
tmp10 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp19 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp28 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp30 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp32 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp11 = tmp9 + tmp10
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp16 = tmp15 / tmp7
tmp17 = tmp8 + tmp16
tmp20 = tmp18 + tmp19
tmp22 = tmp20 + tmp21
tmp24 = tmp22 + tmp23
tmp25 = tmp24 / tmp7
tmp26 = tmp17 + tmp25
tmp29 = tmp27 + tmp28
tmp31 = tmp29 + tmp30
tmp33 = tmp31 + tmp32
tmp34 = tmp33 / tmp7
tmp35 = tmp26 + tmp34
tmp36 = tmp35 / tmp7
tl.store(out_ptr0 + x0, tmp36, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_abs_ge_mean_mul_pow_rsub_sub_where_0[grid(64)](arg0_1,
arg1_1, arg2_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del arg2_1
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_poi_fused_mean_1[grid(4)](buf0, buf1, 4, XBLOCK=4, num_warps
=1, num_stages=1)
del buf0
return buf1,
class FocalL2LossNew(nn.Module):
"""
Compute focal l2 loss between predict and groundtruth
:param thre: the threshold to distinguish between the foreground
heatmap pixels and the background heatmap pixels
:param alpha beta: compensation factors to reduce the punishment of easy
samples (both easy foreground pixels and easy background pixels)
"""
def __init__(self, thre=0.01, alpha=0.1, beta=0.02):
super().__init__()
self.thre = thre
self.alpha = alpha
self.beta = beta
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]
|
ducongju/Scale-sensitive-Heatmap
|
FocalL2Loss
| false
| 1,868
|
[
"MIT"
] | 0
|
4016610ba96a6a6645895bbf4bcdb3ff4690a2d8
|
https://github.com/ducongju/Scale-sensitive-Heatmap/tree/4016610ba96a6a6645895bbf4bcdb3ff4690a2d8
|
PermEqui2_mean
|
import torch
from torch import nn
class PermEqui2_mean(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.Gamma = nn.Linear(in_dim, out_dim)
self.Lambda = nn.Linear(in_dim, out_dim, bias=False)
self.weight = self.Gamma.weight
self.bias = self.Gamma.bias
def forward(self, x):
xm = x.mean(0, keepdim=True)
xm = self.Lambda(xm)
x = self.Gamma(x)
x = x - xm
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4, 'out_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_mean_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0), xmask)
tmp3 = tl.load(in_ptr0 + (128 + x0), xmask)
tmp5 = tl.load(in_ptr0 + (192 + x0), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
@triton.jit
def triton_poi_fused_sub_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 4
x4 = xindex % 64
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 - tmp3
tl.store(in_out_ptr0 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mean_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf2)
del primals_3
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
triton_poi_fused_sub_1[grid(256)](buf3, primals_4, buf1, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_4
return buf3, reinterpret_tensor(buf0, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0)
class PermEqui2_meanNew(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.Gamma = nn.Linear(in_dim, out_dim)
self.Lambda = nn.Linear(in_dim, out_dim, bias=False)
self.weight = self.Gamma.weight
self.bias = self.Gamma.bias
def forward(self, input_0):
primals_2 = self.weight
primals_4 = self.bias
primals_3 = self.Lambda.weight
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
dvirsamuel/CrowdDet
|
PermEqui2_mean
| false
| 1,869
|
[
"MIT"
] | 0
|
db729bf71c0ca72229e5d446019769e095fdaa79
|
https://github.com/dvirsamuel/CrowdDet/tree/db729bf71c0ca72229e5d446019769e095fdaa79
|
CNN
|
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.nn.functional as F
class CNN(nn.Module):
"""Convolutional Neural Network"""
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 8, 4)
self.conv2 = nn.Conv2d(16, 32, 4, 4)
self.fc1 = nn.Linear(32 * 4 * 4, 256)
self.fc2 = nn.Linear(256, 4)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = x.view(-1, 32 * 4 * 4)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
def get_inputs():
return [torch.rand([4, 1, 48, 48])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.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_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 7744
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 121 % 16
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_1(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 32
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x0, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (16, 1, 8, 8), (64, 64, 8, 1))
assert_size_stride(primals_2, (16,), (1,))
assert_size_stride(primals_3, (4, 1, 48, 48), (2304, 2304, 48, 1))
assert_size_stride(primals_4, (32, 16, 4, 4), (256, 16, 4, 1))
assert_size_stride(primals_5, (32,), (1,))
assert_size_stride(primals_6, (256, 512), (512, 1))
assert_size_stride(primals_7, (256,), (1,))
assert_size_stride(primals_8, (4, 256), (256, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(4,
4), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 16, 11, 11), (1936, 121, 11, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(7744)](buf1, primals_2,
7744, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(4, 4),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 32, 2, 2), (128, 4, 2, 1))
buf3 = buf2
del buf2
buf7 = empty_strided_cuda((4, 32, 2, 2), (128, 4, 2, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_1[grid(512)](buf3,
primals_5, buf7, 512, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((1, 256), (256, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (1, 512), (0, 1), 0),
reinterpret_tensor(primals_6, (512, 256), (1, 512), 0), out=buf4)
buf5 = buf4
del buf4
triton_poi_fused_relu_2[grid(256)](buf5, primals_7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((1, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_9, buf5, reinterpret_tensor(primals_8,
(256, 4), (1, 256), 0), alpha=1, beta=1, out=buf6)
del primals_9
return buf6, primals_1, primals_3, primals_4, buf1, reinterpret_tensor(buf3
, (1, 512), (512, 1), 0), buf5, primals_8, primals_6, buf7
class CNNNew(nn.Module):
"""Convolutional Neural Network"""
def __init__(self):
super(CNNNew, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 8, 4)
self.conv2 = nn.Conv2d(16, 32, 4, 4)
self.fc1 = nn.Linear(32 * 4 * 4, 256)
self.fc2 = nn.Linear(256, 4)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
dziganto/DQN
|
CNN
| false
| 1,870
|
[
"MIT"
] | 0
|
033de76a2295ddc5d9775cfd2612a9d79634547e
|
https://github.com/dziganto/DQN/tree/033de76a2295ddc5d9775cfd2612a9d79634547e
|
Wav2Vec2ClassificationHead
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class Wav2Vec2ClassificationHead(nn.Module):
"""Head for wav2vec classification task."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.final_dropout)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, features, **kwargs):
x = features
x = self.dropout(x)
x = self.dense(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, final_dropout=0.5,
num_labels=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((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 = 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_3, 256, 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, 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_1, (64, 4), (4, 1), 0), buf1, primals_4
class Wav2Vec2ClassificationHeadNew(nn.Module):
"""Head for wav2vec classification task."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.final_dropout)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_4 = self.out_proj.weight
primals_5 = self.out_proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
Ayushk4/MedImaging
|
Wav2Vec2ClassificationHead
| false
| 1,871
|
[
"MIT"
] | 0
|
dbc8968f076385be0c8db42210817ae0940fa26a
|
https://github.com/Ayushk4/MedImaging/tree/dbc8968f076385be0c8db42210817ae0940fa26a
|
TransposeMultiheadAttention
|
import torch
import torch.nn as nn
import torch.utils.data
from typing import Optional
import torch.nn
class TransposeMultiheadAttention(nn.Module):
"""
Wrapper for nn.MultiheadAttention which first transposes the input tensor
from (batch_size, seq_len, feature_dim) to (seq_length, batch_size, feature_dim),
then applies the attention and transposes the attention outputs back to the input
shape.
"""
def __init__(self, feature_dim: 'int', num_heads: 'int'=1):
"""
Args:
feature_dim (int): attention embedding dimension
num_heads (int): number of attention heads
"""
super().__init__()
self._attention = nn.MultiheadAttention(embed_dim=feature_dim,
num_heads=num_heads)
self._attention_weights = None
@property
def attention_weights(self) ->Optional[torch.Tensor]:
"""
Contains attention weights from last forward call.
"""
return self._attention_weights
def forward(self, x: 'torch.Tensor', mask: 'Optional[torch.Tensor]'=None
) ->torch.Tensor:
"""
Args:
x (torch.Tensor): tensor of shape (batch_size, seq_len, feature_dim)
mask (torch.Tensor): bool tensor with shape (batch_size, seq_len).
Sequence elements that are False are invalid.
Returns:
Tensor with shape (batch_size, seq_len, feature_dim)
"""
assert x.dim(
) == 3, 'Requires x shape (batch_size x seq_len x feature_dim)'
if mask is not None:
mask[:, 0] = True
mask = ~mask
x = x.transpose(0, 1)
attn_output, self._attention_weights = self._attention(x, x, x,
key_padding_mask=mask)
attn_output = attn_output.transpose(0, 1)
return attn_output
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'feature_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
import torch.utils.data
from typing import Optional
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_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1), xmask)
tl.store(out_ptr0 + x3, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 16
x2 = xindex // 64
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 12 * x1), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, 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
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_mean_4(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)
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
tmp9 = 1.0
tmp10 = tmp8 / tmp9
tl.store(out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr1 + x2, tmp10, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (12,), (1,))
assert_size_stride(primals_3, (12, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 12), (12, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 12), (1, 4), 0), out=buf1)
del primals_3
buf2 = empty_strided_cuda((3, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(192)](buf1, primals_2, buf2, 192,
XBLOCK=256, num_warps=4, num_stages=1)
del buf1
del primals_2
buf3 = empty_strided_cuda((4, 4, 4), (4, 16, 1), torch.float32)
triton_poi_fused_mul_2[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf2, (4, 4, 4), (4, 1,
16), 64), out=buf4)
buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_3[grid(64)](buf4, buf5, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf6 = buf4
del buf4
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_mean_4[grid(64)](buf5, buf6, buf10, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf7 = buf5
del buf5
extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 4), (4, 16,
1), 128), out=buf7)
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(64)](buf7, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_5, reinterpret_tensor(buf8, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf9)
del primals_5
return reinterpret_tensor(buf9, (4, 4, 4), (4, 16, 1), 0
), buf10, reinterpret_tensor(buf0, (16, 4), (4, 1), 0
), buf6, reinterpret_tensor(buf8, (16, 4), (4, 1), 0
), primals_4, reinterpret_tensor(buf2, (4, 4, 4), (4, 1, 16), 128
), reinterpret_tensor(buf3, (4, 4, 4), (4, 1, 16), 0
), reinterpret_tensor(buf2, (4, 4, 4), (4, 16, 1), 64)
class TransposeMultiheadAttentionNew(nn.Module):
"""
Wrapper for nn.MultiheadAttention which first transposes the input tensor
from (batch_size, seq_len, feature_dim) to (seq_length, batch_size, feature_dim),
then applies the attention and transposes the attention outputs back to the input
shape.
"""
def __init__(self, feature_dim: 'int', num_heads: 'int'=1):
"""
Args:
feature_dim (int): attention embedding dimension
num_heads (int): number of attention heads
"""
super().__init__()
self._attention = nn.MultiheadAttention(embed_dim=feature_dim,
num_heads=num_heads)
self._attention_weights = None
@property
def attention_weights(self) ->Optional[torch.Tensor]:
"""
Contains attention weights from last forward call.
"""
return self._attention_weights
def forward(self, input_0):
primals_3 = self._attention.in_proj_weight
primals_2 = self._attention.in_proj_bias
primals_4 = self._attention.out_proj.weight
primals_5 = self._attention.out_proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
denred0/pytorchvideo
|
TransposeMultiheadAttention
| false
| 1,872
|
[
"Apache-2.0"
] | 0
|
d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
https://github.com/denred0/pytorchvideo/tree/d874bfc9969895d2afcedea2e12bae5e1bcfb809
|
SynthWide256
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SynthWide256(nn.Module):
def __init__(self, num_c=10, f=1):
super(SynthWide256, self).__init__()
self.pool = nn.MaxPool2d(2, 2)
self.conv1 = nn.Conv2d(3, 32 * f, 3, padding=1)
self.conv2 = nn.Conv2d(32 * f, 64 * f, 3, padding=1)
self.conv3 = nn.Conv2d(64 * f, 128 * f, 3, padding=1)
self.conv4 = nn.Conv2d(128 * f, 256 * f, 3, padding=1)
self.conv5 = nn.Conv2d(256 * f, 512 * f, 3, padding=1)
self.conv6 = nn.Conv2d(512 * f, 1024 * f, 3, padding=1)
self.conv7 = nn.Conv2d(1024 * f, 256, 3, padding=1)
self.fc1 = nn.Linear(256 * 4 * 4, num_c)
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 = self.pool(F.relu(self.conv5(x)))
x = self.pool(F.relu(self.conv6(x)))
x = self.pool(F.relu(self.conv7(x)))
x = x.view(-1, 256 * 4 * 4)
x = self.fc1(x)
return x
def get_inputs():
return [torch.rand([4, 3, 256, 256])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 65536 % 32
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 128
x1 = xindex // 128
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 512 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 512 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (256 + 2 * x0 + 512 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (257 + 2 * x0 + 512 * x1), None,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16384 % 64
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, 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
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 256 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 256 * x1), None, eviction_policy
='evict_last')
tmp3 = tl.load(in_ptr0 + (128 + 2 * x0 + 256 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (129 + 2 * x0 + 256 * x1), None,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_5(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_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)
x3 = xindex
x1 = xindex // 1024 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_7(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 16
x1 = xindex // 16
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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_8(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 256 % 512
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_9(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 % 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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_10(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 1024
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_11(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 % 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 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x2, tmp6, None)
tl.store(out_ptr1 + x2, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_12(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 256
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_13(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 % 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')
tmp7 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), None, eviction_policy=
'evict_last')
tmp12 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), None, eviction_policy=
'evict_last')
tmp2 = tmp1 > tmp0
tmp3 = tl.full([1], 1, tl.int8)
tmp4 = tl.full([1], 0, tl.int8)
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = triton_helpers.maximum(tmp1, tmp0)
tmp8 = tmp7 > tmp6
tmp9 = tl.full([1], 2, tl.int8)
tmp10 = tl.where(tmp8, tmp9, tmp5)
tmp11 = triton_helpers.maximum(tmp7, tmp6)
tmp13 = tmp12 > tmp11
tmp14 = tl.full([1], 3, tl.int8)
tmp15 = tl.where(tmp13, tmp14, tmp10)
tmp16 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + x2, tmp15, None)
tl.store(out_ptr1 + x2, tmp16, None)
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, (32, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (32,), (1,))
assert_size_stride(primals_3, (4, 3, 256, 256), (196608, 65536, 256, 1))
assert_size_stride(primals_4, (64, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_9, (256,), (1,))
assert_size_stride(primals_10, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_11, (512,), (1,))
assert_size_stride(primals_12, (1024, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_13, (1024,), (1,))
assert_size_stride(primals_14, (256, 1024, 3, 3), (9216, 9, 3, 1))
assert_size_stride(primals_15, (256,), (1,))
assert_size_stride(primals_16, (10, 4096), (4096, 1))
assert_size_stride(primals_17, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 32, 256, 256), (2097152, 65536, 256, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(8388608)](buf1, primals_2,
8388608, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 32, 128, 128), (524288, 16384, 128, 1
), torch.float32)
buf3 = empty_strided_cuda((4, 32, 128, 128), (524288, 16384, 128, 1
), torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(2097152)](buf1,
buf2, buf3, 2097152, XBLOCK=512, num_warps=8, num_stages=1)
buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 64, 128, 128), (1048576, 16384, 128, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_2[grid(4194304)](buf5, primals_5,
4194304, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf6 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.float32)
buf7 = empty_strided_cuda((4, 64, 64, 64), (262144, 4096, 64, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(1048576)](buf5,
buf6, buf7, 1048576, XBLOCK=512, num_warps=8, num_stages=1)
buf8 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 128, 64, 64), (524288, 4096, 64, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_4[grid(2097152)](buf9, primals_7,
2097152, XBLOCK=512, num_warps=8, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 128, 32, 32), (131072, 1024, 32, 1),
torch.float32)
buf11 = empty_strided_cuda((4, 128, 32, 32), (131072, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_5[grid(524288)](buf9,
buf10, buf11, 524288, XBLOCK=512, num_warps=8, num_stages=1)
buf12 = extern_kernels.convolution(buf10, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 256, 32, 32), (262144, 1024, 32, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_6[grid(1048576)](buf13, primals_9,
1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf14 = empty_strided_cuda((4, 256, 16, 16), (65536, 256, 16, 1),
torch.float32)
buf15 = empty_strided_cuda((4, 256, 16, 16), (65536, 256, 16, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_7[grid(262144)](buf13,
buf14, buf15, 262144, XBLOCK=512, num_warps=8, num_stages=1)
buf16 = extern_kernels.convolution(buf14, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 512, 16, 16), (131072, 256, 16, 1))
buf17 = buf16
del buf16
triton_poi_fused_convolution_relu_8[grid(524288)](buf17, primals_11,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_11
buf18 = empty_strided_cuda((4, 512, 8, 8), (32768, 64, 8, 1), torch
.float32)
buf19 = empty_strided_cuda((4, 512, 8, 8), (32768, 64, 8, 1), torch
.int8)
triton_poi_fused_max_pool2d_with_indices_9[grid(131072)](buf17,
buf18, buf19, 131072, XBLOCK=512, num_warps=8, num_stages=1)
buf20 = extern_kernels.convolution(buf18, primals_12, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf20, (4, 1024, 8, 8), (65536, 64, 8, 1))
buf21 = buf20
del buf20
triton_poi_fused_convolution_relu_10[grid(262144)](buf21,
primals_13, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf22 = empty_strided_cuda((4, 1024, 4, 4), (16384, 16, 4, 1),
torch.float32)
buf23 = empty_strided_cuda((4, 1024, 4, 4), (16384, 16, 4, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_11[grid(65536)](buf21,
buf22, buf23, 65536, XBLOCK=256, num_warps=4, num_stages=1)
buf24 = extern_kernels.convolution(buf22, primals_14, 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, 4, 4), (4096, 16, 4, 1))
buf25 = buf24
del buf24
triton_poi_fused_convolution_relu_12[grid(16384)](buf25, primals_15,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_15
buf26 = empty_strided_cuda((4, 256, 2, 2), (1024, 4, 2, 1), torch.int8)
buf27 = empty_strided_cuda((4, 256, 2, 2), (1024, 4, 2, 1), torch.
float32)
triton_poi_fused_max_pool2d_with_indices_13[grid(4096)](buf25,
buf26, buf27, 4096, XBLOCK=256, num_warps=4, num_stages=1)
buf28 = empty_strided_cuda((1, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_17, reinterpret_tensor(buf27, (1, 4096
), (0, 1), 0), reinterpret_tensor(primals_16, (4096, 10), (1,
4096), 0), alpha=1, beta=1, out=buf28)
del primals_17
return (buf28, primals_1, primals_3, primals_4, primals_6, primals_8,
primals_10, primals_12, primals_14, buf1, buf2, buf3, buf5, buf6,
buf7, buf9, buf10, buf11, buf13, buf14, buf15, buf17, buf18, buf19,
buf21, buf22, buf23, buf25, buf26, reinterpret_tensor(buf27, (1,
4096), (4096, 1), 0), primals_16)
class SynthWide256New(nn.Module):
def __init__(self, num_c=10, f=1):
super(SynthWide256New, self).__init__()
self.pool = nn.MaxPool2d(2, 2)
self.conv1 = nn.Conv2d(3, 32 * f, 3, padding=1)
self.conv2 = nn.Conv2d(32 * f, 64 * f, 3, padding=1)
self.conv3 = nn.Conv2d(64 * f, 128 * f, 3, padding=1)
self.conv4 = nn.Conv2d(128 * f, 256 * f, 3, padding=1)
self.conv5 = nn.Conv2d(256 * f, 512 * f, 3, padding=1)
self.conv6 = nn.Conv2d(512 * f, 1024 * f, 3, padding=1)
self.conv7 = nn.Conv2d(1024 * f, 256, 3, padding=1)
self.fc1 = nn.Linear(256 * 4 * 4, num_c)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_8 = self.conv4.weight
primals_9 = self.conv4.bias
primals_10 = self.conv5.weight
primals_11 = self.conv5.bias
primals_12 = self.conv6.weight
primals_13 = self.conv6.bias
primals_14 = self.conv7.weight
primals_15 = self.conv7.bias
primals_16 = self.fc1.weight
primals_17 = self.fc1.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]
|
dengliming/iotnets
|
SynthWide256
| false
| 1,873
|
[
"MIT"
] | 0
|
db744e56769c799dbf765a27fc5aa91e3edeaaa3
|
https://github.com/dengliming/iotnets/tree/db744e56769c799dbf765a27fc5aa91e3edeaaa3
|
CNNCifar
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn.functional as F
from torch import nn
class CNNCifar(nn.Module):
def __init__(self, args):
super(CNNCifar, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, args.num_classes)
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)
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, 32, 32])]
def get_init_inputs():
return [[], {'args': _mock_config(num_classes=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_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)
@triton.jit
def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 480
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 120
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 336
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 84
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (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,))
assert_size_stride(primals_6, (120, 400), (400, 1))
assert_size_stride(primals_7, (120,), (1,))
assert_size_stride(primals_8, (84, 120), (120, 1))
assert_size_stride(primals_9, (84,), (1,))
assert_size_stride(primals_10, (4, 84), (84, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(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=128, 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=128, 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=256, num_warps=4, num_stages=1)
buf8 = empty_strided_cuda((4, 120), (120, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (4, 400), (400, 1), 0),
reinterpret_tensor(primals_6, (400, 120), (1, 400), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(480)](buf9, primals_7, 480, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 84), (84, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_8, (120, 84), (1,
120), 0), out=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_5[grid(336)](buf11, primals_9, 336, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, buf11, reinterpret_tensor(
primals_10, (84, 4), (1, 84), 0), alpha=1, beta=1, out=buf12)
del primals_11
return (buf12, primals_1, primals_3, primals_4, buf1, buf2, buf3, buf5,
buf6, reinterpret_tensor(buf7, (4, 400), (400, 1), 0), buf9, buf11,
primals_10, primals_8, primals_6)
class CNNCifarNew(nn.Module):
def __init__(self, args):
super(CNNCifarNew, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, args.num_classes)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_10 = self.fc3.weight
primals_11 = self.fc3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
FANJIYU0825/federated-learning
|
CNNCifar
| false
| 1,874
|
[
"MIT"
] | 0
|
5772ca0a321a222eae5d5e29b70fb4a468c28374
|
https://github.com/FANJIYU0825/federated-learning/tree/5772ca0a321a222eae5d5e29b70fb4a468c28374
|
TransformerEncoderLayer
|
import math
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == 'relu':
return F.relu
if activation == 'gelu':
return F.gelu
if activation == 'glu':
return F.glu
raise RuntimeError(f'activation should be relu/gelu, not {activation}.')
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
no_norm=False, activation='relu'):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=
dropout, bias=False)
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) if not no_norm else nn.Identity()
self.norm2 = nn.LayerNorm(d_model) if not no_norm else nn.Identity()
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
nn.init.kaiming_uniform_(self.self_attn.in_proj_weight, a=math.sqrt(5))
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, src, pos=None):
src2 = self.norm1(src)
q = k = self.with_pos_embed(src2, pos)
src2 = self.self_attn(q, k, src2)
src = src + self.dropout1(src2[0])
src2 = self.norm2(src)
src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
src = src + self.dropout2(src2)
return src
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'nhead': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import math
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo
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 = 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_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, 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
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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_5(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_6(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_7(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_8(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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_9(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp3 = tl.load(in_out_ptr0 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (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, (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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(4)](primals_3, buf0, buf1,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(16)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 16), out=buf4)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 32), out=buf5)
buf6 = reinterpret_tensor(buf3, (4, 4, 1), (1, 4, 16), 0)
del buf3
triton_poi_fused_mul_2[grid(16)](buf6, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf4, (4, 1, 4), (1, 1,
4), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_3[grid(64)](buf7, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused__softmax_4[grid(64)](buf8, buf9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf8
buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf9, reinterpret_tensor(buf5, (4, 4, 1), (1, 4,
1), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_5[grid(4, 4)](buf10, buf11, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (4, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf11, (4, 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_6[grid(4)](primals_3, buf12,
buf13, buf14, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_7[grid(16)](primals_3, buf12,
buf13, buf14, primals_6, primals_7, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf13
del buf14
del primals_7
buf16 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32)
extern_kernels.mm(buf15, reinterpret_tensor(primals_8, (4, 2048), (
1, 4), 0), out=buf16)
buf17 = buf16
del buf16
triton_poi_fused_relu_8[grid(8192)](buf17, primals_9, 8192, XBLOCK=
256, num_warps=4, num_stages=1)
del primals_9
buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf17, reinterpret_tensor(primals_10, (2048, 4),
(1, 2048), 0), out=buf18)
buf19 = buf18
del buf18
triton_poi_fused_add_9[grid(16)](buf19, primals_3, buf12,
primals_11, 16, XBLOCK=16, num_warps=1, num_stages=1)
del primals_11
return (buf19, primals_3, primals_6, buf2, buf9, reinterpret_tensor(
buf11, (4, 4), (4, 1), 0), buf12, buf15, buf17, primals_10,
primals_8, primals_5, reinterpret_tensor(buf5, (4, 1, 4), (1, 1, 4),
0), reinterpret_tensor(buf6, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf4, (4, 4, 1), (1, 4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 16),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 0))
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == 'relu':
return F.relu
if activation == 'gelu':
return F.gelu
if activation == 'glu':
return F.glu
raise RuntimeError(f'activation should be relu/gelu, not {activation}.')
class TransformerEncoderLayerNew(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
no_norm=False, activation='relu'):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=
dropout, bias=False)
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) if not no_norm else nn.Identity()
self.norm2 = nn.LayerNorm(d_model) if not no_norm else nn.Identity()
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
nn.init.kaiming_uniform_(self.self_attn.in_proj_weight, a=math.sqrt(5))
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, input_0):
primals_4 = self.self_attn.in_proj_weight
primals_3 = self.self_attn.out_proj.weight
primals_8 = self.linear1.weight
primals_9 = self.linear1.bias
primals_10 = self.linear2.weight
primals_1 = self.linear2.bias
primals_2 = self.norm1.weight
primals_6 = self.norm1.bias
primals_7 = self.norm2.weight
primals_11 = 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])
return output[0]
|
dongyan007/Pretrained-IPT-main-master
|
TransformerEncoderLayer
| false
| 1,875
|
[
"Apache-2.0"
] | 0
|
7ed47002373e11bd57b7904f6935acdfba1e44ff
|
https://github.com/dongyan007/Pretrained-IPT-main-master/tree/7ed47002373e11bd57b7904f6935acdfba1e44ff
|
BertOutput
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
import torch.onnx
class BertLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(BertLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class BertOutput(nn.Module):
def __init__(self, config):
super(BertOutput, self).__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(intermediate_size=4, hidden_size=4,
layer_norm_eps=1, hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
import torch.onnx
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_mean_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp4 = tl.load(in_ptr2 + 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)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp10 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr1 + 2)
tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
tmp17 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr1 + 3)
tmp22 = tl.broadcast_to(tmp21, [XBLOCK])
tmp24 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = tmp0 + tmp2
tmp5 = tmp3 + tmp4
tmp9 = tmp6 + tmp8
tmp11 = tmp9 + tmp10
tmp12 = tmp5 + tmp11
tmp16 = tmp13 + tmp15
tmp18 = tmp16 + tmp17
tmp19 = tmp12 + tmp18
tmp23 = tmp20 + tmp22
tmp25 = tmp23 + tmp24
tmp26 = tmp19 + tmp25
tmp27 = 4.0
tmp28 = tmp26 / tmp27
tl.store(out_ptr0 + x0, tmp28, xmask)
@triton.jit
def triton_poi_fused_add_sub_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
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
x1 = xindex // 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp5 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 - tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_pow_sqrt_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
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp2 * tmp2
tmp5 = tmp4 * tmp4
tmp6 = tmp3 + tmp5
tmp8 = tmp7 * tmp7
tmp9 = tmp6 + tmp8
tmp11 = tmp10 * tmp10
tmp12 = tmp9 + tmp11
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = 1.0
tmp16 = tmp14 + tmp15
tmp17 = libdevice.sqrt(tmp16)
tmp18 = tmp1 / tmp17
tmp19 = tmp0 * tmp18
tmp21 = tmp19 + tmp20
tl.store(out_ptr0 + x2, tmp21, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mean_0[grid(64)](buf0, primals_2, primals_4,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_add_sub_1[grid(256)](buf2, primals_2, primals_4,
buf1, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_2
del primals_4
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_pow_sqrt_2[grid(256)](primals_5,
buf2, primals_6, buf3, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_6
return buf3, primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf2
class BertLayerNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(BertLayerNorm, self).__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.bias = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = eps
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.weight * x + self.bias
class BertOutputNew(nn.Module):
def __init__(self, config):
super(BertOutputNew, self).__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_0, input_1):
primals_1 = self.dense.weight
primals_2 = self.dense.bias
primals_5 = self.LayerNorm.weight
primals_6 = self.LayerNorm.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
Alwaysproblem/examples-1
|
BertOutput
| false
| 1,876
|
[
"MIT"
] | 0
|
9754fa63ed1931489a21ac1f5b299f945e369a5c
|
https://github.com/Alwaysproblem/examples-1/tree/9754fa63ed1931489a21ac1f5b299f945e369a5c
|
L1DistanceLoss
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class L1DistanceLoss(nn.Module):
"""Custom L1 loss for distance matrices."""
def __init__(self, args):
super(L1DistanceLoss, self).__init__()
self.args = args
self.word_pair_dims = 1, 2
def forward(self, predictions, label_batch, length_batch):
""" Computes L1 loss on distance matrices.
Ignores all entries where label_batch=-1
Normalizes first within sentences (by dividing by the square of the sentence length)
and then across the batch.
Args:
predictions: A pytorch batch of predicted distances
label_batch: A pytorch batch of true distances
length_batch: A pytorch batch of sentence lengths
Returns:
A tuple of:
batch_loss: average loss in the batch
total_sents: number of sentences in the batch
"""
labels_1s = (label_batch != -1).float()
predictions_masked = predictions * labels_1s
labels_masked = label_batch * labels_1s
total_sents = torch.sum(length_batch != 0).float()
squared_lengths = length_batch.pow(2).float()
if total_sents > 0:
loss_per_sent = torch.sum(torch.abs(predictions_masked -
labels_masked), dim=self.word_pair_dims)
normalized_loss_per_sent = loss_per_sent / squared_lengths
batch_loss = torch.sum(normalized_loss_per_sent) / total_sents
else:
batch_loss = torch.tensor(0.0, device=self.args['device'])
return batch_loss, total_sents
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 [[], {'args': _mock_config()}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused__to_copy_gt_ne_pow_sum_0(in_ptr0, out_ptr0, out_ptr2,
out_ptr3, 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 = tmp0 * tmp0
tmp2 = 0.0
tmp3 = tmp0 != tmp2
tmp4 = tmp3.to(tl.int64)
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = tmp7.to(tl.float32)
tmp9 = tmp8 > tmp2
tl.store(out_ptr0 + tl.broadcast_to(r0, [RBLOCK]), tmp1, None)
tl.store(out_ptr2 + tl.full([1], 0, tl.int32), tmp8, None)
tl.store(out_ptr3 + tl.full([1], 0, tl.int32), tmp9, None)
@triton.jit
def triton_poi_fused__to_copy_mul_ne_1(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)
tmp5 = tl.load(in_ptr1 + x0, xmask)
tmp1 = -1.0
tmp2 = tmp0 != tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tmp0 * tmp3
tmp6 = tmp5 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr1 + x0, tmp6, 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)
buf4 = empty_strided_cuda((), (), torch.float32)
buf5 = empty_strided_cuda((), (), torch.bool)
get_raw_stream(0)
triton_per_fused__to_copy_gt_ne_pow_sum_0[grid(1)](arg2_1, buf0,
buf4, buf5, 1, 256, num_warps=2, num_stages=1)
del arg2_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__to_copy_mul_ne_1[grid(256)](arg0_1, arg1_1, buf1,
buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0, buf4, buf1, buf2, buf5
class L1DistanceLossNew(nn.Module):
"""Custom L1 loss for distance matrices."""
def __init__(self, args):
super(L1DistanceLossNew, self).__init__()
self.args = args
self.word_pair_dims = 1, 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]
|
AnReu/structural-probes
|
L1DistanceLoss
| false
| 1,877
|
[
"Apache-2.0"
] | 0
|
fdc99dc124fa6df3dbdd5ba48a90f08bb6bf37b7
|
https://github.com/AnReu/structural-probes/tree/fdc99dc124fa6df3dbdd5ba48a90f08bb6bf37b7
|
MultiHeadAttention
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ScaledDotProductAttention(nn.Module):
def forward(self, query, key, value, mask=None):
dk = query.size()[-1]
scores = query.matmul(key.transpose(-2, -1)) / math.sqrt(dk)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1000000000.0)
attention = F.softmax(scores, dim=-1)
return attention.matmul(value)
class MultiHeadAttention(nn.Module):
def __init__(self, in_features, head_num, bias=True, activation=None):
super(MultiHeadAttention, self).__init__()
if in_features % head_num != 0:
raise ValueError(
'`in_features`({}) should be divisible by `head_num`({})'.
format(in_features, head_num))
self.in_features = in_features
self.head_num = head_num
self.activation = activation
self.bias = bias
self.linear_q = nn.Linear(in_features, in_features, bias)
self.linear_k = nn.Linear(in_features, in_features, bias)
self.linear_v = nn.Linear(in_features, in_features, bias)
self.linear_o = nn.Linear(in_features, in_features // self.head_num,
bias)
def forward(self, q, k, v, mask=None):
q, k, v = self.linear_q(q), self.linear_k(k), self.linear_v(v)
if self.activation is not None:
q = self.activation(q)
k = self.activation(k)
v = self.activation(v)
q = self._reshape_to_batches(q)
k = self._reshape_to_batches(k)
v = self._reshape_to_batches(v)
if mask is not None:
mask = mask.repeat(self.head_num, 1, 1)
y = ScaledDotProductAttention()(q, k, v, mask)
y = self._reshape_from_batches(y)
y = self.linear_o(y)
if self.activation is not None:
y = self.activation(y)
return y
@staticmethod
def gen_history_mask(x):
"""Generate the mask that only uses history data.
:param x: Input tensor.
:return: The mask.
"""
batch_size, seq_len, _ = x.size()
return torch.tril(torch.ones(seq_len, seq_len)).view(1, seq_len,
seq_len).repeat(batch_size, 1, 1)
def _reshape_to_batches(self, x):
batch_size, seq_len, in_feature = x.size()
sub_dim = in_feature // self.head_num
return x.reshape(batch_size, seq_len, self.head_num, sub_dim).permute(
0, 2, 1, 3).reshape(batch_size * self.head_num, seq_len, sub_dim)
def _reshape_from_batches(self, x):
batch_size, seq_len, in_feature = x.size()
batch_size //= self.head_num
out_dim = in_feature * self.head_num
return x.reshape(batch_size, self.head_num, seq_len, in_feature
).permute(0, 2, 1, 3).reshape(batch_size, seq_len, out_dim)
def extra_repr(self):
return 'in_features={}, head_num={}, bias={}, activation={}'.format(
self.in_features, self.head_num, self.bias, self.activation)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'in_features': 4, 'head_num': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime 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_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 = 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_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
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_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr0 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 + tmp2
tl.store(in_out_ptr0 + x0, tmp3, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 4), (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), (16, 4, 1))
assert_size_stride(primals_10, (1, 4), (4, 1))
assert_size_stride(primals_11, (1,), (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_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (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_9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
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=4, 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((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_1[grid(256)](buf5, buf6, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused__softmax_2[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_clone_0[grid(16, 4)](buf2, primals_8, buf8, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(buf7, reinterpret_tensor(buf8, (16, 4, 1), (4, 1,
0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4), (16, 4, 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)
del buf9
buf11 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf10, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 1), (1, 4), 0), out=buf11)
buf12 = reinterpret_tensor(buf11, (4, 4, 1), (4, 1, 1), 0)
del buf11
triton_poi_fused_add_4[grid(16)](buf12, primals_11, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_11
return buf12, reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 4), (4, 1), 0
), primals_10, reinterpret_tensor(buf8, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf3, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf4, (16, 4, 1), (4, 1, 1), 0)
class ScaledDotProductAttention(nn.Module):
def forward(self, query, key, value, mask=None):
dk = query.size()[-1]
scores = query.matmul(key.transpose(-2, -1)) / math.sqrt(dk)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1000000000.0)
attention = F.softmax(scores, dim=-1)
return attention.matmul(value)
class MultiHeadAttentionNew(nn.Module):
def __init__(self, in_features, head_num, bias=True, activation=None):
super(MultiHeadAttentionNew, self).__init__()
if in_features % head_num != 0:
raise ValueError(
'`in_features`({}) should be divisible by `head_num`({})'.
format(in_features, head_num))
self.in_features = in_features
self.head_num = head_num
self.activation = activation
self.bias = bias
self.linear_q = nn.Linear(in_features, in_features, bias)
self.linear_k = nn.Linear(in_features, in_features, bias)
self.linear_v = nn.Linear(in_features, in_features, bias)
self.linear_o = nn.Linear(in_features, in_features // self.head_num,
bias)
@staticmethod
def gen_history_mask(x):
"""Generate the mask that only uses history data.
:param x: Input tensor.
:return: The mask.
"""
batch_size, seq_len, _ = x.size()
return torch.tril(torch.ones(seq_len, seq_len)).view(1, seq_len,
seq_len).repeat(batch_size, 1, 1)
def _reshape_to_batches(self, x):
batch_size, seq_len, in_feature = x.size()
sub_dim = in_feature // self.head_num
return x.reshape(batch_size, seq_len, self.head_num, sub_dim).permute(
0, 2, 1, 3).reshape(batch_size * self.head_num, seq_len, sub_dim)
def _reshape_from_batches(self, x):
batch_size, seq_len, in_feature = x.size()
batch_size //= self.head_num
out_dim = in_feature * self.head_num
return x.reshape(batch_size, self.head_num, seq_len, in_feature
).permute(0, 2, 1, 3).reshape(batch_size, seq_len, out_dim)
def extra_repr(self):
return 'in_features={}, head_num={}, bias={}, activation={}'.format(
self.in_features, self.head_num, self.bias, self.activation)
def forward(self, input_0, input_1, input_2):
primals_1 = self.linear_q.weight
primals_2 = self.linear_q.bias
primals_4 = self.linear_k.weight
primals_5 = self.linear_k.bias
primals_7 = self.linear_v.weight
primals_8 = self.linear_v.bias
primals_10 = self.linear_o.weight
primals_11 = self.linear_o.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,
primals_10, primals_11])
return output[0]
|
dukeNashor/CaptainStony
|
MultiHeadAttention
| false
| 1,878
|
[
"MIT"
] | 0
|
6320a27420e686666a4d7172437cf55fe42de2b6
|
https://github.com/dukeNashor/CaptainStony/tree/6320a27420e686666a4d7172437cf55fe42de2b6
|
CRF
|
import torch
from torch import nn
class CRF(nn.Module):
def __init__(self, num_nodes, iteration=10):
"""Initialize the CRF module
Args:
num_nodes: int, number of nodes/patches within the fully CRF
iteration: int, number of mean field iterations, e.g. 10
"""
super(CRF, self).__init__()
self.num_nodes = num_nodes
self.iteration = iteration
self.W = nn.Parameter(torch.zeros(1, num_nodes, num_nodes))
def forward(self, feats, logits):
"""Performing the CRF. Algorithm details is explained below:
Within the paper, I formulate the CRF distribution using negative
energy and cost, e.g. cosine distance, to derive pairwise potentials
following the convention in energy based models. But for implementation
simplicity, I use reward, e.g. cosine similarity to derive pairwise
potentials. So now, pairwise potentials would encourage high reward for
assigning (y_i, y_j) with the same label if (x_i, x_j) are similar, as
measured by cosine similarity, pairwise_sim. For
pairwise_potential_E = torch.sum(
probs * pairwise_potential - (1 - probs) * pairwise_potential,
dim=2, keepdim=True
)
This is taking the expectation of pairwise potentials using the current
marginal distribution of each patch being tumor, i.e. probs. There are
four cases to consider when taking the expectation between (i, j):
1. i=T,j=T; 2. i=N,j=T; 3. i=T,j=N; 4. i=N,j=N
probs is the marginal distribution of each i being tumor, therefore
logits > 0 means tumor and logits < 0 means normal. Given this, the
full expectation equation should be:
[probs * +pairwise_potential] + [(1 - probs) * +pairwise_potential] +
case 1 case 2
[probs * -pairwise_potential] + [(1 - probs) * -pairwise_potential]
case 3 case 4
positive sign rewards logits to be more tumor and negative sign rewards
logits to be more normal. But because of label compatibility, i.e. the
indicator function within equation 3 in the paper, case 2 and case 3
are dropped, which ends up being:
probs * pairwise_potential - (1 - probs) * pairwise_potential
In high level speaking, if (i, j) embedding are different, then
pairwise_potential, as computed as cosine similarity, would approach 0,
which then as no affect anyway. if (i, j) embedding are similar, then
pairwise_potential would be a positive reward. In this case,
if probs -> 1, then pairwise_potential promotes tumor probability;
if probs -> 0, then -pairwise_potential promotes normal probability.
Args:
feats: 3D tensor with the shape of
[batch_size, num_nodes, embedding_size], where num_nodes is the
number of patches within a grid, e.g. 9 for a 3x3 grid;
embedding_size is the size of extracted feature representation for
each patch from ResNet, e.g. 512
logits: 3D tensor with shape of [batch_size, num_nodes, 1], the
logit of each patch within the grid being tumor before CRF
Returns:
logits: 3D tensor with shape of [batch_size, num_nodes, 1], the
logit of each patch within the grid being tumor after CRF
"""
feats_norm = torch.norm(feats, p=2, dim=2, keepdim=True)
pairwise_norm = torch.bmm(feats_norm, torch.transpose(feats_norm, 1, 2)
)
pairwise_dot = torch.bmm(feats, torch.transpose(feats, 1, 2))
pairwise_sim = pairwise_dot / pairwise_norm
W_sym = (self.W + torch.transpose(self.W, 1, 2)) / 2
pairwise_potential = pairwise_sim * W_sym
unary_potential = logits.clone()
for i in range(self.iteration):
probs = torch.transpose(logits.sigmoid(), 1, 2)
pairwise_potential_E = torch.sum(probs * pairwise_potential - (
1 - probs) * pairwise_potential, dim=2, keepdim=True)
logits = unary_potential + pairwise_potential_E
return logits
def __repr__(self):
return 'CRF(num_nodes={}, iteration={})'.format(self.num_nodes,
self.iteration)
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'num_nodes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_linalg_vector_norm_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = libdevice.sqrt(tmp10)
tl.store(out_ptr0 + x0, tmp11, xmask)
@triton.jit
def triton_poi_fused_div_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_out_ptr0 + x0, xmask)
tmp2 = tmp0 / tmp1
tl.store(in_out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_rsub_sub_sum_2(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp2 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp16 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp17 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp30 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
tmp40 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp42 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp43 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp44 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp5 = tmp3 + tmp4
tmp6 = 0.5
tmp7 = tmp5 * tmp6
tmp8 = tmp2 * tmp7
tmp9 = tmp1 * tmp8
tmp10 = 1.0
tmp11 = tmp10 - tmp1
tmp12 = tmp11 * tmp8
tmp13 = tmp9 - tmp12
tmp15 = tl.sigmoid(tmp14)
tmp19 = tmp17 + tmp18
tmp20 = tmp19 * tmp6
tmp21 = tmp16 * tmp20
tmp22 = tmp15 * tmp21
tmp23 = tmp10 - tmp15
tmp24 = tmp23 * tmp21
tmp25 = tmp22 - tmp24
tmp26 = tmp13 + tmp25
tmp28 = tl.sigmoid(tmp27)
tmp32 = tmp30 + tmp31
tmp33 = tmp32 * tmp6
tmp34 = tmp29 * tmp33
tmp35 = tmp28 * tmp34
tmp36 = tmp10 - tmp28
tmp37 = tmp36 * tmp34
tmp38 = tmp35 - tmp37
tmp39 = tmp26 + tmp38
tmp41 = tl.sigmoid(tmp40)
tmp45 = tmp43 + tmp44
tmp46 = tmp45 * tmp6
tmp47 = tmp42 * tmp46
tmp48 = tmp41 * tmp47
tmp49 = tmp10 - tmp41
tmp50 = tmp49 * tmp47
tmp51 = tmp48 - tmp50
tmp52 = tmp39 + tmp51
tl.store(out_ptr0 + x2, tmp52, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_rsub_sub_sum_3(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
tmp1 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr2 + 4 * x2, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
tmp17 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp20 = tl.load(in_ptr2 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr3 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr3 + (4 + x0), xmask, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
tmp32 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp35 = tl.load(in_ptr2 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_ptr3 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp37 = tl.load(in_ptr3 + (8 + x0), xmask, eviction_policy='evict_last')
tmp46 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
tmp47 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp50 = tl.load(in_ptr2 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp51 = tl.load(in_ptr3 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp52 = tl.load(in_ptr3 + (12 + x0), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.sigmoid(tmp2)
tmp7 = tmp5 + tmp6
tmp8 = 0.5
tmp9 = tmp7 * tmp8
tmp10 = tmp4 * tmp9
tmp11 = tmp3 * tmp10
tmp12 = 1.0
tmp13 = tmp12 - tmp3
tmp14 = tmp13 * tmp10
tmp15 = tmp11 - tmp14
tmp18 = tmp16 + tmp17
tmp19 = tl.sigmoid(tmp18)
tmp23 = tmp21 + tmp22
tmp24 = tmp23 * tmp8
tmp25 = tmp20 * tmp24
tmp26 = tmp19 * tmp25
tmp27 = tmp12 - tmp19
tmp28 = tmp27 * tmp25
tmp29 = tmp26 - tmp28
tmp30 = tmp15 + tmp29
tmp33 = tmp31 + tmp32
tmp34 = tl.sigmoid(tmp33)
tmp38 = tmp36 + tmp37
tmp39 = tmp38 * tmp8
tmp40 = tmp35 * tmp39
tmp41 = tmp34 * tmp40
tmp42 = tmp12 - tmp34
tmp43 = tmp42 * tmp40
tmp44 = tmp41 - tmp43
tmp45 = tmp30 + tmp44
tmp48 = tmp46 + tmp47
tmp49 = tl.sigmoid(tmp48)
tmp53 = tmp51 + tmp52
tmp54 = tmp53 * tmp8
tmp55 = tmp50 * tmp54
tmp56 = tmp49 * tmp55
tmp57 = tmp12 - tmp49
tmp58 = tmp57 * tmp55
tmp59 = tmp56 - tmp58
tmp60 = tmp45 + tmp59
tl.store(out_ptr0 + x2, tmp60, xmask)
@triton.jit
def triton_poi_fused_add_4(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
get_raw_stream(0)
triton_poi_fused_linalg_vector_norm_0[grid(16)](primals_1, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf0, reinterpret_tensor(buf0, (4, 1, 4), (4, 16,
1), 0), out=buf1)
buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(primals_1, reinterpret_tensor(primals_1, (4, 4,
4), (16, 1, 4), 0), out=buf2)
del primals_1
buf3 = buf1
del buf1
triton_poi_fused_div_1[grid(64)](buf3, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = buf0
del buf0
triton_poi_fused_add_div_mul_rsub_sub_sum_2[grid(16)](primals_3,
buf3, primals_2, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf4, buf3, primals_2, buf5, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf6 = buf4
del buf4
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf5, buf3, primals_2, buf6, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf7 = buf5
del buf5
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf6, buf3, primals_2, buf7, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf8 = buf6
del buf6
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf7, buf3, primals_2, buf8, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf8, buf3, primals_2, buf9, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf10 = buf8
del buf8
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf9, buf3, primals_2, buf10, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf11 = buf9
del buf9
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf10, buf3, primals_2, buf11, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf12 = buf10
del buf10
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf11, buf3, primals_2, buf12, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf13 = buf11
del buf11
triton_poi_fused_add_div_mul_rsub_sub_sum_3[grid(16)](primals_3,
buf12, buf3, primals_2, buf13, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf12
buf14 = buf2
del buf2
triton_poi_fused_add_4[grid(64)](primals_3, buf13, buf14, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf13
return buf14, primals_2, primals_3, buf3
class CRFNew(nn.Module):
def __init__(self, num_nodes, iteration=10):
"""Initialize the CRF module
Args:
num_nodes: int, number of nodes/patches within the fully CRF
iteration: int, number of mean field iterations, e.g. 10
"""
super(CRFNew, self).__init__()
self.num_nodes = num_nodes
self.iteration = iteration
self.W = nn.Parameter(torch.zeros(1, num_nodes, num_nodes))
def __repr__(self):
return 'CRF(num_nodes={}, iteration={})'.format(self.num_nodes,
self.iteration)
def forward(self, input_0, input_1):
primals_2 = self.W
primals_1 = input_0
primals_3 = input_1
output = call([primals_1, primals_2, primals_3])
return output[0]
|
dradientgescent/NCRF
|
CRF
| false
| 1,879
|
[
"Apache-2.0"
] | 0
|
21e95c0e0f965de2b1daa2d446306052b3703b6a
|
https://github.com/dradientgescent/NCRF/tree/21e95c0e0f965de2b1daa2d446306052b3703b6a
|
L1DepthLoss
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
class L1DepthLoss(nn.Module):
"""Custom L1 loss for depth sequences."""
def __init__(self, args):
super(L1DepthLoss, self).__init__()
self.args = args
self.word_dim = 1
def forward(self, predictions, label_batch, length_batch):
""" Computes L1 loss on depth sequences.
Ignores all entries where label_batch=-1
Normalizes first within sentences (by dividing by the sentence length)
and then across the batch.
Args:
predictions: A pytorch batch of predicted depths
label_batch: A pytorch batch of true depths
length_batch: A pytorch batch of sentence lengths
Returns:
A tuple of:
batch_loss: average loss in the batch
total_sents: number of sentences in the batch
"""
total_sents = torch.sum(length_batch != 0).float()
labels_1s = (label_batch != -1).float()
predictions_masked = predictions * labels_1s
labels_masked = label_batch * labels_1s
if total_sents > 0:
loss_per_sent = torch.sum(torch.abs(predictions_masked -
labels_masked), dim=self.word_dim)
normalized_loss_per_sent = loss_per_sent / length_batch.float()
batch_loss = torch.sum(normalized_loss_per_sent) / total_sents
else:
batch_loss = torch.tensor(0.0, device=self.args['device'])
return batch_loss, total_sents
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 [[], {'args': _mock_config()}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__to_copy_mul_ne_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)
tmp5 = tl.load(in_ptr1 + x0, xmask)
tmp1 = -1.0
tmp2 = tmp0 != tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tmp0 * tmp3
tmp6 = tmp5 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr1 + x0, tmp6, xmask)
@triton.jit
def triton_per_fused__to_copy_gt_ne_sum_1(in_ptr0, out_ptr1, out_ptr2,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = 0.0
tmp2 = tmp0 != tmp1
tmp3 = tmp2.to(tl.int64)
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp7 > tmp1
tl.store(out_ptr1 + tl.full([1], 0, tl.int32), tmp7, None)
tl.store(out_ptr2 + tl.full([1], 0, tl.int32), tmp8, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__to_copy_mul_ne_0[grid(256)](arg1_1, arg2_1, buf0,
buf1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg1_1
del arg2_1
buf3 = empty_strided_cuda((), (), torch.float32)
buf4 = empty_strided_cuda((), (), torch.bool)
triton_per_fused__to_copy_gt_ne_sum_1[grid(1)](arg0_1, buf3, buf4,
1, 256, num_warps=2, num_stages=1)
del arg0_1
return buf0, buf1, buf3, buf4
class L1DepthLossNew(nn.Module):
"""Custom L1 loss for depth sequences."""
def __init__(self, args):
super(L1DepthLossNew, self).__init__()
self.args = args
self.word_dim = 1
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]
|
AnReu/structural-probes
|
L1DepthLoss
| false
| 1,880
|
[
"Apache-2.0"
] | 0
|
fdc99dc124fa6df3dbdd5ba48a90f08bb6bf37b7
|
https://github.com/AnReu/structural-probes/tree/fdc99dc124fa6df3dbdd5ba48a90f08bb6bf37b7
|
CriticNetwork
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch as T
class CriticNetwork(nn.Module):
def __init__(self, beta, input_dims, fc1_dims, fc2_dims, n_actions, name):
super(CriticNetwork, self).__init__()
self.input_dims = input_dims
self.fc1_dims = fc1_dims
self.fc2_dims = fc2_dims
self.n_actions = n_actions
self.name = name
self.fc1 = nn.Linear(self.input_dims, self.fc1_dims)
self.fc2 = nn.Linear(self.fc1_dims, self.fc2_dims)
self.action_value = nn.Linear(self.n_actions, self.fc1_dims)
self.action_value2 = nn.Linear(self.fc1_dims, self.fc2_dims)
self.q = nn.Linear(self.fc2_dims, 1)
f1 = 1.0 / np.sqrt(self.fc1.weight.data.size()[0])
self.fc1.weight.data.uniform_(-f1, f1)
self.fc1.bias.data.uniform_(-f1, f1)
f2 = 1.0 / np.sqrt(self.fc2.weight.data.size()[0])
self.fc2.weight.data.uniform_(-f2, f2)
self.fc2.bias.data.uniform_(-f2, f2)
f3 = 0.003
self.q.weight.data.uniform_(-f3, f3)
self.q.bias.data.uniform_(-f3, f3)
f4 = 1.0 / np.sqrt(self.action_value.weight.data.size()[0])
self.action_value.weight.data.uniform_(-f4, f4)
self.action_value.bias.data.uniform_(-f4, f4)
self.optimizer = optim.Adam(self.parameters(), lr=beta,
weight_decay=0.01)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self
def forward(self, state, action):
state_value = self.fc1(state)
action_value = self.action_value(action)
state_action_value = F.relu(T.add(state_value, action_value))
state_action_value = F.relu(T.add(self.fc2(state_action_value),
self.action_value2(state_action_value)))
state_action_value = self.q(state_action_value)
return state_action_value
def save_checkpoint(self, chkpt_dir='tmp/ddpg'):
None
checkpoint_file = chkpt_dir + '/' + str(self.name + '_ddpg.pt')
T.save(self.state_dict(), checkpoint_file)
def load_checkpoint(self, chkpt_dir='tmp/ddpg'):
None
checkpoint_file = chkpt_dir + '/' + str(self.name + '_ddpg.pt')
self.load_state_dict(T.load(checkpoint_file))
def save_best(self, chkpt_dir='best/ddpg'):
None
checkpoint_file = chkpt_dir + '/' + str(self.name + '_ddpg.pt')
T.save(self.state_dict(), checkpoint_file)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'beta': 4, 'input_dims': 4, 'fc1_dims': 4, 'fc2_dims': 4,
'n_actions': 4, 'name': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch as T
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_0(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp7 = tl.full([1], 0, tl.int32)
tmp8 = triton_helpers.maximum(tmp7, tmp6)
tmp9 = 0.0
tmp10 = tmp8 <= tmp9
tl.store(in_out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr0 + x2, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = 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, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (1, 4), (4, 1))
assert_size_stride(primals_12, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_6, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = 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_add_relu_threshold_backward_0[grid(256)](buf2,
primals_2, buf1, primals_5, buf9, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del primals_2
del primals_5
buf3 = buf1
del buf1
extern_kernels.mm(reinterpret_tensor(buf2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), out=buf3)
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf2, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (1, 4), 0), out=buf4)
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
buf8 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_add_relu_threshold_backward_0[grid(256)](buf5,
primals_8, buf4, primals_10, buf8, 256, XBLOCK=128, num_warps=4,
num_stages=1)
del buf4
del primals_10
del primals_8
buf7 = empty_strided_cuda((64, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_12, reinterpret_tensor(buf5, (64, 4),
(4, 1), 0), reinterpret_tensor(primals_11, (4, 1), (1, 4), 0),
alpha=1, beta=1, out=buf7)
del primals_12
return reinterpret_tensor(buf7, (4, 4, 4, 1), (16, 4, 1, 1), 0
), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), reinterpret_tensor(primals_6, (64, 4), (4, 1), 0
), reinterpret_tensor(buf2, (64, 4), (4, 1), 0), reinterpret_tensor(
buf5, (64, 4), (4, 1), 0), primals_11, buf8, primals_9, primals_7, buf9
class CriticNetworkNew(nn.Module):
def __init__(self, beta, input_dims, fc1_dims, fc2_dims, n_actions, name):
super(CriticNetworkNew, self).__init__()
self.input_dims = input_dims
self.fc1_dims = fc1_dims
self.fc2_dims = fc2_dims
self.n_actions = n_actions
self.name = name
self.fc1 = nn.Linear(self.input_dims, self.fc1_dims)
self.fc2 = nn.Linear(self.fc1_dims, self.fc2_dims)
self.action_value = nn.Linear(self.n_actions, self.fc1_dims)
self.action_value2 = nn.Linear(self.fc1_dims, self.fc2_dims)
self.q = nn.Linear(self.fc2_dims, 1)
f1 = 1.0 / np.sqrt(self.fc1.weight.data.size()[0])
self.fc1.weight.data.uniform_(-f1, f1)
self.fc1.bias.data.uniform_(-f1, f1)
f2 = 1.0 / np.sqrt(self.fc2.weight.data.size()[0])
self.fc2.weight.data.uniform_(-f2, f2)
self.fc2.bias.data.uniform_(-f2, f2)
f3 = 0.003
self.q.weight.data.uniform_(-f3, f3)
self.q.bias.data.uniform_(-f3, f3)
f4 = 1.0 / np.sqrt(self.action_value.weight.data.size()[0])
self.action_value.weight.data.uniform_(-f4, f4)
self.action_value.bias.data.uniform_(-f4, f4)
self.optimizer = optim.Adam(self.parameters(), lr=beta,
weight_decay=0.01)
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self
def save_checkpoint(self, chkpt_dir='tmp/ddpg'):
None
checkpoint_file = chkpt_dir + '/' + str(self.name + '_ddpg.pt')
T.save(self.state_dict(), checkpoint_file)
def load_checkpoint(self, chkpt_dir='tmp/ddpg'):
None
checkpoint_file = chkpt_dir + '/' + str(self.name + '_ddpg.pt')
self.load_state_dict(T.load(checkpoint_file))
def save_best(self, chkpt_dir='best/ddpg'):
None
checkpoint_file = chkpt_dir + '/' + str(self.name + '_ddpg.pt')
T.save(self.state_dict(), checkpoint_file)
def forward(self, input_0, input_1):
primals_1 = self.fc1.weight
primals_2 = self.fc1.bias
primals_4 = self.fc2.weight
primals_5 = self.fc2.bias
primals_7 = self.action_value.weight
primals_8 = self.action_value.bias
primals_9 = self.action_value2.weight
primals_10 = self.action_value2.bias
primals_11 = self.q.weight
primals_12 = self.q.bias
primals_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
Yang2581/Behavioral-Cloning
|
CriticNetwork
| false
| 1,881
|
[
"MIT"
] | 0
|
426e68a639e3e341f5547cfe40fb03ed8e87f3c8
|
https://github.com/Yang2581/Behavioral-Cloning/tree/426e68a639e3e341f5547cfe40fb03ed8e87f3c8
|
Net
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.device = torch.device('cuda' if torch.cuda.is_available() else
'cpu')
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = x
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
F.relu(self.fc1(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, 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)
@triton.jit
def triton_poi_fused_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 480
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 120
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 336
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 84
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11) = args
args.clear()
assert_size_stride(primals_1, (4, 3, 32, 32), (3072, 1024, 32, 1))
assert_size_stride(primals_2, (6, 3, 5, 5), (75, 25, 5, 1))
assert_size_stride(primals_3, (6,), (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, (120, 400), (400, 1))
assert_size_stride(primals_7, (120,), (1,))
assert_size_stride(primals_8, (84, 120), (120, 1))
assert_size_stride(primals_9, (84,), (1,))
assert_size_stride(primals_10, (10, 84), (84, 1))
assert_size_stride(primals_11, (10,), (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, 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_3,
18816, XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
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=128, 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=256, num_warps=4, num_stages=1)
buf8 = empty_strided_cuda((4, 120), (120, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf7, (4, 400), (400, 1), 0),
reinterpret_tensor(primals_6, (400, 120), (1, 400), 0), out=buf8)
buf9 = buf8
del buf8
triton_poi_fused_relu_4[grid(480)](buf9, primals_7, 480, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 84), (84, 1), torch.float32)
extern_kernels.mm(buf9, reinterpret_tensor(primals_8, (120, 84), (1,
120), 0), out=buf10)
buf11 = buf10
del buf10
triton_poi_fused_relu_5[grid(336)](buf11, primals_9, 336, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_9
buf12 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_11, buf11, reinterpret_tensor(
primals_10, (84, 10), (1, 84), 0), alpha=1, beta=1, out=buf12)
del primals_11
return (buf12, primals_1, primals_2, primals_4, buf1, buf2, buf3, buf5,
buf6, reinterpret_tensor(buf7, (4, 400), (400, 1), 0), buf9, buf11,
primals_10, primals_8, primals_6)
class NetNew(nn.Module):
def __init__(self):
super(NetNew, self).__init__()
self.device = torch.device('cuda' if torch.cuda.is_available() else
'cpu')
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, input_0):
primals_2 = self.conv1.weight
primals_3 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.fc1.weight
primals_7 = self.fc1.bias
primals_8 = self.fc2.weight
primals_9 = self.fc2.bias
primals_10 = self.fc3.weight
primals_11 = self.fc3.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11])
return output[0]
|
The-very-most-awesome-team-of-cool-kids/02463_Active_Learning
|
Net
| false
| 1,882
|
[
"MIT"
] | 0
|
abc35a31996de1c2e3275cf946b6a44f62abb781
|
https://github.com/The-very-most-awesome-team-of-cool-kids/02463_Active_Learning/tree/abc35a31996de1c2e3275cf946b6a44f62abb781
|
BertOutput
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.utils.checkpoint
class BertOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(intermediate_size=4, hidden_size=4,
layer_norm_eps=1, hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.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_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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_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 = 1.0
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, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_2, primals_4, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
del primals_4
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_5, primals_6, buf4, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del buf3
del primals_6
return buf4, primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf1
class BertOutputNew(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_0, input_1):
primals_1 = self.dense.weight
primals_2 = self.dense.bias
primals_5 = self.LayerNorm.weight
primals_6 = self.LayerNorm.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
MikeWangWZHL/BLIP
|
BertOutput
| false
| 1,883
|
[
"BSD-3-Clause"
] | 0
|
b82134f1892a54c8f63b0f4b51bdcb8684e1dc6d
|
https://github.com/MikeWangWZHL/BLIP/tree/b82134f1892a54c8f63b0f4b51bdcb8684e1dc6d
|
PixelNorm
|
import torch
import torch.nn as nn
import torch.utils.cpp_extension
def pixel_norm(x, eps=1e-06):
"""Pixel Normalization.
This normalization is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Args:
x (torch.Tensor): Tensor to be normalized.
eps (float, optional): Epsilon to avoid dividing zero.
Defaults to 1e-6.
Returns:
torch.Tensor: Normalized tensor.
"""
if torch.__version__ >= '1.7.0':
norm = torch.linalg.norm(x, ord=2, dim=1, keepdim=True)
else:
norm = torch.norm(x, p=2, dim=1, keepdim=True)
norm = norm / torch.sqrt(torch.tensor(x.shape[1]))
return x / (norm + eps)
class PixelNorm(nn.Module):
"""Pixel Normalization.
This module is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Args:
eps (float, optional): Epsilon value. Defaults to 1e-6.
"""
_abbr_ = 'pn'
def __init__(self, in_channels=None, eps=1e-06):
super().__init__()
self.eps = eps
def forward(self, x):
"""Forward function.
Args:
x (torch.Tensor): Tensor to be normalized.
Returns:
torch.Tensor: Normalized tensor.
"""
return pixel_norm(x, self.eps)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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_div_linalg_vector_norm_sqrt_0(in_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 0.5
tmp14 = tmp12 * tmp13
tmp15 = 1e-06
tmp16 = tmp14 + tmp15
tmp17 = tmp0 / tmp16
tl.store(out_ptr0 + x3, tmp17, 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_linalg_vector_norm_sqrt_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
def pixel_norm(x, eps=1e-06):
"""Pixel Normalization.
This normalization is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Args:
x (torch.Tensor): Tensor to be normalized.
eps (float, optional): Epsilon to avoid dividing zero.
Defaults to 1e-6.
Returns:
torch.Tensor: Normalized tensor.
"""
if torch.__version__ >= '1.7.0':
norm = torch.linalg.norm(x, ord=2, dim=1, keepdim=True)
else:
norm = torch.norm(x, p=2, dim=1, keepdim=True)
norm = norm / torch.sqrt(torch.tensor(x.shape[1]))
return x / (norm + eps)
class PixelNormNew(nn.Module):
"""Pixel Normalization.
This module is proposed in:
Progressive Growing of GANs for Improved Quality, Stability, and Variation
Args:
eps (float, optional): Epsilon value. Defaults to 1e-6.
"""
_abbr_ = 'pn'
def __init__(self, in_channels=None, eps=1e-06):
super().__init__()
self.eps = eps
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
bladesaber/mmgeneration
|
PixelNorm
| false
| 1,884
|
[
"Apache-2.0"
] | 0
|
158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
https://github.com/bladesaber/mmgeneration/tree/158b49f7efd8028f231f6e9ca758ae0e20dd72ae
|
EncoderBlock
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ScaledDotProductAttention(nn.Module):
def forward(self, query, key, value, mask=None):
dk = query.size()[-1]
scores = query.matmul(key.transpose(-2, -1)) / math.sqrt(dk)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1000000000.0)
attention = F.softmax(scores, dim=-1)
return attention.matmul(value)
class MultiHeadAttention(nn.Module):
def __init__(self, in_features, head_num, bias=True, activation=None):
super(MultiHeadAttention, self).__init__()
if in_features % head_num != 0:
raise ValueError(
'`in_features`({}) should be divisible by `head_num`({})'.
format(in_features, head_num))
self.in_features = in_features
self.head_num = head_num
self.activation = activation
self.bias = bias
self.linear_q = nn.Linear(in_features, in_features, bias)
self.linear_k = nn.Linear(in_features, in_features, bias)
self.linear_v = nn.Linear(in_features, in_features, bias)
self.linear_o = nn.Linear(in_features, in_features // self.head_num,
bias)
def forward(self, q, k, v, mask=None):
q, k, v = self.linear_q(q), self.linear_k(k), self.linear_v(v)
if self.activation is not None:
q = self.activation(q)
k = self.activation(k)
v = self.activation(v)
q = self._reshape_to_batches(q)
k = self._reshape_to_batches(k)
v = self._reshape_to_batches(v)
if mask is not None:
mask = mask.repeat(self.head_num, 1, 1)
y = ScaledDotProductAttention()(q, k, v, mask)
y = self._reshape_from_batches(y)
y = self.linear_o(y)
if self.activation is not None:
y = self.activation(y)
return y
@staticmethod
def gen_history_mask(x):
"""Generate the mask that only uses history data.
:param x: Input tensor.
:return: The mask.
"""
batch_size, seq_len, _ = x.size()
return torch.tril(torch.ones(seq_len, seq_len)).view(1, seq_len,
seq_len).repeat(batch_size, 1, 1)
def _reshape_to_batches(self, x):
batch_size, seq_len, in_feature = x.size()
sub_dim = in_feature // self.head_num
return x.reshape(batch_size, seq_len, self.head_num, sub_dim).permute(
0, 2, 1, 3).reshape(batch_size * self.head_num, seq_len, sub_dim)
def _reshape_from_batches(self, x):
batch_size, seq_len, in_feature = x.size()
batch_size //= self.head_num
out_dim = in_feature * self.head_num
return x.reshape(batch_size, self.head_num, seq_len, in_feature
).permute(0, 2, 1, 3).reshape(batch_size, seq_len, out_dim)
def extra_repr(self):
return 'in_features={}, head_num={}, bias={}, activation={}'.format(
self.in_features, self.head_num, self.bias, self.activation)
class EncoderBlock(nn.Module):
def __init__(self, embed_size, heads):
super(EncoderBlock, self).__init__()
self.heads = heads
self.norm1 = nn.LayerNorm(embed_size)
self.attention = MultiHeadAttention(embed_size * heads, head_num=
heads, bias=True, activation=None)
self.norm2 = nn.LayerNorm(embed_size)
self.mlp = nn.Linear(embed_size, embed_size)
def forward(self, x):
out = self.norm1(x)
out = out.repeat(1, 1, self.heads)
attention = self.attention(out, out, out, mask=None)
attention = attention + x
out2 = self.norm2(attention)
out3 = self.mlp(out2)
out3 = out3 + attention
return out3
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'embed_size': 4, '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 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_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_native_layer_norm_repeat_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 % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (4 * x1 + x0 % 4), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_clone_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 % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask)
tmp1 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + x4, tmp2, xmask)
@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 = 0.5
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x2, tmp17, 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, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4 % 4
x2 = xindex // 16 % 4
x3 = xindex // 64
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), xmask)
tl.store(out_ptr0 + x4, tmp0, xmask)
@triton.jit
def triton_poi_fused_add_native_layer_norm_7(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 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_8(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
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_add_9(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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp4 = tl.load(in_ptr2 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15) = 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, (16, 16), (16, 1))
assert_size_stride(primals_5, (16,), (1,))
assert_size_stride(primals_6, (16, 16), (16, 1))
assert_size_stride(primals_7, (16,), (1,))
assert_size_stride(primals_8, (16, 16), (16, 1))
assert_size_stride(primals_9, (16,), (1,))
assert_size_stride(primals_10, (4, 16), (16, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (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,))
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((4, 4, 16), (64, 16, 1), torch.float32)
triton_poi_fused_native_layer_norm_repeat_2[grid(256)](buf2, buf3,
256, XBLOCK=256, num_warps=4, num_stages=1)
buf4 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_4, (16, 16), (1, 16), 0), out=buf4)
buf5 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_6, (16, 16), (1, 16), 0), out=buf5)
buf6 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (16, 16), (16, 1), 0),
reinterpret_tensor(primals_8, (16, 16), (1, 16), 0), out=buf6)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_3[grid(256)](buf4, primals_5, buf7, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf8 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf4
triton_poi_fused_clone_3[grid(256)](buf5, primals_7, buf8, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1), 0)
del buf5
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 4), (16, 1, 4), 0), out=buf9)
buf10 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_4[grid(256)](buf9, buf10, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf11 = buf9
del buf9
triton_poi_fused__softmax_5[grid(256)](buf10, buf11, 256, XBLOCK=
256, num_warps=4, num_stages=1)
buf12 = reinterpret_tensor(buf10, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf10
triton_poi_fused_clone_3[grid(256)](buf6, primals_9, buf12, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_9
buf13 = reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1), 0)
del buf6
extern_kernels.bmm(buf11, reinterpret_tensor(buf12, (16, 4, 4), (16,
4, 1), 0), out=buf13)
buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_6[grid(256)](buf13, buf14, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf13
buf15 = reinterpret_tensor(buf2, (16, 4), (4, 1), 0)
del buf2
extern_kernels.addmm(primals_11, reinterpret_tensor(buf14, (16, 16),
(16, 1), 0), reinterpret_tensor(primals_10, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf15)
del primals_11
buf16 = buf1
del buf1
buf17 = buf0
del buf0
triton_poi_fused_add_native_layer_norm_7[grid(16)](buf15, primals_3,
buf16, buf17, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_8[grid(64)](buf15, primals_3,
buf16, buf17, primals_12, primals_13, buf18, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf16
del buf17
del primals_13
buf19 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf18, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_14, (4, 4), (1, 4), 0), out=buf19)
buf20 = reinterpret_tensor(buf19, (4, 4, 4), (16, 4, 1), 0)
del buf19
triton_poi_fused_add_9[grid(64)](buf20, primals_15, buf15,
primals_3, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_15
return buf20, primals_3, primals_12, reinterpret_tensor(buf3, (16, 16),
(16, 1), 0), buf11, reinterpret_tensor(buf14, (16, 16), (16, 1), 0
), buf15, reinterpret_tensor(buf18, (16, 4), (4, 1), 0
), primals_14, primals_10, reinterpret_tensor(buf12, (16, 4, 4), (
16, 1, 4), 0), reinterpret_tensor(buf7, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1), 0
), primals_8, primals_6, primals_4
class ScaledDotProductAttention(nn.Module):
def forward(self, query, key, value, mask=None):
dk = query.size()[-1]
scores = query.matmul(key.transpose(-2, -1)) / math.sqrt(dk)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1000000000.0)
attention = F.softmax(scores, dim=-1)
return attention.matmul(value)
class MultiHeadAttention(nn.Module):
def __init__(self, in_features, head_num, bias=True, activation=None):
super(MultiHeadAttention, self).__init__()
if in_features % head_num != 0:
raise ValueError(
'`in_features`({}) should be divisible by `head_num`({})'.
format(in_features, head_num))
self.in_features = in_features
self.head_num = head_num
self.activation = activation
self.bias = bias
self.linear_q = nn.Linear(in_features, in_features, bias)
self.linear_k = nn.Linear(in_features, in_features, bias)
self.linear_v = nn.Linear(in_features, in_features, bias)
self.linear_o = nn.Linear(in_features, in_features // self.head_num,
bias)
def forward(self, q, k, v, mask=None):
q, k, v = self.linear_q(q), self.linear_k(k), self.linear_v(v)
if self.activation is not None:
q = self.activation(q)
k = self.activation(k)
v = self.activation(v)
q = self._reshape_to_batches(q)
k = self._reshape_to_batches(k)
v = self._reshape_to_batches(v)
if mask is not None:
mask = mask.repeat(self.head_num, 1, 1)
y = ScaledDotProductAttention()(q, k, v, mask)
y = self._reshape_from_batches(y)
y = self.linear_o(y)
if self.activation is not None:
y = self.activation(y)
return y
@staticmethod
def gen_history_mask(x):
"""Generate the mask that only uses history data.
:param x: Input tensor.
:return: The mask.
"""
batch_size, seq_len, _ = x.size()
return torch.tril(torch.ones(seq_len, seq_len)).view(1, seq_len,
seq_len).repeat(batch_size, 1, 1)
def _reshape_to_batches(self, x):
batch_size, seq_len, in_feature = x.size()
sub_dim = in_feature // self.head_num
return x.reshape(batch_size, seq_len, self.head_num, sub_dim).permute(
0, 2, 1, 3).reshape(batch_size * self.head_num, seq_len, sub_dim)
def _reshape_from_batches(self, x):
batch_size, seq_len, in_feature = x.size()
batch_size //= self.head_num
out_dim = in_feature * self.head_num
return x.reshape(batch_size, self.head_num, seq_len, in_feature
).permute(0, 2, 1, 3).reshape(batch_size, seq_len, out_dim)
def extra_repr(self):
return 'in_features={}, head_num={}, bias={}, activation={}'.format(
self.in_features, self.head_num, self.bias, self.activation)
class EncoderBlockNew(nn.Module):
def __init__(self, embed_size, heads):
super(EncoderBlockNew, self).__init__()
self.heads = heads
self.norm1 = nn.LayerNorm(embed_size)
self.attention = MultiHeadAttention(embed_size * heads, head_num=
heads, bias=True, activation=None)
self.norm2 = nn.LayerNorm(embed_size)
self.mlp = nn.Linear(embed_size, embed_size)
def forward(self, input_0):
primals_1 = self.norm1.weight
primals_2 = self.norm1.bias
primals_4 = self.attention.linear_q.weight
primals_5 = self.attention.linear_q.bias
primals_6 = self.attention.linear_k.weight
primals_7 = self.attention.linear_k.bias
primals_8 = self.attention.linear_v.weight
primals_9 = self.attention.linear_v.bias
primals_10 = self.attention.linear_o.weight
primals_11 = self.attention.linear_o.bias
primals_12 = self.norm2.weight
primals_13 = self.norm2.bias
primals_14 = self.mlp.weight
primals_15 = self.mlp.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15])
return output[0]
|
dukeNashor/CaptainStony
|
EncoderBlock
| false
| 1,885
|
[
"MIT"
] | 0
|
6320a27420e686666a4d7172437cf55fe42de2b6
|
https://github.com/dukeNashor/CaptainStony/tree/6320a27420e686666a4d7172437cf55fe42de2b6
|
RobertaClassificationHead
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.utils.data
import torch.nn
class RobertaClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super(RobertaClassificationHead, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, features, **kwargs):
x = features[:, 0, :]
x = self.dropout(x)
x = self.dense(x)
x = torch.tanh(x)
x = self.dropout(x)
x = self.out_proj(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, hidden_dropout_prob=
0.5, num_labels=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.utils.data
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = libdevice.tanh(tmp2)
tl.store(in_out_ptr0 + x2, tmp3, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
del primals_2
buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused_tanh_1[grid(64)](buf2, primals_3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_3
buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (16, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf2, primals_4
class RobertaClassificationHeadNew(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super(RobertaClassificationHeadNew, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
def forward(self, input_0):
primals_2 = self.dense.weight
primals_3 = self.dense.bias
primals_4 = self.out_proj.weight
primals_5 = self.out_proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
HeartForNlp/VL-BERT
|
RobertaClassificationHead
| false
| 1,886
|
[
"MIT"
] | 0
|
c1a590e2597b592629329db126cf8eae74b49cc0
|
https://github.com/HeartForNlp/VL-BERT/tree/c1a590e2597b592629329db126cf8eae74b49cc0
|
CrossEntropyLoss
|
import torch
import torch.utils.cpp_extension
class CrossEntropyLoss(torch.nn.Module):
def __init__(self):
super(CrossEntropyLoss, self).__init__()
self.ce_loss = torch.nn.CrossEntropyLoss()
def forward(self, cls_output, label, **_):
return self.ce_loss(cls_output, label).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.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__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
@triton.jit
def triton_per_fused__log_softmax_div_mean_mul_neg_sum_1(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r3 = rindex
r0 = rindex % 16
r2 = rindex // 64
tmp0 = tl.load(in_ptr0 + r3, None)
tmp1 = tl.load(in_ptr0 + (r0 + 64 * r2), None, eviction_policy='evict_last'
)
tmp3 = tl.load(in_ptr0 + (16 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + r0 + 64 * r2), None, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr1 + r3, None)
tmp2 = tl_math.exp(tmp1)
tmp4 = tl_math.exp(tmp3)
tmp5 = tmp2 + tmp4
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp5 + tmp7
tmp10 = tl_math.exp(tmp9)
tmp11 = tmp8 + tmp10
tmp12 = tl_math.log(tmp11)
tmp13 = tmp0 - tmp12
tmp15 = tmp13 * tmp14
tmp16 = tl.broadcast_to(tmp15, [RBLOCK])
tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0))
tmp19 = -tmp18
tmp20 = 0.015625
tmp21 = tmp19 * tmp20
tmp22 = 1.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 = 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
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
triton_per_fused__log_softmax_div_mean_mul_neg_sum_1[grid(1)](buf2,
buf0, arg0_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del buf0
return buf2,
class CrossEntropyLossNew(torch.nn.Module):
def __init__(self):
super(CrossEntropyLossNew, self).__init__()
self.ce_loss = torch.nn.CrossEntropyLoss()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
ParthaEth/PyTorch-StudioGAN
|
CrossEntropyLoss
| false
| 1,887
|
[
"MIT"
] | 0
|
16dd84415e4b7f4667cb1b1e0ef3fc04edf6b5a9
|
https://github.com/ParthaEth/PyTorch-StudioGAN/tree/16dd84415e4b7f4667cb1b1e0ef3fc04edf6b5a9
|
BertSelfOutput
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn as nn
import torch.utils.checkpoint
class BertSelfOutput(nn.Module):
def __init__(self, config, twin=False, merge=False):
super().__init__()
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
if twin:
self.dense0 = nn.Linear(config.hidden_size, config.hidden_size)
self.dense1 = nn.Linear(config.hidden_size, config.hidden_size)
else:
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if merge:
self.act = ACT2FN[config.hidden_act]
self.merge_layer = nn.Linear(config.hidden_size * 2, config.
hidden_size)
self.merge = True
else:
self.merge = False
def forward(self, hidden_states, input_tensor):
if type(hidden_states) == list:
hidden_states0 = self.dense0(hidden_states[0])
hidden_states1 = self.dense1(hidden_states[1])
if self.merge:
hidden_states = self.merge_layer(torch.cat([hidden_states0,
hidden_states1], dim=-1))
else:
hidden_states = (hidden_states0 + hidden_states1) / 2
else:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, layer_norm_eps=1,
hidden_dropout_prob=0.5)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.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_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
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_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 = 1.0
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, 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, 4), (64, 16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_3, primals_4, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
del primals_4
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_5, primals_6, buf4, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf2
del buf3
del primals_6
return buf4, primals_5, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0
), buf1
class BertSelfOutputNew(nn.Module):
def __init__(self, config, twin=False, merge=False):
super().__init__()
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
if twin:
self.dense0 = nn.Linear(config.hidden_size, config.hidden_size)
self.dense1 = nn.Linear(config.hidden_size, config.hidden_size)
else:
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if merge:
self.act = ACT2FN[config.hidden_act]
self.merge_layer = nn.Linear(config.hidden_size * 2, config.
hidden_size)
self.merge = True
else:
self.merge = False
def forward(self, input_0, input_1):
primals_3 = self.LayerNorm.weight
primals_5 = self.LayerNorm.bias
primals_2 = self.dense.weight
primals_6 = self.dense.bias
primals_1 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
MikeWangWZHL/BLIP
|
BertSelfOutput
| false
| 1,888
|
[
"BSD-3-Clause"
] | 0
|
b82134f1892a54c8f63b0f4b51bdcb8684e1dc6d
|
https://github.com/MikeWangWZHL/BLIP/tree/b82134f1892a54c8f63b0f4b51bdcb8684e1dc6d
|
TransformerDecoderLayer
|
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == 'relu':
return F.relu
if activation == 'gelu':
return F.gelu
if activation == 'glu':
return F.glu
raise RuntimeError(f'activation should be relu/gelu, not {activation}.')
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
no_norm=False, activation='relu'):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=
dropout, bias=False)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout
=dropout, bias=False)
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) if not no_norm else nn.Identity()
self.norm2 = nn.LayerNorm(d_model) if not no_norm else nn.Identity()
self.norm3 = nn.LayerNorm(d_model) if not no_norm else nn.Identity()
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, tgt, memory, pos=None, query_pos=None):
tgt2 = self.norm1(tgt)
q = k = self.with_pos_embed(tgt2, query_pos)
tgt2 = self.self_attn(q, k, value=tgt2)[0]
tgt = tgt + self.dropout1(tgt2)
tgt2 = self.norm2(tgt)
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2,
query_pos), key=self.with_pos_embed(memory, pos), value=memory)[0]
tgt = tgt + self.dropout2(tgt2)
tgt2 = self.norm3(tgt)
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
tgt = tgt + self.dropout3(tgt2)
return tgt
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'nhead': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo
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 = 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_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_mul_2(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tl.store(in_out_ptr0 + x0, tmp2, 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
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 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_5(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_6(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_7(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_add_8(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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp3 = tl.load(in_out_ptr0 + x0, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x0, tmp4, xmask)
@triton.jit
def triton_poi_fused_relu_9(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr
):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 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_10(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)
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) = 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, 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, 4), (4, 1))
assert_size_stride(primals_9, (12, 4), (4, 1))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (2048, 4), (4, 1))
assert_size_stride(primals_14, (2048,), (1,))
assert_size_stride(primals_15, (4, 2048), (2048, 1))
assert_size_stride(primals_16, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf1 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(4)](primals_3, buf0, buf1,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(16)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del primals_1
del primals_2
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 16), out=buf4)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4, 4), (1, 4
), 32), out=buf5)
buf6 = reinterpret_tensor(buf3, (4, 4, 1), (1, 4, 16), 0)
del buf3
triton_poi_fused_mul_2[grid(16)](buf6, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(buf6, reinterpret_tensor(buf4, (4, 1, 4), (1, 1,
4), 0), out=buf7)
buf8 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_3[grid(64)](buf7, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = buf7
del buf7
triton_poi_fused__softmax_4[grid(64)](buf8, buf9, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf9, reinterpret_tensor(buf5, (4, 4, 1), (1, 4,
1), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_5[grid(4, 4)](buf10, buf11, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf12 = reinterpret_tensor(buf10, (4, 4), (4, 1), 0)
del buf10
extern_kernels.mm(reinterpret_tensor(buf11, (4, 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_6[grid(4)](primals_3, buf12,
buf13, buf14, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_7[grid(16)](primals_3, buf12,
buf13, buf14, primals_6, primals_7, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_7
buf16 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf15, reinterpret_tensor(primals_9, (4, 4), (1,
4), 0), out=buf16)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_8, reinterpret_tensor(primals_9, (4, 4),
(1, 4), 16), out=buf17)
buf18 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_8, reinterpret_tensor(primals_9, (4, 4),
(1, 4), 32), out=buf18)
buf19 = reinterpret_tensor(buf16, (4, 4, 1), (1, 4, 16), 0)
del buf16
triton_poi_fused_mul_2[grid(16)](buf19, 16, XBLOCK=16, num_warps=1,
num_stages=1)
buf20 = buf8
del buf8
extern_kernels.bmm(buf19, reinterpret_tensor(buf17, (4, 1, 4), (1,
1, 4), 0), out=buf20)
buf21 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused__softmax_3[grid(64)](buf20, buf21, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf22 = buf20
del buf20
triton_poi_fused__softmax_4[grid(64)](buf21, buf22, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf21
buf23 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf22, reinterpret_tensor(buf18, (4, 4, 1), (1,
4, 1), 0), out=buf23)
buf24 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
triton_poi_fused_clone_5[grid(4, 4)](buf23, buf24, 4, 4, XBLOCK=4,
YBLOCK=4, num_warps=1, num_stages=1)
buf25 = reinterpret_tensor(buf23, (4, 4), (4, 1), 0)
del buf23
extern_kernels.mm(reinterpret_tensor(buf24, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf25)
buf26 = buf25
del buf25
triton_poi_fused_add_8[grid(16)](buf26, primals_3, buf12, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf27 = buf14
del buf14
buf28 = buf13
del buf13
triton_poi_fused_native_layer_norm_0[grid(4)](buf26, buf27, buf28,
4, XBLOCK=4, num_warps=1, num_stages=1)
buf29 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(16)](buf26, buf27, buf28,
primals_11, primals_12, buf29, 16, XBLOCK=16, num_warps=1,
num_stages=1)
del buf27
del buf28
del primals_12
buf30 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32)
extern_kernels.mm(buf29, reinterpret_tensor(primals_13, (4, 2048),
(1, 4), 0), out=buf30)
buf31 = buf30
del buf30
triton_poi_fused_relu_9[grid(8192)](buf31, primals_14, 8192, XBLOCK
=256, num_warps=4, num_stages=1)
del primals_14
buf32 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf31, reinterpret_tensor(primals_15, (2048, 4),
(1, 2048), 0), out=buf32)
buf33 = buf32
del buf32
triton_poi_fused_add_10[grid(16)](buf33, buf26, primals_16, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_16
return (buf33, primals_3, primals_6, primals_11, buf2, buf9,
reinterpret_tensor(buf11, (4, 4), (4, 1), 0), buf12, buf15,
primals_8, buf22, reinterpret_tensor(buf24, (4, 4), (4, 1), 0),
buf26, buf29, buf31, primals_15, primals_13, primals_10,
reinterpret_tensor(buf18, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf19, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf17, (4, 4, 1), (1, 4, 1), 0),
reinterpret_tensor(primals_9, (4, 4), (4, 1), 0), primals_5,
reinterpret_tensor(buf5, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf6, (4, 1, 4), (1, 1, 4), 0),
reinterpret_tensor(buf4, (4, 4, 1), (1, 4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 32),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 16),
reinterpret_tensor(primals_4, (4, 4), (4, 1), 0))
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == 'relu':
return F.relu
if activation == 'gelu':
return F.gelu
if activation == 'glu':
return F.glu
raise RuntimeError(f'activation should be relu/gelu, not {activation}.')
class TransformerDecoderLayerNew(nn.Module):
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1,
no_norm=False, activation='relu'):
super().__init__()
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=
dropout, bias=False)
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout
=dropout, bias=False)
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) if not no_norm else nn.Identity()
self.norm2 = nn.LayerNorm(d_model) if not no_norm else nn.Identity()
self.norm3 = nn.LayerNorm(d_model) if not no_norm else nn.Identity()
self.dropout1 = nn.Dropout(dropout)
self.dropout2 = nn.Dropout(dropout)
self.dropout3 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation)
def with_pos_embed(self, tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, input_0, input_1):
primals_4 = self.self_attn.in_proj_weight
primals_3 = self.self_attn.out_proj.weight
primals_9 = self.multihead_attn.in_proj_weight
primals_5 = self.multihead_attn.out_proj.weight
primals_13 = self.linear1.weight
primals_14 = self.linear1.bias
primals_15 = self.linear2.weight
primals_1 = self.linear2.bias
primals_2 = self.norm1.weight
primals_6 = self.norm1.bias
primals_7 = self.norm2.weight
primals_11 = self.norm2.bias
primals_12 = self.norm3.weight
primals_16 = self.norm3.bias
primals_8 = input_0
primals_10 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16])
return output[0]
|
dongyan007/Pretrained-IPT-main-master
|
TransformerDecoderLayer
| false
| 1,889
|
[
"Apache-2.0"
] | 0
|
7ed47002373e11bd57b7904f6935acdfba1e44ff
|
https://github.com/dongyan007/Pretrained-IPT-main-master/tree/7ed47002373e11bd57b7904f6935acdfba1e44ff
|
Sampling
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
class Sampling(nn.Module):
def __init__(self, args, seq_len):
super(Sampling, self).__init__()
self.conv = nn.Conv1d(seq_len, args.att_out_channel, kernel_size=1)
def forward(self, x):
"""
:param x: (batch, N=1, channel, wavelet_seq)
:return: (batch, N=1, att_out_channel, wavelet_seq[-1])
"""
x = x.squeeze()
conv_out = self.conv(x)
return conv_out[..., -1]
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'args': _mock_config(att_out_channel=4), 'seq_len': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 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
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
4, 4), (16, 4, 1), 0), primals_2, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (1, 4, 4), (16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16)](buf1, primals_3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
return reinterpret_tensor(buf1, (4,), (4,), 3
), primals_2, reinterpret_tensor(primals_1, (1, 4, 4), (16, 4, 1), 0)
class SamplingNew(nn.Module):
def __init__(self, args, seq_len):
super(SamplingNew, self).__init__()
self.conv = nn.Conv1d(seq_len, args.att_out_channel, kernel_size=1)
def forward(self, input_0):
primals_2 = self.conv.weight
primals_3 = self.conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
ICLab4DL/AWN
|
Sampling
| false
| 1,890
|
[
"MIT"
] | 0
|
48d6edd85eabd77e9bb410dc5f31f8f937c9a857
|
https://github.com/ICLab4DL/AWN/tree/48d6edd85eabd77e9bb410dc5f31f8f937c9a857
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.