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
|
|---|---|---|---|---|---|---|---|---|---|---|
ScaledDotProductAttentionMemory
|
import torch
import numpy as np
import torch.nn as nn
class ScaledDotProductAttentionMemory(nn.Module):
"""
Scaled dot-product attention with memory
"""
def __init__(self, d_model, d_k, d_v, h, m):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
:param m: Number of memory slots
"""
super(ScaledDotProductAttentionMemory, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.m_k = nn.Parameter(torch.FloatTensor(1, m, h * d_k))
self.m_v = nn.Parameter(torch.FloatTensor(1, m, h * d_v))
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.m = m
self.init_weights()
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.normal_(self.m_k, 0, 1 / self.d_k)
nn.init.normal_(self.m_v, 0, 1 / self.m)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
m_k = np.sqrt(self.d_k) * self.m_k.expand(b_s, self.m, self.h *
self.d_k)
m_v = np.sqrt(self.m) * self.m_v.expand(b_s, self.m, self.h * self.d_v)
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = torch.cat([self.fc_k(keys), m_k], 1).view(b_s, nk + self.m,
self.h, self.d_k).permute(0, 2, 3, 1)
v = torch.cat([self.fc_v(values), m_v], 1).view(b_s, nk + self.m,
self.h, self.d_v).permute(0, 2, 1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = torch.cat([att[:, :, :, :nk] * attention_weights, att[:,
:, :, nk:]], -1)
if attention_mask is not None:
att[:, :, :, :nk] = att[:, :, :, :nk].masked_fill(attention_mask,
-np.inf)
att = torch.softmax(att, -1)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'d_model': 4, 'd_k': 4, 'd_v': 4, 'h': 4, 'm': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, 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_clone_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8 % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x1 + 16 * x0 + 64 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x1 + 16 * (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = 2.0
tmp11 = tmp10 * tmp9
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp6, tmp11, tmp12)
tmp14 = tl.where(tmp4, tmp5, tmp13)
tl.store(out_ptr0 + x3, tmp14, xmask)
@triton.jit
def triton_per_fused__softmax_sqrt_2(in_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 8 * x0), xmask, other=0.0)
tmp1 = tl.full([1, 1], 2.0, tl.float64)
tmp2 = tl.full([1, 1], 0.0, tl.float64)
tmp3 = tmp1 >= tmp2
tmp4 = 1.0
tmp5 = -1.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.where(xmask, tmp8, float('-inf'))
tmp11 = triton_helpers.max2(tmp10, 1)[:, None]
tmp12 = tmp7 - tmp11
tmp13 = tmp6.to(tl.float64)
tmp14 = tmp13 * tmp1
tmp15 = tmp14.to(tl.float32)
tmp16 = tmp12 / tmp15
tmp17 = tl_math.exp(tmp16)
tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
tmp20 = tl.where(xmask, tmp18, 0)
tmp21 = tl.sum(tmp20, 1)[:, None]
tmp22 = tmp17 / tmp21
tl.store(out_ptr2 + (r1 + 8 * x0), tmp22, xmask)
@triton.jit
def triton_poi_fused_clone_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 8
x0 = xindex % 4
x2 = xindex // 32 % 4
x3 = xindex // 128
x4 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 4 * x2 + 16 * x1 + 64 * x3), tmp4 &
xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 4 * x2 + 16 * (-4 + x1)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = 2.0
tmp11 = tmp10 * tmp9
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp6, tmp11, tmp12)
tmp14 = tl.where(tmp4, tmp5, tmp13)
tl.store(out_ptr0 + x4, tmp14, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (1, 4, 16), (64, 16, 1))
assert_size_stride(primals_4, (1, 4, 16), (64, 16, 1))
assert_size_stride(primals_5, (16, 4), (4, 1))
assert_size_stride(primals_6, (16,), (1,))
assert_size_stride(primals_7, (16, 4), (4, 1))
assert_size_stride(primals_8, (16,), (1,))
assert_size_stride(primals_9, (16, 4), (4, 1))
assert_size_stride(primals_10, (16,), (1,))
assert_size_stride(primals_11, (4, 4, 4), (16, 4, 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((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 16), (1, 4), 0), out=buf0)
del primals_5
buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(primals_2, (16,
4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf1)
del primals_7
del primals_8
buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.addmm(primals_10, reinterpret_tensor(primals_11, (16,
4), (4, 1), 0), reinterpret_tensor(primals_9, (4, 16), (1, 4),
0), alpha=1, beta=1, out=buf2)
del primals_10
del primals_9
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf0, primals_6, buf3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_6
buf4 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.float32)
triton_poi_fused_clone_1[grid(512)](buf1, primals_3, buf4, 512,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf5 = empty_strided_cuda((16, 4, 8), (32, 8, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (16, 4, 8), (32, 8, 1), 0), out=buf5)
buf8 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.float32)
triton_per_fused__softmax_sqrt_2[grid(64)](buf5, buf8, 64, 8,
XBLOCK=32, num_warps=2, num_stages=1)
buf9 = reinterpret_tensor(buf5, (4, 4, 8, 4), (128, 32, 4, 1), 0)
del buf5
triton_poi_fused_clone_3[grid(512)](buf2, primals_4, buf9, 512,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_4
buf10 = reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 8), (32, 8, 1),
0), reinterpret_tensor(buf9, (16, 8, 4), (32, 4, 1), 0), out=buf10)
buf11 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
triton_poi_fused_clone_4[grid(256)](buf10, buf11, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf10
buf12 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_13, reinterpret_tensor(buf11, (16, 16),
(16, 1), 0), reinterpret_tensor(primals_12, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf12)
del primals_13
return reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_11, (16, 4), (4, 1), 0
), buf8, reinterpret_tensor(buf11, (16, 16), (16, 1), 0
), primals_12, reinterpret_tensor(buf9, (16, 4, 8), (32, 1, 4), 0
), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf4, (16, 8, 4), (32, 1, 8), 0)
class ScaledDotProductAttentionMemoryNew(nn.Module):
"""
Scaled dot-product attention with memory
"""
def __init__(self, d_model, d_k, d_v, h, m):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
:param m: Number of memory slots
"""
super(ScaledDotProductAttentionMemoryNew, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.m_k = nn.Parameter(torch.FloatTensor(1, m, h * d_k))
self.m_v = nn.Parameter(torch.FloatTensor(1, m, h * d_v))
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.m = m
self.init_weights()
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.normal_(self.m_k, 0, 1 / self.d_k)
nn.init.normal_(self.m_v, 0, 1 / self.m)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, input_0, input_1, input_2):
primals_3 = self.m_k
primals_4 = self.m_v
primals_5 = self.fc_q.weight
primals_6 = self.fc_q.bias
primals_7 = self.fc_k.weight
primals_8 = self.fc_k.bias
primals_9 = self.fc_v.weight
primals_10 = self.fc_v.bias
primals_12 = self.fc_o.weight
primals_13 = self.fc_o.bias
primals_1 = input_0
primals_2 = input_1
primals_11 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
jianqingxie/RSTNet
|
ScaledDotProductAttentionMemory
| false
| 15,692
|
[
"BSD-3-Clause"
] | 68
|
aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
https://github.com/jianqingxie/RSTNet/tree/aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
ScaledDotProductGeometryAttention
|
import torch
import numpy as np
import torch.nn as nn
class ScaledDotProductGeometryAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1, comment=None):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductGeometryAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
self.comment = comment
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, queries, keys, values, box_relation_embed_matrix,
attention_mask=None, attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
w_g = box_relation_embed_matrix
w_a = att
w_mn = torch.log(torch.clamp(w_g, min=1e-06)) + w_a
w_mn = torch.softmax(w_mn, -1)
att = self.dropout(w_mn)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
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])]
def get_init_inputs():
return [[], {'d_model': 4, 'd_k': 4, 'd_v': 4, 'h': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, 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_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_add_clamp_div_log_sqrt_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 % 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp1 = 1e-06
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tl_math.log(tmp2)
tmp5 = 2.0
tmp6 = tmp4 / tmp5
tmp7 = tmp3 + tmp6
tmp9 = triton_helpers.maximum(tmp8, tmp1)
tmp10 = tl_math.log(tmp9)
tmp12 = tmp11 / tmp5
tmp13 = tmp10 + tmp12
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp16 = triton_helpers.maximum(tmp15, tmp1)
tmp17 = tl_math.log(tmp16)
tmp19 = tmp18 / tmp5
tmp20 = tmp17 + tmp19
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp23 = triton_helpers.maximum(tmp22, tmp1)
tmp24 = tl_math.log(tmp23)
tmp26 = tmp25 / tmp5
tmp27 = tmp24 + tmp26
tmp28 = triton_helpers.maximum(tmp21, tmp27)
tmp29 = tmp7 - tmp28
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp13 - tmp28
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp30 + tmp32
tmp34 = tmp20 - tmp28
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp33 + tmp35
tmp37 = tmp27 - tmp28
tmp38 = tl_math.exp(tmp37)
tmp39 = tmp36 + tmp38
tl.store(out_ptr0 + x2, tmp28, xmask)
tl.store(out_ptr1 + x2, tmp39, xmask)
@triton.jit
def triton_poi_fused__softmax_add_clamp_div_log_sqrt_3(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
x3 = xindex % 64
x4 = xindex
x5 = xindex // 4
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_out_ptr0 + x4, xmask)
tmp8 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last')
tmp1 = 1e-06
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tl_math.log(tmp2)
tmp5 = 2.0
tmp6 = tmp4 / tmp5
tmp7 = tmp3 + tmp6
tmp9 = tmp7 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tl.store(in_out_ptr0 + x4, tmp12, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12
) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (16, 4), (4, 1))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (16, 4), (4, 1))
assert_size_stride(primals_6, (16,), (1,))
assert_size_stride(primals_7, (16, 4), (4, 1))
assert_size_stride(primals_8, (16,), (1,))
assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_10, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_11, (4, 16), (16, 1))
assert_size_stride(primals_12, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 16), (1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 16), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 16), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf0, primals_4, buf3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_4
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_clone_1[grid(64, 4)](buf1, primals_6, buf4, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_6
buf5 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_add_clamp_div_log_sqrt_2[grid(64)](primals_10
, buf5, buf6, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused__softmax_add_clamp_div_log_sqrt_3[grid(256)](buf8,
primals_10, buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf6
del primals_10
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(256)](buf2, primals_8, buf9, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_8
buf10 = reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (16, 4, 4), (16, 4, 1), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_4[grid(256)](buf10, buf11, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf10
buf12 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_12, reinterpret_tensor(buf11, (16, 16),
(16, 1), 0), reinterpret_tensor(primals_11, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf12)
del primals_12
return reinterpret_tensor(buf12, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_2, (16, 4), (4, 1), 0
), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
), buf8, reinterpret_tensor(buf11, (16, 16), (16, 1), 0
), primals_11, reinterpret_tensor(buf9, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf4, (16, 4, 4), (16, 1, 4), 0)
class ScaledDotProductGeometryAttentionNew(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1, comment=None):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductGeometryAttentionNew, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
self.comment = comment
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, input_0, input_1, input_2, input_3):
primals_3 = self.fc_q.weight
primals_4 = self.fc_q.bias
primals_5 = self.fc_k.weight
primals_6 = self.fc_k.bias
primals_7 = self.fc_v.weight
primals_8 = self.fc_v.bias
primals_11 = self.fc_o.weight
primals_12 = self.fc_o.bias
primals_1 = input_0
primals_2 = input_1
primals_9 = input_2
primals_10 = input_3
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12])
return output[0]
|
jianqingxie/RSTNet
|
ScaledDotProductGeometryAttention
| false
| 15,693
|
[
"BSD-3-Clause"
] | 68
|
aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
https://github.com/jianqingxie/RSTNet/tree/aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
NTN
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class NTN(nn.Module):
def __init__(self, l_dim, r_dim, k=4, non_linear=F.tanh):
super(NTN, self).__init__()
self.u_R = nn.Linear(k, 1, bias=False)
self.f = non_linear
self.W = nn.Bilinear(l_dim, r_dim, k, bias=True)
self.V = nn.Linear(l_dim + r_dim, k, bias=False)
def forward(self, e1, e2):
"""
e1: tensor of size (*, l_dim)
e2: tensor of size (*, r_dim)
return: tensor of size (*, 1)
"""
return self.u_R(self.f(self.W(e1, e2) + self.V(torch.cat((e1, e2), 1)))
)
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'l_dim': 4, 'r_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_tanh_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
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
tmp5 = libdevice.tanh(tmp4)
tl.store(in_out_ptr0 + x2, tmp5, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 8), (8, 1))
assert_size_stride(primals_6, (1, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = torch.ops.aten._trilinear.default(primals_4, primals_1,
primals_3, [1, 3], [0], [1, 2], [2, 3])
del primals_1
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(32)](primals_4, primals_3, buf2, 32,
XBLOCK=32, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(primals_5, (8, 4), (1, 8
), 0), out=buf3)
del primals_5
buf4 = buf1
del buf1
triton_poi_fused_add_tanh_1[grid(16)](buf4, primals_2, buf3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf3
del primals_2
buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.mm(buf4, reinterpret_tensor(primals_6, (4, 1), (1, 4
), 0), out=buf5)
return buf5, primals_4, primals_3, buf2, buf4, primals_6
class NTNNew(nn.Module):
def __init__(self, l_dim, r_dim, k=4, non_linear=F.tanh):
super(NTNNew, self).__init__()
self.u_R = nn.Linear(k, 1, bias=False)
self.f = non_linear
self.W = nn.Bilinear(l_dim, r_dim, k, bias=True)
self.V = nn.Linear(l_dim + r_dim, k, bias=False)
def forward(self, input_0, input_1):
primals_6 = self.u_R.weight
primals_1 = self.W.weight
primals_2 = self.W.bias
primals_5 = self.V.weight
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]
|
jinfenglin/TaxoExpan
|
NTN
| false
| 15,694
|
[
"Apache-2.0"
] | 55
|
86bd3f805508d03367539f2fdd43889fc0a4f6b2
|
https://github.com/jinfenglin/TaxoExpan/tree/86bd3f805508d03367539f2fdd43889fc0a4f6b2
|
ELU
|
import torch
import torch.nn as nn
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class ELU(ActivationFunction):
def forward(self, x):
return torch.where(x > 0, x, torch.exp(x) - 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 math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_exp_gt_sub_where_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = tl_math.exp(tmp0)
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tl.where(tmp2, tmp0, 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, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_exp_gt_sub_where_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class ELUNew(ActivationFunction):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiwidi/lightning-tutorials
|
ELU
| false
| 15,695
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
LeakyReLU
|
import torch
import torch.nn as nn
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class LeakyReLU(ActivationFunction):
def __init__(self, alpha=0.1):
super().__init__()
self.config['alpha'] = alpha
def forward(self, x):
return torch.where(x > 0, x, self.config['alpha'] * 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_gt_mul_where_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 0.1
tmp4 = tmp0 * tmp3
tmp5 = tl.where(tmp2, tmp0, tmp4)
tl.store(out_ptr0 + x0, tmp5, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_gt_mul_where_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class LeakyReLUNew(ActivationFunction):
def __init__(self, alpha=0.1):
super().__init__()
self.config['alpha'] = alpha
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiwidi/lightning-tutorials
|
LeakyReLU
| false
| 15,696
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
ConcatELU
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConcatELU(nn.Module):
"""Activation function that applies ELU in both direction (inverted and plain).
Allows non-linearity while providing strong gradients for any input (important for final convolution)
"""
def forward(self, x):
return torch.cat([F.elu(x), F.elu(-x)], dim=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
@triton.jit
def triton_poi_fused_cat_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
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = 0.0
tmp7 = tmp5 > tmp6
tmp8 = 1.0
tmp9 = tmp5 * tmp8
tmp10 = libdevice.expm1(tmp9)
tmp11 = tmp10 * tmp8
tmp12 = tl.where(tmp7, tmp9, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp18 = tl.load(in_ptr0 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp15 &
xmask, other=0.0)
tmp19 = -tmp18
tmp20 = tmp19 > tmp6
tmp21 = tmp19 * tmp8
tmp22 = libdevice.expm1(tmp21)
tmp23 = tmp22 * tmp8
tmp24 = tl.where(tmp20, tmp21, tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp15, tmp24, tmp25)
tmp27 = tl.where(tmp4, tmp14, tmp26)
tl.store(out_ptr0 + x3, tmp27, 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, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](arg0_1, buf0, 512, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ConcatELUNew(nn.Module):
"""Activation function that applies ELU in both direction (inverted and plain).
Allows non-linearity while providing strong gradients for any input (important for final convolution)
"""
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiwidi/lightning-tutorials
|
ConcatELU
| false
| 15,697
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
ReLU
|
import torch
import torch.nn as nn
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class ReLU(ActivationFunction):
def forward(self, x):
return x * (x > 0).float()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__to_copy_gt_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tmp0 * tmp3
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__to_copy_gt_mul_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class ReLUNew(ActivationFunction):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiwidi/lightning-tutorials
|
ReLU
| false
| 15,698
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
MultiHeadGeometryAttention
|
from torch.nn import Module
import torch
import numpy as np
import torch.nn as nn
class ScaledDotProductGeometryAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1, comment=None):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductGeometryAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
self.comment = comment
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, queries, keys, values, box_relation_embed_matrix,
attention_mask=None, attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
w_g = box_relation_embed_matrix
w_a = att
w_mn = torch.log(torch.clamp(w_g, min=1e-06)) + w_a
w_mn = torch.softmax(w_mn, -1)
att = self.dropout(w_mn)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class MultiHeadGeometryAttention(Module):
"""
Multi-head attention layer with Dropout and Layer Normalization.
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1,
identity_map_reordering=False, can_be_stateful=False,
attention_module=None, attention_module_kwargs=None, comment=None):
super(MultiHeadGeometryAttention, self).__init__()
self.identity_map_reordering = identity_map_reordering
self.attention = ScaledDotProductGeometryAttention(d_model=d_model,
d_k=d_k, d_v=d_v, h=h, comment=comment)
self.dropout = nn.Dropout(p=dropout)
self.layer_norm = nn.LayerNorm(d_model)
self.can_be_stateful = can_be_stateful
if self.can_be_stateful:
self.register_state('running_keys', torch.zeros((0, d_model)))
self.register_state('running_values', torch.zeros((0, d_model)))
def forward(self, queries, keys, values, relative_geometry_weights,
attention_mask=None, attention_weights=None):
if self.can_be_stateful and self._is_stateful:
self.running_keys = torch.cat([self.running_keys, keys], 1)
keys = self.running_keys
self.running_values = torch.cat([self.running_values, values], 1)
values = self.running_values
if self.identity_map_reordering:
q_norm = self.layer_norm(queries)
k_norm = self.layer_norm(keys)
v_norm = self.layer_norm(values)
out = self.attention(q_norm, k_norm, v_norm,
relative_geometry_weights, attention_mask, attention_weights)
out = queries + self.dropout(torch.relu(out))
else:
out = self.attention(queries, keys, values,
relative_geometry_weights, attention_mask, attention_weights)
out = self.dropout(out)
out = self.layer_norm(queries + out)
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])]
def get_init_inputs():
return [[], {'d_model': 4, 'd_k': 4, 'd_v': 4, 'h': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch.nn import Module
import numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
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_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused__softmax_add_clamp_div_log_sqrt_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 % 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + 4 * x2, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr1 + (1 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr1 + (2 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + (3 + 4 * x2), xmask, eviction_policy='evict_last'
)
tmp1 = 1e-06
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tl_math.log(tmp2)
tmp5 = 2.0
tmp6 = tmp4 / tmp5
tmp7 = tmp3 + tmp6
tmp9 = triton_helpers.maximum(tmp8, tmp1)
tmp10 = tl_math.log(tmp9)
tmp12 = tmp11 / tmp5
tmp13 = tmp10 + tmp12
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp16 = triton_helpers.maximum(tmp15, tmp1)
tmp17 = tl_math.log(tmp16)
tmp19 = tmp18 / tmp5
tmp20 = tmp17 + tmp19
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp23 = triton_helpers.maximum(tmp22, tmp1)
tmp24 = tl_math.log(tmp23)
tmp26 = tmp25 / tmp5
tmp27 = tmp24 + tmp26
tmp28 = triton_helpers.maximum(tmp21, tmp27)
tmp29 = tmp7 - tmp28
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp13 - tmp28
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp30 + tmp32
tmp34 = tmp20 - tmp28
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp33 + tmp35
tmp37 = tmp27 - tmp28
tmp38 = tl_math.exp(tmp37)
tmp39 = tmp36 + tmp38
tl.store(out_ptr0 + x2, tmp28, xmask)
tl.store(out_ptr1 + x2, tmp39, xmask)
@triton.jit
def triton_poi_fused__softmax_add_clamp_div_log_sqrt_3(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
x3 = xindex % 64
x4 = xindex
x5 = xindex // 4
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_out_ptr0 + x4, xmask)
tmp8 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last')
tmp1 = 1e-06
tmp2 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = tl_math.log(tmp2)
tmp5 = 2.0
tmp6 = tmp4 / tmp5
tmp7 = tmp3 + tmp6
tmp9 = tmp7 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tl.store(in_out_ptr0 + x4, tmp12, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_5(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_6(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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (16, 4), (4, 1))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (16, 4), (4, 1))
assert_size_stride(primals_6, (16,), (1,))
assert_size_stride(primals_7, (16, 4), (4, 1))
assert_size_stride(primals_8, (16,), (1,))
assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_10, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_11, (4, 16), (16, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4,), (1,))
assert_size_stride(primals_14, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 16), (1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 16), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 16), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf0, primals_4, buf3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_4
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_clone_1[grid(64, 4)](buf1, primals_6, buf4, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_6
buf5 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf7 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
triton_poi_fused__softmax_add_clamp_div_log_sqrt_2[grid(64)](primals_10
, buf5, buf6, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf8 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused__softmax_add_clamp_div_log_sqrt_3[grid(256)](buf8,
primals_10, buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_10
buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_0[grid(256)](buf2, primals_8, buf9, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_8
buf10 = reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf9, (16, 4, 4), (16, 4, 1), 0), out=buf10)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_4[grid(256)](buf10, buf11, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf10
buf12 = reinterpret_tensor(buf7, (16, 4), (4, 1), 0)
del buf7
extern_kernels.addmm(primals_12, reinterpret_tensor(buf11, (16, 16),
(16, 1), 0), reinterpret_tensor(primals_11, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf12)
del primals_12
buf13 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf14 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_5[grid(16)](primals_1, buf12,
buf13, buf14, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf15 = reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0)
del buf6
triton_poi_fused_add_native_layer_norm_6[grid(64)](primals_1, buf12,
buf13, buf14, primals_13, primals_14, buf15, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf13
del buf14
del primals_14
return buf15, primals_1, primals_13, reinterpret_tensor(primals_2, (16,
4), (4, 1), 0), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
), buf8, reinterpret_tensor(buf11, (16, 16), (16, 1), 0
), buf12, primals_11, reinterpret_tensor(buf9, (16, 4, 4), (16, 1,
4), 0), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf4, (16, 4, 4), (16, 1, 4), 0)
class ScaledDotProductGeometryAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1, comment=None):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductGeometryAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
self.comment = comment
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, queries, keys, values, box_relation_embed_matrix,
attention_mask=None, attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
w_g = box_relation_embed_matrix
w_a = att
w_mn = torch.log(torch.clamp(w_g, min=1e-06)) + w_a
w_mn = torch.softmax(w_mn, -1)
att = self.dropout(w_mn)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class MultiHeadGeometryAttentionNew(Module):
"""
Multi-head attention layer with Dropout and Layer Normalization.
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1,
identity_map_reordering=False, can_be_stateful=False,
attention_module=None, attention_module_kwargs=None, comment=None):
super(MultiHeadGeometryAttentionNew, self).__init__()
self.identity_map_reordering = identity_map_reordering
self.attention = ScaledDotProductGeometryAttention(d_model=d_model,
d_k=d_k, d_v=d_v, h=h, comment=comment)
self.dropout = nn.Dropout(p=dropout)
self.layer_norm = nn.LayerNorm(d_model)
self.can_be_stateful = can_be_stateful
if self.can_be_stateful:
self.register_state('running_keys', torch.zeros((0, d_model)))
self.register_state('running_values', torch.zeros((0, d_model)))
def forward(self, input_0, input_1, input_2, input_3):
primals_3 = self.attention.fc_q.weight
primals_4 = self.attention.fc_q.bias
primals_5 = self.attention.fc_k.weight
primals_6 = self.attention.fc_k.bias
primals_7 = self.attention.fc_v.weight
primals_8 = self.attention.fc_v.bias
primals_11 = self.attention.fc_o.weight
primals_12 = self.attention.fc_o.bias
primals_13 = self.layer_norm.weight
primals_14 = self.layer_norm.bias
primals_1 = input_0
primals_2 = input_1
primals_9 = input_2
primals_10 = input_3
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14])
return output[0]
|
jianqingxie/RSTNet
|
MultiHeadGeometryAttention
| false
| 15,699
|
[
"BSD-3-Clause"
] | 68
|
aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
https://github.com/jianqingxie/RSTNet/tree/aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
Sigmoid
|
import torch
import torch.nn as nn
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class Sigmoid(ActivationFunction):
def forward(self, x):
return 1 / (1 + torch.exp(-x))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_exp_mul_neg_reciprocal_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = -tmp0
tmp2 = tl_math.exp(tmp1)
tmp3 = 1.0
tmp4 = tmp2 + tmp3
tmp5 = tl.full([1], 1, tl.int32)
tmp6 = tmp5 / tmp4
tmp7 = tmp6 * tmp3
tl.store(out_ptr0 + x0, tmp7, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_exp_mul_neg_reciprocal_0[grid(256)](arg0_1,
buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class SigmoidNew(ActivationFunction):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiwidi/lightning-tutorials
|
Sigmoid
| false
| 15,700
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
DisparityConv
|
import torch
import torch.nn as nn
class DisparityConv(nn.Module):
def __init__(self, max_shift, output_nc):
super().__init__()
self.max_shift = int(max_shift)
self.conv = nn.Conv2d(self.max_shift, output_nc, kernel_size=3,
stride=1, padding=1, bias=True)
def forward(self, x):
b, c, h, w = x.shape
Unfold = nn.Unfold(kernel_size=(h, w), stride=(1, 1))
pad_clomns = x[:, :, :, 0:self.max_shift]
x_cat = torch.cat([x, pad_clomns], dim=-1)
patches = Unfold(x_cat)[:, :, 1:]
patches = patches.permute([0, 2, 1])
patches = torch.reshape(patches, [b, -1, c, h, w])
x = x.unsqueeze(dim=1)
diff = torch.abs(x - patches)
diff = torch.mean(diff, dim=2, keepdim=False)
out = self.conv(diff)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'max_shift': 4, 'output_nc': 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
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_mean_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex // 64
x4 = xindex % 16
x0 = xindex % 4
x2 = xindex // 16 % 4
x1 = xindex // 4 % 4
x5 = xindex
tmp0 = tl.load(in_ptr0 + (x4 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp14 = tl.load(in_ptr0 + (16 + x4 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp21 = tl.load(in_ptr0 + (32 + x4 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp28 = tl.load(in_ptr0 + (48 + x4 + 64 * x3), xmask, eviction_policy=
'evict_last')
tmp1 = 1 + x0 + x2
tl.full([1], 0, tl.int64)
tmp4 = tl.full([1], 4, tl.int64)
tmp5 = tmp1 < tmp4
tmp6 = tl.load(in_ptr0 + (4 * x1 + 64 * x3 + (1 + x0 + x2)), tmp5 &
xmask, eviction_policy='evict_last', other=0.0)
tmp7 = tmp1 >= tmp4
tl.full([1], 8, tl.int64)
tmp10 = tl.load(in_ptr0 + (4 * x1 + 64 * x3 + (-3 + x0 + x2)), tmp7 &
xmask, eviction_policy='evict_last', other=0.0)
tmp11 = tl.where(tmp5, tmp6, tmp10)
tmp12 = tmp0 - tmp11
tmp13 = tl_math.abs(tmp12)
tmp15 = tl.load(in_ptr0 + (16 + 4 * x1 + 16 * ((x0 + 4 * x1) // 16) +
64 * x3 + (1 + x0 + x2)), tmp5 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp16 = tl.load(in_ptr0 + (16 + 4 * x1 + 16 * ((x0 + 4 * x1) // 16) +
64 * x3 + (-3 + x0 + x2)), tmp7 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp17 = tl.where(tmp5, tmp15, tmp16)
tmp18 = tmp14 - tmp17
tmp19 = tl_math.abs(tmp18)
tmp20 = tmp13 + tmp19
tmp22 = tl.load(in_ptr0 + (32 + 4 * x1 + 16 * ((x0 + 4 * x1) // 16) +
64 * x3 + (1 + x0 + x2)), tmp5 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp23 = tl.load(in_ptr0 + (32 + 4 * x1 + 16 * ((x0 + 4 * x1) // 16) +
64 * x3 + (-3 + x0 + x2)), tmp7 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp24 = tl.where(tmp5, tmp22, tmp23)
tmp25 = tmp21 - tmp24
tmp26 = tl_math.abs(tmp25)
tmp27 = tmp20 + tmp26
tmp29 = tl.load(in_ptr0 + (48 + 4 * x1 + 16 * ((x0 + 4 * x1) // 16) +
64 * x3 + (1 + x0 + x2)), tmp5 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp30 = tl.load(in_ptr0 + (48 + 4 * x1 + 16 * ((x0 + 4 * x1) // 16) +
64 * x3 + (-3 + x0 + x2)), tmp7 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp31 = tl.where(tmp5, tmp29, tmp30)
tmp32 = tmp28 - tmp31
tmp33 = tl_math.abs(tmp32)
tmp34 = tmp27 + tmp33
tmp35 = 4.0
tmp36 = tmp34 / tmp35
tl.store(out_ptr0 + x5, tmp36, 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, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_abs_mean_sub_0[grid(256)](primals_1, buf0, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(256)](buf2, primals_3, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
return buf2, primals_2, buf0
class DisparityConvNew(nn.Module):
def __init__(self, max_shift, output_nc):
super().__init__()
self.max_shift = int(max_shift)
self.conv = nn.Conv2d(self.max_shift, output_nc, kernel_size=3,
stride=1, padding=1, bias=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]
|
jiupinjia/neural-magic-eye
|
DisparityConv
| false
| 15,701
|
[
"MIT"
] | 59
|
ded1cd4fc2194fe031f76bc3a2c307e761f70d85
|
https://github.com/jiupinjia/neural-magic-eye/tree/ded1cd4fc2194fe031f76bc3a2c307e761f70d85
|
DotRole
|
from _paritybench_helpers import _mock_config
import torch
import torch as th
import torch.nn as nn
class DotRole(nn.Module):
def __init__(self, args):
super(DotRole, self).__init__()
self.args = args
self.n_actions = args.n_actions
self.q_fc = nn.Linear(args.rnn_hidden_dim, args.action_latent_dim)
self.action_space = th.ones(args.n_actions)
def forward(self, h, action_latent):
role_key = self.q_fc(h)
role_key = role_key.unsqueeze(-1)
action_latent_reshaped = action_latent.unsqueeze(0).repeat(role_key
.shape[0], 1, 1)
q = th.bmm(action_latent_reshaped, role_key).squeeze()
return q
def update_action_space(self, new_action_space):
self.action_space = th.Tensor(new_action_space).float()
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'args': _mock_config(n_actions=4, rnn_hidden_dim=4,
action_latent_dim=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch 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_repeat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, primals_3, reinterpret_tensor(
primals_1, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_repeat_0[grid(64)](primals_4, buf1, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_4
buf2 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf1, reinterpret_tensor(buf0, (4, 4, 1), (4, 1,
1), 0), out=buf2)
del buf0
return reinterpret_tensor(buf2, (4, 4), (4, 1), 0
), primals_3, reinterpret_tensor(buf1, (4, 4, 4), (16, 1, 4), 0)
class DotRoleNew(nn.Module):
def __init__(self, args):
super(DotRoleNew, self).__init__()
self.args = args
self.n_actions = args.n_actions
self.q_fc = nn.Linear(args.rnn_hidden_dim, args.action_latent_dim)
self.action_space = th.ones(args.n_actions)
def update_action_space(self, new_action_space):
self.action_space = th.Tensor(new_action_space).float()
def forward(self, input_0, input_1):
primals_1 = self.q_fc.weight
primals_2 = self.q_fc.bias
primals_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
jk96491/SMAC
|
DotRole
| false
| 15,702
|
[
"Apache-2.0"
] | 64
|
7aaf4673b0eecafc4ab25f381eea20fc762af56a
|
https://github.com/jk96491/SMAC/tree/7aaf4673b0eecafc4ab25f381eea20fc762af56a
|
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, node_feats, adj_matrix):
"""
Args:
node_feats: Tensor with node features of shape [batch_size, num_nodes, c_in]
adj_matrix: Batch of adjacency matrices of the graph. If there is an edge from i to j,
adj_matrix[b,i,j]=1 else 0. Supports directed edges by non-symmetric matrices.
Assumes to already have added the identity connections.
Shape: [batch_size, num_nodes, num_nodes]
"""
num_neighbours = adj_matrix.sum(dim=-1, keepdims=True)
node_feats = self.projection(node_feats)
node_feats = torch.bmm(adj_matrix, node_feats)
node_feats = node_feats / num_neighbours
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]
|
jiwidi/lightning-tutorials
|
GCNLayer
| false
| 15,703
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
BarlowTwinsLoss
|
import torch
import torch.nn as nn
class BarlowTwinsLoss(nn.Module):
def __init__(self, batch_size, lambda_coeff=0.005, z_dim=128):
super().__init__()
self.z_dim = z_dim
self.batch_size = batch_size
self.lambda_coeff = lambda_coeff
def off_diagonal_ele(self, x):
n, m = x.shape
assert n == m
return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()
def forward(self, z1, z2):
z1_norm = (z1 - torch.mean(z1, dim=0)) / torch.std(z1, dim=0)
z2_norm = (z2 - torch.mean(z2, dim=0)) / torch.std(z2, dim=0)
cross_corr = torch.matmul(z1_norm.T, z2_norm) / self.batch_size
on_diag = torch.diagonal(cross_corr).add_(-1).pow_(2).sum()
off_diag = self.off_diagonal_ele(cross_corr).pow_(2).sum()
return on_diag + self.lambda_coeff * off_diag
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'batch_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_div_mean_std_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (8 + x0), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (12 + x0), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = 4.0
tmp9 = tmp7 / tmp8
tmp10 = tmp0 - tmp9
tmp11 = tmp1 - tmp9
tmp12 = tmp11 * tmp11
tmp13 = tmp2 - tmp9
tmp14 = tmp13 * tmp13
tmp15 = tmp12 + tmp14
tmp16 = tmp4 - tmp9
tmp17 = tmp16 * tmp16
tmp18 = tmp15 + tmp17
tmp19 = tmp6 - tmp9
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = 3.0
tmp23 = tmp21 / tmp22
tmp24 = libdevice.sqrt(tmp23)
tmp25 = tmp10 / tmp24
tl.store(out_ptr0 + x2, tmp25, xmask)
@triton.jit
def triton_poi_fused_div_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.25
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_2(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 + 5 * x0, xmask, eviction_policy='evict_last')
tmp1 = 0.25
tmp2 = tmp0 * tmp1
tmp3 = -1.0
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + 5 * x0, tmp4, xmask)
@triton.jit
def triton_per_fused_pow_sum_3(in_ptr0, out_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
tmp0 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last')
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.sum(tmp2, 1)[:, None]
tl.store(out_ptr1 + tl.broadcast_to(5 * r0, [XBLOCK, RBLOCK]), tmp1, None)
tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp4, None)
@triton.jit
def triton_per_fused_add_mul_sum_4(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
rnumel = 12
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, :]
rmask = rindex < rnumel
r0 = rindex
tmp0 = tl.load(in_ptr0 + (1 + 5 * (r0 // 4) + 5 * (r0 % 4 // 4) + r0 %
4), rmask, other=0.0)
tmp6 = tl.load(in_out_ptr0 + 0)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, 1])
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.where(rmask, tmp2, 0)
tmp5 = tl.sum(tmp4, 1)[:, None]
tmp8 = 0.005
tmp9 = tmp5 * tmp8
tmp10 = tmp7 + tmp9
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp10, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_mean_std_sub_0[grid(16)](arg0_1, buf0, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg0_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_div_mean_std_sub_0[grid(16)](arg1_1, buf1, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del arg1_1
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf0, (4, 4), (1, 4), 0), buf1,
out=buf2)
del buf0
buf3 = buf1
del buf1
triton_poi_fused_div_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
triton_poi_fused_add_2[grid(4)](buf2, buf3, 4, XBLOCK=4, num_warps=
1, num_stages=1)
del buf2
buf7 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_pow_sum_3[grid(1)](buf3, buf3, buf7, 1, 4, XBLOCK=
1, num_warps=2, num_stages=1)
buf9 = buf7
del buf7
triton_per_fused_add_mul_sum_4[grid(1)](buf9, buf3, 1, 12, XBLOCK=1,
num_warps=2, num_stages=1)
del buf3
return buf9,
class BarlowTwinsLossNew(nn.Module):
def __init__(self, batch_size, lambda_coeff=0.005, z_dim=128):
super().__init__()
self.z_dim = z_dim
self.batch_size = batch_size
self.lambda_coeff = lambda_coeff
def off_diagonal_ele(self, x):
n, m = x.shape
assert n == m
return x.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
jiwidi/lightning-tutorials
|
BarlowTwinsLoss
| false
| 15,704
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
Conv2dLayer
|
import math
import torch
import torch.nn.functional as F
import torch.nn as nn
def cal_width_dim_2d(input_dim, kernel_size, stride, padding=1):
return math.floor((input_dim + 2 * padding - kernel_size) / stride + 1)
class Conv2dLayer(nn.Module):
def __init__(self, input_size, in_channel, out_channel, kernel_size,
stride, dropout=0.1, batch_norm=False, residual=False,
act_func_type='relu'):
super(Conv2dLayer, self).__init__()
self.input_size = input_size
self.in_channel = in_channel
self.out_channel = out_channel
self.batch_norm = batch_norm
self.kernel_size = kernel_size
self.stride = stride
self.padding = 0, kernel_size // 2 if isinstance(self.kernel_size, int
) else kernel_size[1] // 2
self.residual = residual
self.act_func_type = act_func_type
self.conv_layer = nn.Conv2d(in_channels=in_channel, out_channels=
out_channel, kernel_size=self.kernel_size, stride=self.stride,
padding=self.padding)
self.output_size = cal_width_dim_2d(input_size, self.kernel_size if
isinstance(self.kernel_size, int) else self.kernel_size[1],
self.stride if isinstance(self.stride, int) else self.stride[1],
padding=self.padding if isinstance(self.padding, int) else self
.padding[1])
if self.batch_norm:
self.norm = nn.BatchNorm2d(out_channel)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask):
"""Forward computation.
Args:
x (FloatTensor): `[B, C_i, T, F]`
mask (IntTensor): `[B, 1, T]`
Returns:
out (FloatTensor): `[B, C_o, T', F']`
out_mask (IntTensor): `[B, 1, T]`
"""
residual = x
out = self.conv_layer(x)
out = F.relu(out)
if self.batch_norm:
out = self.norm(out)
out = self.dropout(out)
if self.residual and out.size() == residual.size():
out += residual
mask = self.return_output_mask(mask, out.size(2))
return out, mask
def return_output_mask(self, mask, t):
stride = self.stride if isinstance(self.stride, int) else self.stride[0
]
kernel_size = self.kernel_size if isinstance(self.kernel_size, int
) else self.kernel_size[0]
mask = mask[:, math.floor(kernel_size / 2)::stride][:, :t]
return mask
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'in_channel': 4, 'out_channel': 4,
'kernel_size': 4, 'stride': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_0(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 5 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, 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,), (1,))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(0, 2), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 1, 5), (20, 5, 5, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 1, 5), (20, 5, 5, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_convolution_relu_threshold_backward_0[grid(80)](buf1,
primals_3, buf2, 80, XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
return buf1, reinterpret_tensor(primals_4, (4, 1, 4, 4), (64, 16, 4, 1), 32
), primals_1, primals_2, buf2
def cal_width_dim_2d(input_dim, kernel_size, stride, padding=1):
return math.floor((input_dim + 2 * padding - kernel_size) / stride + 1)
class Conv2dLayerNew(nn.Module):
def __init__(self, input_size, in_channel, out_channel, kernel_size,
stride, dropout=0.1, batch_norm=False, residual=False,
act_func_type='relu'):
super(Conv2dLayerNew, self).__init__()
self.input_size = input_size
self.in_channel = in_channel
self.out_channel = out_channel
self.batch_norm = batch_norm
self.kernel_size = kernel_size
self.stride = stride
self.padding = 0, kernel_size // 2 if isinstance(self.kernel_size, int
) else kernel_size[1] // 2
self.residual = residual
self.act_func_type = act_func_type
self.conv_layer = nn.Conv2d(in_channels=in_channel, out_channels=
out_channel, kernel_size=self.kernel_size, stride=self.stride,
padding=self.padding)
self.output_size = cal_width_dim_2d(input_size, self.kernel_size if
isinstance(self.kernel_size, int) else self.kernel_size[1],
self.stride if isinstance(self.stride, int) else self.stride[1],
padding=self.padding if isinstance(self.padding, int) else self
.padding[1])
if self.batch_norm:
self.norm = nn.BatchNorm2d(out_channel)
self.dropout = nn.Dropout(dropout)
def return_output_mask(self, mask, t):
stride = self.stride if isinstance(self.stride, int) else self.stride[0
]
kernel_size = self.kernel_size if isinstance(self.kernel_size, int
) else self.kernel_size[0]
mask = mask[:, math.floor(kernel_size / 2)::stride][:, :t]
return mask
def forward(self, input_0, input_1):
primals_1 = self.conv_layer.weight
primals_3 = self.conv_layer.bias
primals_2 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0], output[1]
|
jiyanglii/OpenTransformer
|
Conv2dLayer
| false
| 15,705
|
[
"MIT"
] | 321
|
f37cc8cbbc96ddb67082dd2962d09303551010c8
|
https://github.com/jiyanglii/OpenTransformer/tree/f37cc8cbbc96ddb67082dd2962d09303551010c8
|
TransformerEncoderLayer
|
import torch
import torch.nn as nn
class MultiHeadAttention(nn.Module):
"""Multi-Head Attention module."""
def __init__(self, n_head=8, d_model=512, d_k=64, d_v=64, dropout=0.1,
qkv_bias=False, mask_value=0):
super().__init__()
self.mask_value = mask_value
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.scale = d_k ** -0.5
self.dim_k = n_head * d_k
self.dim_v = n_head * d_v
self.linear_q = nn.Linear(self.dim_k, self.dim_k, bias=qkv_bias)
self.linear_k = nn.Linear(self.dim_k, self.dim_k, bias=qkv_bias)
self.linear_v = nn.Linear(self.dim_v, self.dim_v, bias=qkv_bias)
self.fc = nn.Linear(self.dim_v, d_model, bias=qkv_bias)
self.attn_drop = nn.Dropout(dropout)
self.proj_drop = nn.Dropout(dropout)
def forward(self, q, k, v, mask=None):
batch_size, len_q, _ = q.size()
_, len_k, _ = k.size()
q = self.linear_q(q).view(batch_size, len_q, self.n_head, self.d_k)
k = self.linear_k(k).view(batch_size, len_k, self.n_head, self.d_k)
v = self.linear_v(v).view(batch_size, len_k, self.n_head, self.d_v)
q = q.permute(0, 2, 1, 3)
k = k.permute(0, 2, 3, 1)
v = v.permute(0, 2, 1, 3)
logits = torch.matmul(q, k) * self.scale
if mask is not None:
if mask.dim() == 3:
mask = mask.unsqueeze(1)
elif mask.dim() == 2:
mask = mask.unsqueeze(1).unsqueeze(1)
logits = logits.masked_fill(mask == self.mask_value, float('-inf'))
weights = logits.softmax(dim=-1)
weights = self.attn_drop(weights)
attn_out = torch.matmul(weights, v).transpose(1, 2)
attn_out = attn_out.reshape(batch_size, len_q, self.dim_v)
attn_out = self.fc(attn_out)
attn_out = self.proj_drop(attn_out)
return attn_out
class PositionwiseFeedForward(nn.Module):
"""A two-feed-forward-layer module."""
def __init__(self, d_in, d_hid, dropout=0.1, act_layer=nn.GELU):
super().__init__()
self.w_1 = nn.Linear(d_in, d_hid)
self.w_2 = nn.Linear(d_hid, d_in)
self.act = act_layer()
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = self.w_1(x)
x = self.act(x)
x = self.dropout(x)
x = self.w_2(x)
x = self.dropout(x)
return x
class TransformerEncoderLayer(nn.Module):
""""""
def __init__(self, d_model=512, d_inner=256, n_head=8, d_k=64, d_v=64,
dropout=0.1, qkv_bias=False, mask_value=0, act_layer=nn.GELU):
super().__init__()
self.norm1 = nn.LayerNorm(d_model)
self.attn = MultiHeadAttention(n_head, d_model, d_k, d_v, qkv_bias=
qkv_bias, dropout=dropout, mask_value=mask_value)
self.norm2 = nn.LayerNorm(d_model)
self.mlp = PositionwiseFeedForward(d_model, d_inner, dropout=
dropout, act_layer=act_layer)
def forward(self, x, mask=None):
residual = x
x = self.norm1(x)
x = residual + self.attn(x, x, x, mask)
residual = x
x = self.norm2(x)
x = residual + self.mlp(x)
return x
def get_inputs():
return [torch.rand([4, 4, 512])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import 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_native_layer_norm_0(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 512 * x0), None)
tmp21 = tl.load(in_ptr1 + r1, None, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr2 + r1, None, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = tl.broadcast_to(tmp1, [RBLOCK])
tmp5 = triton_helpers.promote_to_tensor(tl.sum(tmp3, 0))
tmp6 = tl.full([1], 512, tl.int32)
tmp7 = tmp6.to(tl.float32)
tmp8 = tmp5 / tmp7
tmp9 = tmp1 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tl.broadcast_to(tmp10, [RBLOCK])
tmp13 = triton_helpers.promote_to_tensor(tl.sum(tmp11, 0))
tmp14 = 512.0
tmp15 = tmp13 / tmp14
tmp16 = 1e-05
tmp17 = tmp15 + tmp16
tmp18 = libdevice.rsqrt(tmp17)
tmp19 = tmp0 - tmp8
tmp20 = tmp19 * tmp18
tmp22 = tmp20 * tmp21
tmp24 = tmp22 + tmp23
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp18, None)
tl.store(out_ptr1 + (r1 + 512 * x0), tmp24, None)
tl.store(out_ptr0 + x0, tmp8, None)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 64
x1 = xindex // 64 % 4
x2 = xindex // 256 % 8
x3 = xindex // 2048
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x2 + 512 * x1 + 2048 * x3), None)
tl.store(out_ptr0 + x4, tmp0, None)
@triton.jit
def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 512
y1 = yindex // 512
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 512 * x2 + 2048 * y1), xmask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, 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)
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.125
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x2, tmp17, xmask)
@triton.jit
def triton_poi_fused__softmax_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
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, 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 % 8
x2 = xindex // 512 % 4
x3 = xindex // 2048
x4 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x2 + 256 * x1 + 2048 * x3), None)
tl.store(out_ptr0 + x4, tmp0, None)
@triton.jit
def triton_per_fused_add_native_layer_norm_6(in_out_ptr0, in_ptr0, in_ptr1,
in_ptr2, in_ptr3, out_ptr0, out_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 512 * x0), None)
tmp1 = tl.load(in_ptr1 + (r1 + 512 * x0), None)
tmp23 = tl.load(in_ptr2 + r1, None, eviction_policy='evict_last')
tmp25 = tl.load(in_ptr3 + r1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [RBLOCK])
tmp5 = tl.broadcast_to(tmp3, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = tl.full([1], 512, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp3 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tmp16 = 512.0
tmp17 = tmp15 / tmp16
tmp18 = 1e-05
tmp19 = tmp17 + tmp18
tmp20 = libdevice.rsqrt(tmp19)
tmp21 = tmp2 - tmp10
tmp22 = tmp21 * tmp20
tmp24 = tmp22 * tmp23
tmp26 = tmp24 + tmp25
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp20, None)
tl.store(out_ptr1 + (r1 + 512 * x0), tmp26, None)
tl.store(out_ptr0 + x0, tmp10, None)
@triton.jit
def triton_poi_fused_gelu_7(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, None)
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, None)
@triton.jit
def triton_poi_fused_add_8(in_out_ptr0, 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)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_ptr0 + x2, None)
tmp1 = tl.load(in_ptr1 + x2, None)
tmp3 = tl.load(in_out_ptr0 + x2, None)
tmp4 = tl.load(in_ptr2 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tl.store(in_out_ptr0 + x2, 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) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 512), (2048, 512, 1))
assert_size_stride(primals_2, (512,), (1,))
assert_size_stride(primals_3, (512,), (1,))
assert_size_stride(primals_4, (512, 512), (512, 1))
assert_size_stride(primals_5, (512, 512), (512, 1))
assert_size_stride(primals_6, (512, 512), (512, 1))
assert_size_stride(primals_7, (512, 512), (512, 1))
assert_size_stride(primals_8, (512,), (1,))
assert_size_stride(primals_9, (512,), (1,))
assert_size_stride(primals_10, (256, 512), (512, 1))
assert_size_stride(primals_11, (256,), (1,))
assert_size_stride(primals_12, (512, 256), (256, 1))
assert_size_stride(primals_13, (512,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf3 = reinterpret_tensor(buf1, (4, 4, 1), (4, 1, 1), 0)
del buf1
buf4 = empty_strided_cuda((4, 4, 512), (2048, 512, 1), torch.float32)
get_raw_stream(0)
triton_per_fused_native_layer_norm_0[grid(16)](buf3, primals_1,
primals_2, primals_3, buf0, buf4, 16, 512, num_warps=4,
num_stages=1)
del primals_2
del primals_3
buf5 = empty_strided_cuda((16, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (16, 512), (512, 1), 0),
reinterpret_tensor(primals_4, (512, 512), (1, 512), 0), out=buf5)
buf6 = empty_strided_cuda((16, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (16, 512), (512, 1), 0),
reinterpret_tensor(primals_5, (512, 512), (1, 512), 0), out=buf6)
buf7 = empty_strided_cuda((16, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf4, (16, 512), (512, 1), 0),
reinterpret_tensor(primals_6, (512, 512), (1, 512), 0), out=buf7)
buf8 = empty_strided_cuda((4, 8, 4, 64), (2048, 256, 64, 1), torch.
float32)
triton_poi_fused_clone_1[grid(8192)](buf5, buf8, 8192, XBLOCK=256,
num_warps=4, num_stages=1)
buf9 = reinterpret_tensor(buf5, (4, 8, 64, 4), (2048, 256, 4, 1), 0)
del buf5
triton_poi_fused_clone_2[grid(2048, 4)](buf6, buf9, 2048, 4, XBLOCK
=4, YBLOCK=256, num_warps=4, num_stages=1)
buf10 = empty_strided_cuda((32, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf8, (32, 4, 64), (256, 64,
1), 0), reinterpret_tensor(buf9, (32, 64, 4), (256, 4, 1), 0),
out=buf10)
buf11 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32
)
triton_poi_fused__softmax_3[grid(512)](buf10, buf11, 512, XBLOCK=
256, num_warps=4, num_stages=1)
buf12 = reinterpret_tensor(buf10, (4, 8, 4, 4), (128, 16, 4, 1), 0)
del buf10
triton_poi_fused__softmax_4[grid(512)](buf11, buf12, 512, XBLOCK=
128, num_warps=4, num_stages=1)
del buf11
buf13 = reinterpret_tensor(buf6, (4, 8, 4, 64), (2048, 256, 64, 1), 0)
del buf6
triton_poi_fused_clone_1[grid(8192)](buf7, buf13, 8192, XBLOCK=256,
num_warps=4, num_stages=1)
buf14 = reinterpret_tensor(buf7, (32, 4, 64), (256, 64, 1), 0)
del buf7
extern_kernels.bmm(reinterpret_tensor(buf12, (32, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf13, (32, 4, 64), (256, 64, 1), 0),
out=buf14)
buf15 = empty_strided_cuda((4, 4, 8, 64), (2048, 512, 64, 1), torch
.float32)
triton_poi_fused_clone_5[grid(8192)](buf14, buf15, 8192, XBLOCK=256,
num_warps=4, num_stages=1)
buf16 = reinterpret_tensor(buf14, (16, 512), (512, 1), 0)
del buf14
extern_kernels.mm(reinterpret_tensor(buf15, (16, 512), (512, 1), 0),
reinterpret_tensor(primals_7, (512, 512), (1, 512), 0), out=buf16)
buf17 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
buf18 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf20 = reinterpret_tensor(buf18, (4, 4, 1), (4, 1, 1), 0)
del buf18
buf21 = empty_strided_cuda((4, 4, 512), (2048, 512, 1), torch.float32)
triton_per_fused_add_native_layer_norm_6[grid(16)](buf20, primals_1,
buf16, primals_8, primals_9, buf17, buf21, 16, 512, num_warps=4,
num_stages=1)
del primals_9
buf22 = empty_strided_cuda((16, 256), (256, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf21, (16, 512
), (512, 1), 0), reinterpret_tensor(primals_10, (512, 256), (1,
512), 0), alpha=1, beta=1, out=buf22)
del primals_11
buf23 = empty_strided_cuda((4, 4, 256), (1024, 256, 1), torch.float32)
triton_poi_fused_gelu_7[grid(4096)](buf22, buf23, 4096, XBLOCK=256,
num_warps=4, num_stages=1)
buf24 = empty_strided_cuda((16, 512), (512, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf23, (16, 256), (256, 1), 0),
reinterpret_tensor(primals_12, (256, 512), (1, 256), 0), out=buf24)
buf25 = reinterpret_tensor(buf24, (4, 4, 512), (2048, 512, 1), 0)
del buf24
triton_poi_fused_add_8[grid(8192)](buf25, primals_1, buf16,
primals_13, 8192, XBLOCK=256, num_warps=4, num_stages=1)
del primals_13
return buf25, primals_1, primals_8, buf0, buf3, reinterpret_tensor(buf4,
(16, 512), (512, 1), 0), buf12, reinterpret_tensor(buf15, (16, 512),
(512, 1), 0), buf16, buf17, buf20, reinterpret_tensor(buf21, (16,
512), (512, 1), 0), buf22, reinterpret_tensor(buf23, (16, 256), (
256, 1), 0), primals_12, primals_10, primals_7, reinterpret_tensor(
buf13, (32, 64, 4), (256, 1, 64), 0), reinterpret_tensor(buf8, (32,
64, 4), (256, 1, 64), 0), reinterpret_tensor(buf9, (32, 4, 64), (
256, 1, 4), 0), primals_6, primals_5, primals_4
class MultiHeadAttention(nn.Module):
"""Multi-Head Attention module."""
def __init__(self, n_head=8, d_model=512, d_k=64, d_v=64, dropout=0.1,
qkv_bias=False, mask_value=0):
super().__init__()
self.mask_value = mask_value
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.scale = d_k ** -0.5
self.dim_k = n_head * d_k
self.dim_v = n_head * d_v
self.linear_q = nn.Linear(self.dim_k, self.dim_k, bias=qkv_bias)
self.linear_k = nn.Linear(self.dim_k, self.dim_k, bias=qkv_bias)
self.linear_v = nn.Linear(self.dim_v, self.dim_v, bias=qkv_bias)
self.fc = nn.Linear(self.dim_v, d_model, bias=qkv_bias)
self.attn_drop = nn.Dropout(dropout)
self.proj_drop = nn.Dropout(dropout)
def forward(self, q, k, v, mask=None):
batch_size, len_q, _ = q.size()
_, len_k, _ = k.size()
q = self.linear_q(q).view(batch_size, len_q, self.n_head, self.d_k)
k = self.linear_k(k).view(batch_size, len_k, self.n_head, self.d_k)
v = self.linear_v(v).view(batch_size, len_k, self.n_head, self.d_v)
q = q.permute(0, 2, 1, 3)
k = k.permute(0, 2, 3, 1)
v = v.permute(0, 2, 1, 3)
logits = torch.matmul(q, k) * self.scale
if mask is not None:
if mask.dim() == 3:
mask = mask.unsqueeze(1)
elif mask.dim() == 2:
mask = mask.unsqueeze(1).unsqueeze(1)
logits = logits.masked_fill(mask == self.mask_value, float('-inf'))
weights = logits.softmax(dim=-1)
weights = self.attn_drop(weights)
attn_out = torch.matmul(weights, v).transpose(1, 2)
attn_out = attn_out.reshape(batch_size, len_q, self.dim_v)
attn_out = self.fc(attn_out)
attn_out = self.proj_drop(attn_out)
return attn_out
class PositionwiseFeedForward(nn.Module):
"""A two-feed-forward-layer module."""
def __init__(self, d_in, d_hid, dropout=0.1, act_layer=nn.GELU):
super().__init__()
self.w_1 = nn.Linear(d_in, d_hid)
self.w_2 = nn.Linear(d_hid, d_in)
self.act = act_layer()
self.dropout = nn.Dropout(dropout)
def forward(self, x):
x = self.w_1(x)
x = self.act(x)
x = self.dropout(x)
x = self.w_2(x)
x = self.dropout(x)
return x
class TransformerEncoderLayerNew(nn.Module):
""""""
def __init__(self, d_model=512, d_inner=256, n_head=8, d_k=64, d_v=64,
dropout=0.1, qkv_bias=False, mask_value=0, act_layer=nn.GELU):
super().__init__()
self.norm1 = nn.LayerNorm(d_model)
self.attn = MultiHeadAttention(n_head, d_model, d_k, d_v, qkv_bias=
qkv_bias, dropout=dropout, mask_value=mask_value)
self.norm2 = nn.LayerNorm(d_model)
self.mlp = PositionwiseFeedForward(d_model, d_inner, dropout=
dropout, act_layer=act_layer)
def forward(self, input_0):
primals_2 = self.norm1.weight
primals_3 = self.norm1.bias
primals_4 = self.attn.linear_q.weight
primals_5 = self.attn.linear_k.weight
primals_6 = self.attn.linear_v.weight
primals_7 = self.attn.fc.weight
primals_8 = self.norm2.weight
primals_9 = self.norm2.bias
primals_10 = self.mlp.w_1.weight
primals_11 = self.mlp.w_1.bias
primals_12 = self.mlp.w_2.weight
primals_13 = self.mlp.w_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]
|
jeffreykuang/mmocr-1
|
TransformerEncoderLayer
| false
| 15,706
|
[
"Apache-2.0"
] | 206
|
b17304edeb493b0a4d7224c23d23b952350d0db5
|
https://github.com/jeffreykuang/mmocr-1/tree/b17304edeb493b0a4d7224c23d23b952350d0db5
|
Tanh
|
import torch
import torch.nn as nn
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class Tanh(ActivationFunction):
def forward(self, x):
x_exp, neg_x_exp = torch.exp(x), torch.exp(-x)
return (x_exp - neg_x_exp) / (x_exp + neg_x_exp)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_exp_neg_sub_0(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl_math.exp(tmp0)
tmp2 = -tmp0
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 - tmp3
tmp5 = tmp1 + tmp3
tmp6 = tmp4 / tmp5
tl.store(out_ptr0 + x0, tmp6, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_exp_neg_sub_0[grid(256)](arg0_1, buf0, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ActivationFunction(nn.Module):
def __init__(self):
super().__init__()
self.name = self.__class__.__name__
self.config = {'name': self.name}
class TanhNew(ActivationFunction):
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
jiwidi/lightning-tutorials
|
Tanh
| false
| 15,707
|
[
"Apache-2.0"
] | 114
|
70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
https://github.com/jiwidi/lightning-tutorials/tree/70ba437447f345d4d6ba089d5b30fd1da2cbc04b
|
PrimaryCapsules
|
import torch
import torch.nn as nn
def squash(s, dim=-1):
"""
"Squashing" non-linearity that shrunks short vectors to almost zero length and long vectors to a length slightly below 1
Eq. (1): v_j = ||s_j||^2 / (1 + ||s_j||^2) * s_j / ||s_j||
Args:
s: Vector before activation
dim: Dimension along which to calculate the norm
Returns:
Squashed vector
"""
squared_norm = torch.sum(s ** 2, dim=dim, keepdim=True)
return squared_norm / (1 + squared_norm) * s / (torch.sqrt(squared_norm
) + 1e-08)
class PrimaryCapsules(nn.Module):
def __init__(self, in_channels, out_channels, dim_caps, kernel_size=9,
stride=2, padding=0):
"""
Initialize the layer.
Args:
in_channels: Number of input channels. 256
out_channels: Number of output channels. 256
dim_caps: Dimensionality, i.e. length, of the output capsule vector. 8
"""
super(PrimaryCapsules, self).__init__()
self.dim_caps = dim_caps
self._caps_channel = int(out_channels / dim_caps)
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=
kernel_size, stride=stride, padding=padding)
def forward(self, x):
out = self.conv(x)
out = out.view(out.size(0), self._caps_channel, out.size(2), out.
size(3), self.dim_caps)
out = out.view(out.size(0), -1, self.dim_caps)
return squash(out)
def get_inputs():
return [torch.rand([4, 4, 64, 64])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4, 'dim_caps': 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
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 12544
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 784 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_div_mul_pow_sqrt_sum_1(in_ptr0, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 12544
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp14 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tmp0 * tmp0
tmp3 = tmp2 * tmp2
tmp4 = tmp1 + tmp3
tmp6 = tmp5 * tmp5
tmp7 = tmp4 + tmp6
tmp9 = tmp8 * tmp8
tmp10 = tmp7 + tmp9
tmp11 = 1.0
tmp12 = tmp10 + tmp11
tmp13 = tmp10 / tmp12
tmp15 = tmp13 * tmp14
tmp16 = libdevice.sqrt(tmp10)
tmp17 = 1e-08
tmp18 = tmp16 + tmp17
tmp19 = tmp15 / tmp18
tl.store(out_ptr0 + x2, tmp19, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 9, 9), (324, 81, 9, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 64, 64), (16384, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2,
2), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 28, 28), (3136, 784, 28, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(12544)](buf1, primals_2, 12544,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 784, 4), (3136, 4, 1), torch.float32)
triton_poi_fused_add_div_mul_pow_sqrt_sum_1[grid(12544)](buf1, buf2,
12544, XBLOCK=256, num_warps=4, num_stages=1)
return buf2, primals_1, primals_3, buf1
def squash(s, dim=-1):
"""
"Squashing" non-linearity that shrunks short vectors to almost zero length and long vectors to a length slightly below 1
Eq. (1): v_j = ||s_j||^2 / (1 + ||s_j||^2) * s_j / ||s_j||
Args:
s: Vector before activation
dim: Dimension along which to calculate the norm
Returns:
Squashed vector
"""
squared_norm = torch.sum(s ** 2, dim=dim, keepdim=True)
return squared_norm / (1 + squared_norm) * s / (torch.sqrt(squared_norm
) + 1e-08)
class PrimaryCapsulesNew(nn.Module):
def __init__(self, in_channels, out_channels, dim_caps, kernel_size=9,
stride=2, padding=0):
"""
Initialize the layer.
Args:
in_channels: Number of input channels. 256
out_channels: Number of output channels. 256
dim_caps: Dimensionality, i.e. length, of the output capsule vector. 8
"""
super(PrimaryCapsulesNew, self).__init__()
self.dim_caps = dim_caps
self._caps_channel = int(out_channels / dim_caps)
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=
kernel_size, stride=stride, padding=padding)
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]
|
jjcao/capsule-network
|
PrimaryCapsules
| false
| 15,708
|
[
"MIT"
] | 171
|
0c2d9976b25d64720a90d3db71e5869d2592ab71
|
https://github.com/jjcao/capsule-network/tree/0c2d9976b25d64720a90d3db71e5869d2592ab71
|
MultiHeadAttention
|
from torch.nn import Module
import torch
import numpy as np
import torch.nn as nn
class ScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1, comment=None):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
self.comment = comment
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
att = torch.softmax(att, -1)
att = self.dropout(att)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class MultiHeadAttention(Module):
"""
Multi-head attention layer with Dropout and Layer Normalization.
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1,
identity_map_reordering=False, can_be_stateful=False,
attention_module=None, attention_module_kwargs=None, comment=None):
super(MultiHeadAttention, self).__init__()
self.identity_map_reordering = identity_map_reordering
self.attention = ScaledDotProductAttention(d_model=d_model, d_k=d_k,
d_v=d_v, h=h, comment=comment)
self.dropout = nn.Dropout(p=dropout)
self.layer_norm = nn.LayerNorm(d_model)
self.can_be_stateful = can_be_stateful
if self.can_be_stateful:
self.register_state('running_keys', torch.zeros((0, d_model)))
self.register_state('running_values', torch.zeros((0, d_model)))
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
if self.can_be_stateful and self._is_stateful:
self.running_keys = torch.cat([self.running_keys, keys], 1)
keys = self.running_keys
self.running_values = torch.cat([self.running_values, values], 1)
values = self.running_values
if self.identity_map_reordering:
q_norm = self.layer_norm(queries)
k_norm = self.layer_norm(keys)
v_norm = self.layer_norm(values)
out = self.attention(q_norm, k_norm, v_norm, attention_mask,
attention_weights)
out = queries + self.dropout(torch.relu(out))
else:
out = self.attention(queries, keys, values, attention_mask,
attention_weights)
out = self.dropout(out)
out = self.layer_norm(queries + out)
return out
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'d_model': 4, 'd_k': 4, 'd_v': 4, 'h': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch.nn import Module
import numpy as np
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
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_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 64
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 16
y1 = yindex // 16
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 16 * x2 + 64 * 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_sqrt_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)
tmp8 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp16 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = tl.full([1], 2.0, tl.float64)
tmp2 = tl.full([1], 0.0, tl.float64)
tmp3 = tmp1 >= tmp2
tmp4 = 1.0
tmp5 = -1.0
tmp6 = tl.where(tmp3, tmp4, tmp5)
tmp7 = tmp0 * tmp6
tmp9 = tmp8 * tmp6
tmp11 = tmp10 * tmp6
tmp12 = triton_helpers.maximum(tmp9, tmp11)
tmp14 = tmp13 * tmp6
tmp15 = triton_helpers.maximum(tmp12, tmp14)
tmp17 = tmp16 * tmp6
tmp18 = triton_helpers.maximum(tmp15, tmp17)
tmp19 = tmp7 - tmp18
tmp20 = tmp6.to(tl.float64)
tmp21 = tmp20 * tmp1
tmp22 = tmp21.to(tl.float32)
tmp23 = tmp19 / tmp22
tmp24 = tl_math.exp(tmp23)
tl.store(out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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_5(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_6(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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (16, 4), (4, 1))
assert_size_stride(primals_4, (16,), (1,))
assert_size_stride(primals_5, (16, 4), (4, 1))
assert_size_stride(primals_6, (16,), (1,))
assert_size_stride(primals_7, (16, 4), (4, 1))
assert_size_stride(primals_8, (16,), (1,))
assert_size_stride(primals_9, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_10, (4, 16), (16, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_3, (4, 16), (1, 4), 0), out=buf0)
del primals_3
buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_2, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_5, (4, 16), (1, 4), 0), out=buf1)
del primals_5
buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_9, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_7, (4, 16), (1, 4), 0), out=buf2)
del primals_7
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(256)](buf0, primals_4, buf3, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_4
buf4 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused_clone_1[grid(64, 4)](buf1, primals_6, buf4, 64, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
del primals_6
buf5 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf4, (16, 4, 4), (16, 4, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_sqrt_2[grid(256)](buf5, buf6, 256, XBLOCK
=128, num_warps=4, num_stages=1)
buf7 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
triton_poi_fused__softmax_3[grid(256)](buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf8 = buf6
del buf6
triton_poi_fused_clone_0[grid(256)](buf2, primals_8, buf8, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_8
buf9 = reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 4), (16, 4, 1), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_clone_4[grid(256)](buf9, buf10, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf9
buf11 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf10, (16, 16),
(16, 1), 0), reinterpret_tensor(primals_10, (16, 4), (1, 16), 0
), alpha=1, beta=1, out=buf11)
del primals_11
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf13 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_5[grid(16)](primals_1, buf11,
buf12, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_6[grid(64)](primals_1, buf11,
buf12, buf13, primals_12, primals_13, buf14, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf12
del buf13
del primals_13
return buf14, primals_1, primals_12, reinterpret_tensor(primals_2, (16,
4), (4, 1), 0), reinterpret_tensor(primals_9, (16, 4), (4, 1), 0
), buf7, reinterpret_tensor(buf10, (16, 16), (16, 1), 0
), buf11, primals_10, reinterpret_tensor(buf8, (16, 4, 4), (16, 1,
4), 0), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0
), reinterpret_tensor(buf4, (16, 4, 4), (16, 1, 4), 0)
class ScaledDotProductAttention(nn.Module):
"""
Scaled dot-product attention
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1, comment=None):
"""
:param d_model: Output dimensionality of the model
:param d_k: Dimensionality of queries and keys
:param d_v: Dimensionality of values
:param h: Number of heads
"""
super(ScaledDotProductAttention, self).__init__()
self.fc_q = nn.Linear(d_model, h * d_k)
self.fc_k = nn.Linear(d_model, h * d_k)
self.fc_v = nn.Linear(d_model, h * d_v)
self.fc_o = nn.Linear(h * d_v, d_model)
self.dropout = nn.Dropout(dropout)
self.d_model = d_model
self.d_k = d_k
self.d_v = d_v
self.h = h
self.init_weights()
self.comment = comment
def init_weights(self):
nn.init.xavier_uniform_(self.fc_q.weight)
nn.init.xavier_uniform_(self.fc_k.weight)
nn.init.xavier_uniform_(self.fc_v.weight)
nn.init.xavier_uniform_(self.fc_o.weight)
nn.init.constant_(self.fc_q.bias, 0)
nn.init.constant_(self.fc_k.bias, 0)
nn.init.constant_(self.fc_v.bias, 0)
nn.init.constant_(self.fc_o.bias, 0)
def forward(self, queries, keys, values, attention_mask=None,
attention_weights=None):
"""
Computes
:param queries: Queries (b_s, nq, d_model)
:param keys: Keys (b_s, nk, d_model)
:param values: Values (b_s, nk, d_model)
:param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
:param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
:return:
"""
b_s, nq = queries.shape[:2]
nk = keys.shape[1]
q = self.fc_q(queries).view(b_s, nq, self.h, self.d_k).permute(0, 2,
1, 3)
k = self.fc_k(keys).view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
v = self.fc_v(values).view(b_s, nk, self.h, self.d_v).permute(0, 2,
1, 3)
att = torch.matmul(q, k) / np.sqrt(self.d_k)
if attention_weights is not None:
att = att * attention_weights
if attention_mask is not None:
att = att.masked_fill(attention_mask, -np.inf)
att = torch.softmax(att, -1)
att = self.dropout(att)
out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
nq, self.h * self.d_v)
out = self.fc_o(out)
return out
class MultiHeadAttentionNew(Module):
"""
Multi-head attention layer with Dropout and Layer Normalization.
"""
def __init__(self, d_model, d_k, d_v, h, dropout=0.1,
identity_map_reordering=False, can_be_stateful=False,
attention_module=None, attention_module_kwargs=None, comment=None):
super(MultiHeadAttentionNew, self).__init__()
self.identity_map_reordering = identity_map_reordering
self.attention = ScaledDotProductAttention(d_model=d_model, d_k=d_k,
d_v=d_v, h=h, comment=comment)
self.dropout = nn.Dropout(p=dropout)
self.layer_norm = nn.LayerNorm(d_model)
self.can_be_stateful = can_be_stateful
if self.can_be_stateful:
self.register_state('running_keys', torch.zeros((0, d_model)))
self.register_state('running_values', torch.zeros((0, d_model)))
def forward(self, input_0, input_1, input_2):
primals_3 = self.attention.fc_q.weight
primals_4 = self.attention.fc_q.bias
primals_5 = self.attention.fc_k.weight
primals_6 = self.attention.fc_k.bias
primals_7 = self.attention.fc_v.weight
primals_8 = self.attention.fc_v.bias
primals_10 = self.attention.fc_o.weight
primals_11 = self.attention.fc_o.bias
primals_12 = self.layer_norm.weight
primals_13 = self.layer_norm.bias
primals_1 = input_0
primals_2 = 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, primals_12, primals_13])
return output[0]
|
jianqingxie/RSTNet
|
MultiHeadAttention
| false
| 15,709
|
[
"BSD-3-Clause"
] | 68
|
aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
https://github.com/jianqingxie/RSTNet/tree/aaa7b5be08e5ec9e79e14ed3e6a04fc3d50483be
|
MLP
|
import torch
import torch.nn.functional as F
import torch.nn as nn
class MLP(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
n_hid = 20
n_out = 10
self.l1 = nn.Linear(28 * 28, n_hid)
self.l2 = nn.Linear(n_hid, n_hid)
self.l3 = nn.Linear(n_hid, n_hid)
self.l4 = nn.Linear(n_hid, n_out)
def forward(self, x: 'torch.Tensor'):
x = x.view([-1, 28 * 28])
x = F.sigmoid(self.l1(x))
x = F.sigmoid(self.l2(x))
x = F.sigmoid(self.l3(x))
x = self.l4(x)
return x
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_sigmoid_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 20
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 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, (4, 784), (784, 1))
assert_size_stride(primals_2, (20, 784), (784, 1))
assert_size_stride(primals_3, (20,), (1,))
assert_size_stride(primals_4, (20, 20), (20, 1))
assert_size_stride(primals_5, (20,), (1,))
assert_size_stride(primals_6, (20, 20), (20, 1))
assert_size_stride(primals_7, (20,), (1,))
assert_size_stride(primals_8, (10, 20), (20, 1))
assert_size_stride(primals_9, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 20), (20, 1), torch.float32)
extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (784, 20
), (1, 784), 0), out=buf0)
del primals_2
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_sigmoid_0[grid(80)](buf1, primals_3, 80, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 20), (20, 1), torch.float32)
extern_kernels.mm(buf1, reinterpret_tensor(primals_4, (20, 20), (1,
20), 0), out=buf2)
buf3 = buf2
del buf2
triton_poi_fused_sigmoid_0[grid(80)](buf3, primals_5, 80, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 20), (20, 1), torch.float32)
extern_kernels.mm(buf3, reinterpret_tensor(primals_6, (20, 20), (1,
20), 0), out=buf4)
buf5 = buf4
del buf4
triton_poi_fused_sigmoid_0[grid(80)](buf5, primals_7, 80, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.addmm(primals_9, buf5, reinterpret_tensor(primals_8,
(20, 10), (1, 20), 0), alpha=1, beta=1, out=buf6)
del primals_9
return buf6, primals_1, buf1, buf3, buf5, primals_8, primals_6, primals_4
class MLPNew(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
n_hid = 20
n_out = 10
self.l1 = nn.Linear(28 * 28, n_hid)
self.l2 = nn.Linear(n_hid, n_hid)
self.l3 = nn.Linear(n_hid, n_hid)
self.l4 = nn.Linear(n_hid, n_out)
def forward(self, input_0):
primals_2 = self.l1.weight
primals_3 = self.l1.bias
primals_4 = self.l2.weight
primals_5 = self.l2.bias
primals_6 = self.l3.weight
primals_7 = self.l3.bias
primals_8 = self.l4.weight
primals_9 = self.l4.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
jjxu217/pytorch-sso
|
MLP
| false
| 15,710
|
[
"MIT"
] | 121
|
124954a5588120885e2f017c99db7fc540d5b9ab
|
https://github.com/jjxu217/pytorch-sso/tree/124954a5588120885e2f017c99db7fc540d5b9ab
|
CapsuleLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class MarginLoss(nn.Module):
def __init__(self, size_average=False, loss_lambda=0.5):
"""
Margin loss for digit existence
Eq. (4): L_k = T_k * max(0, m+ - ||v_k||)^2 + lambda * (1 - T_k) * max(0, ||v_k|| - m-)^2
Args:
size_average: should the losses be averaged (True) or summed (False) over observations for each minibatch.
loss_lambda: parameter for down-weighting the loss for missing digits
"""
super(MarginLoss, self).__init__()
self.size_average = size_average
self.m_plus = 0.9
self.m_minus = 0.1
self.loss_lambda = loss_lambda
def forward(self, inputs, labels):
L_k = labels * F.relu(self.m_plus - inputs) ** 2 + self.loss_lambda * (
1 - labels) * F.relu(inputs - self.m_minus) ** 2
L_k = L_k.sum(dim=1)
if self.size_average:
return L_k.mean()
else:
return L_k.sum()
class CapsuleLoss(nn.Module):
def __init__(self, loss_lambda=0.5, recon_loss_scale=0.0005,
size_average=False):
"""
Combined margin loss and reconstruction loss. Margin loss see above.
Sum squared error (SSE) was used as a reconstruction loss.
Args:
recon_loss_scale: param for scaling down the the reconstruction loss
size_average: if True, reconstruction loss becomes MSE instead of SSE
"""
super(CapsuleLoss, self).__init__()
self.size_average = size_average
self.margin_loss = MarginLoss(size_average=size_average,
loss_lambda=loss_lambda)
self.reconstruction_loss = nn.MSELoss(size_average=size_average)
self.recon_loss_scale = recon_loss_scale
def forward(self, inputs, labels, images, reconstructions):
margin_loss = self.margin_loss(inputs, labels)
reconstruction_loss = self.reconstruction_loss(reconstructions, images)
caps_loss = margin_loss + self.recon_loss_scale * reconstruction_loss
return caps_loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.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_per_fused_add_mul_pow_relu_rsub_sub_sum_0(in_ptr0, in_ptr1,
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 % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp18 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp19 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp32 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp33 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp46 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp47 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp2 = 0.9
tmp3 = tmp2 - tmp1
tmp4 = tl.full([1, 1], 0, tl.int32)
tmp5 = triton_helpers.maximum(tmp4, tmp3)
tmp6 = tmp5 * tmp5
tmp7 = tmp0 * tmp6
tmp8 = 1.0
tmp9 = tmp8 - tmp0
tmp10 = 0.5
tmp11 = tmp9 * tmp10
tmp12 = 0.1
tmp13 = tmp1 - tmp12
tmp14 = triton_helpers.maximum(tmp4, tmp13)
tmp15 = tmp14 * tmp14
tmp16 = tmp11 * tmp15
tmp17 = tmp7 + tmp16
tmp20 = tmp2 - tmp19
tmp21 = triton_helpers.maximum(tmp4, tmp20)
tmp22 = tmp21 * tmp21
tmp23 = tmp18 * tmp22
tmp24 = tmp8 - tmp18
tmp25 = tmp24 * tmp10
tmp26 = tmp19 - tmp12
tmp27 = triton_helpers.maximum(tmp4, tmp26)
tmp28 = tmp27 * tmp27
tmp29 = tmp25 * tmp28
tmp30 = tmp23 + tmp29
tmp31 = tmp17 + tmp30
tmp34 = tmp2 - tmp33
tmp35 = triton_helpers.maximum(tmp4, tmp34)
tmp36 = tmp35 * tmp35
tmp37 = tmp32 * tmp36
tmp38 = tmp8 - tmp32
tmp39 = tmp38 * tmp10
tmp40 = tmp33 - tmp12
tmp41 = triton_helpers.maximum(tmp4, tmp40)
tmp42 = tmp41 * tmp41
tmp43 = tmp39 * tmp42
tmp44 = tmp37 + tmp43
tmp45 = tmp31 + tmp44
tmp48 = tmp2 - tmp47
tmp49 = triton_helpers.maximum(tmp4, tmp48)
tmp50 = tmp49 * tmp49
tmp51 = tmp46 * tmp50
tmp52 = tmp8 - tmp46
tmp53 = tmp52 * tmp10
tmp54 = tmp47 - tmp12
tmp55 = triton_helpers.maximum(tmp4, tmp54)
tmp56 = tmp55 * tmp55
tmp57 = tmp53 * tmp56
tmp58 = tmp51 + tmp57
tmp59 = tmp45 + tmp58
tmp60 = tl.broadcast_to(tmp59, [XBLOCK, RBLOCK])
tmp62 = tl.sum(tmp60, 1)[:, None]
tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp62, None)
@triton.jit
def triton_per_fused_add_mse_loss_mul_1(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp7 = tl.load(in_out_ptr0 + 0)
tmp8 = tl.broadcast_to(tmp7, [1])
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp4 = tl.broadcast_to(tmp3, [RBLOCK])
tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0))
tmp9 = 0.0005
tmp10 = tmp6 * tmp9
tmp11 = tmp8 + tmp10
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp11, None)
def call(args):
arg0_1, arg1_1, arg2_1, arg3_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
get_raw_stream(0)
triton_per_fused_add_mul_pow_relu_rsub_sub_sum_0[grid(1)](arg1_1,
arg0_1, buf1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf3 = buf1
del buf1
triton_per_fused_add_mse_loss_mul_1[grid(1)](buf3, arg3_1, arg2_1,
1, 256, num_warps=2, num_stages=1)
del arg2_1
del arg3_1
return buf3,
class MarginLoss(nn.Module):
def __init__(self, size_average=False, loss_lambda=0.5):
"""
Margin loss for digit existence
Eq. (4): L_k = T_k * max(0, m+ - ||v_k||)^2 + lambda * (1 - T_k) * max(0, ||v_k|| - m-)^2
Args:
size_average: should the losses be averaged (True) or summed (False) over observations for each minibatch.
loss_lambda: parameter for down-weighting the loss for missing digits
"""
super(MarginLoss, self).__init__()
self.size_average = size_average
self.m_plus = 0.9
self.m_minus = 0.1
self.loss_lambda = loss_lambda
def forward(self, inputs, labels):
L_k = labels * F.relu(self.m_plus - inputs) ** 2 + self.loss_lambda * (
1 - labels) * F.relu(inputs - self.m_minus) ** 2
L_k = L_k.sum(dim=1)
if self.size_average:
return L_k.mean()
else:
return L_k.sum()
class CapsuleLossNew(nn.Module):
def __init__(self, loss_lambda=0.5, recon_loss_scale=0.0005,
size_average=False):
"""
Combined margin loss and reconstruction loss. Margin loss see above.
Sum squared error (SSE) was used as a reconstruction loss.
Args:
recon_loss_scale: param for scaling down the the reconstruction loss
size_average: if True, reconstruction loss becomes MSE instead of SSE
"""
super(CapsuleLossNew, self).__init__()
self.size_average = size_average
self.margin_loss = MarginLoss(size_average=size_average,
loss_lambda=loss_lambda)
self.reconstruction_loss = nn.MSELoss(size_average=size_average)
self.recon_loss_scale = recon_loss_scale
def forward(self, input_0, input_1, input_2, input_3):
arg0_1 = input_0
arg1_1 = input_1
arg2_1 = input_2
arg3_1 = input_3
output = call([arg0_1, arg1_1, arg2_1, arg3_1])
return output[0]
|
jjcao/capsule-network
|
CapsuleLoss
| false
| 15,711
|
[
"MIT"
] | 171
|
0c2d9976b25d64720a90d3db71e5869d2592ab71
|
https://github.com/jjcao/capsule-network/tree/0c2d9976b25d64720a90d3db71e5869d2592ab71
|
DotSelector
|
from _paritybench_helpers import _mock_config
import torch
import torch as th
from torch.distributions import Categorical
import torch.nn as nn
import torch.nn.functional as F
class DotSelector(nn.Module):
def __init__(self, input_shape, args):
super(DotSelector, self).__init__()
self.args = args
self.epsilon_start = self.args.epsilon_start
self.epsilon_finish = self.args.role_epsilon_finish
self.epsilon_anneal_time = self.args.epsilon_anneal_time
self.epsilon_anneal_time_exp = self.args.epsilon_anneal_time_exp
self.delta = (self.epsilon_start - self.epsilon_finish
) / self.epsilon_anneal_time
self.role_action_spaces_update_start = (self.args.
role_action_spaces_update_start)
self.epsilon_start_t = 0
self.epsilon_reset = True
self.fc1 = nn.Linear(args.rnn_hidden_dim, 2 * args.rnn_hidden_dim)
self.fc2 = nn.Linear(2 * args.rnn_hidden_dim, args.action_latent_dim)
self.epsilon = 0.05
def forward(self, inputs, role_latent):
x = self.fc2(F.relu(self.fc1(inputs)))
x = x.unsqueeze(-1)
role_latent_reshaped = role_latent.unsqueeze(0).repeat(x.shape[0], 1, 1
)
role_q = th.bmm(role_latent_reshaped, x).squeeze()
return role_q
def select_role(self, role_qs, hp, test_mode=False, t_env=None):
self.epsilon = self.epsilon_schedule(t_env)
self.calc_roleQ_by_human(hp)
if test_mode:
self.epsilon = 0.0
masked_q_values = role_qs.detach().clone()
random_numbers = th.rand_like(role_qs[:, 0])
pick_random = (random_numbers < self.epsilon).long()
random_roles = Categorical(th.ones(role_qs.shape).float()).sample(
).long()
picked_roles = pick_random * random_roles + (1 - pick_random
) * masked_q_values.max(dim=1)[1]
return picked_roles
def calc_roleQ_by_human(self, hp):
human_roleQ = []
for index1 in range(len(hp)):
for index2 in range(len(hp[index1])):
cur_hp = hp[index1, index2]
if cur_hp >= 0.85:
human_roleQ.append(th.FloatTensor([0, 0.8, 0.1, 0.1]))
elif cur_hp >= 0.7 and cur_hp < 0.85:
human_roleQ.append(th.FloatTensor([0, 0.5, 0.5, 0]))
elif cur_hp < 0.7 and cur_hp >= 0.2:
human_roleQ.append(th.FloatTensor([0.5, 0.2, 0.2, 0.1]))
else:
human_roleQ.append(th.FloatTensor([0.6, 0.2, 0.1, 0.1]))
human_roleQ = th.stack(human_roleQ, dim=0)
return human_roleQ
def epsilon_schedule(self, t_env):
if t_env is None:
return 0.05
if t_env > self.role_action_spaces_update_start and self.epsilon_reset:
self.epsilon_reset = False
self.epsilon_start_t = t_env
self.epsilon_anneal_time = self.epsilon_anneal_time_exp
self.delta = (self.epsilon_start - self.epsilon_finish
) / self.epsilon_anneal_time
if t_env - self.epsilon_start_t > self.epsilon_anneal_time:
epsilon = self.epsilon_finish
else:
epsilon = self.epsilon_start - (t_env - self.epsilon_start_t
) * self.delta
return epsilon
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'input_shape': 4, 'args': _mock_config(epsilon_start=4,
role_epsilon_finish=4, epsilon_anneal_time=4,
epsilon_anneal_time_exp=4, role_action_spaces_update_start=4,
rnn_hidden_dim=4, action_latent_dim=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch as th
from torch.distributions import Categorical
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_relu_0(in_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 = 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_repeat_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 % 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, 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, (8, 4), (4, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 8), (8, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32)
extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 8),
(1, 4), 0), out=buf0)
del primals_1
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_relu_0[grid(32)](buf1, primals_2, 32, XBLOCK=32,
num_warps=1, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, buf1, reinterpret_tensor(primals_4,
(8, 4), (1, 8), 0), alpha=1, beta=1, out=buf2)
del primals_5
buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_repeat_1[grid(64)](primals_6, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(buf3, reinterpret_tensor(buf2, (4, 4, 1), (4, 1,
1), 0), out=buf4)
del buf2
return reinterpret_tensor(buf4, (4, 4), (4, 1), 0
), primals_3, buf1, reinterpret_tensor(buf3, (4, 4, 4), (16, 1, 4), 0
), primals_4
class DotSelectorNew(nn.Module):
def __init__(self, input_shape, args):
super(DotSelectorNew, self).__init__()
self.args = args
self.epsilon_start = self.args.epsilon_start
self.epsilon_finish = self.args.role_epsilon_finish
self.epsilon_anneal_time = self.args.epsilon_anneal_time
self.epsilon_anneal_time_exp = self.args.epsilon_anneal_time_exp
self.delta = (self.epsilon_start - self.epsilon_finish
) / self.epsilon_anneal_time
self.role_action_spaces_update_start = (self.args.
role_action_spaces_update_start)
self.epsilon_start_t = 0
self.epsilon_reset = True
self.fc1 = nn.Linear(args.rnn_hidden_dim, 2 * args.rnn_hidden_dim)
self.fc2 = nn.Linear(2 * args.rnn_hidden_dim, args.action_latent_dim)
self.epsilon = 0.05
def select_role(self, role_qs, hp, test_mode=False, t_env=None):
self.epsilon = self.epsilon_schedule(t_env)
self.calc_roleQ_by_human(hp)
if test_mode:
self.epsilon = 0.0
masked_q_values = role_qs.detach().clone()
random_numbers = th.rand_like(role_qs[:, 0])
pick_random = (random_numbers < self.epsilon).long()
random_roles = Categorical(th.ones(role_qs.shape).float()).sample(
).long()
picked_roles = pick_random * random_roles + (1 - pick_random
) * masked_q_values.max(dim=1)[1]
return picked_roles
def calc_roleQ_by_human(self, hp):
human_roleQ = []
for index1 in range(len(hp)):
for index2 in range(len(hp[index1])):
cur_hp = hp[index1, index2]
if cur_hp >= 0.85:
human_roleQ.append(th.FloatTensor([0, 0.8, 0.1, 0.1]))
elif cur_hp >= 0.7 and cur_hp < 0.85:
human_roleQ.append(th.FloatTensor([0, 0.5, 0.5, 0]))
elif cur_hp < 0.7 and cur_hp >= 0.2:
human_roleQ.append(th.FloatTensor([0.5, 0.2, 0.2, 0.1]))
else:
human_roleQ.append(th.FloatTensor([0.6, 0.2, 0.1, 0.1]))
human_roleQ = th.stack(human_roleQ, dim=0)
return human_roleQ
def epsilon_schedule(self, t_env):
if t_env is None:
return 0.05
if t_env > self.role_action_spaces_update_start and self.epsilon_reset:
self.epsilon_reset = False
self.epsilon_start_t = t_env
self.epsilon_anneal_time = self.epsilon_anneal_time_exp
self.delta = (self.epsilon_start - self.epsilon_finish
) / self.epsilon_anneal_time
if t_env - self.epsilon_start_t > self.epsilon_anneal_time:
epsilon = self.epsilon_finish
else:
epsilon = self.epsilon_start - (t_env - self.epsilon_start_t
) * self.delta
return epsilon
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_3 = input_0
primals_6 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
jk96491/SMAC
|
DotSelector
| false
| 15,713
|
[
"Apache-2.0"
] | 64
|
7aaf4673b0eecafc4ab25f381eea20fc762af56a
|
https://github.com/jk96491/SMAC/tree/7aaf4673b0eecafc4ab25f381eea20fc762af56a
|
ConvRelu
|
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim
import torch.backends.cudnn
import torch.onnx
import torch.autograd
class ConvRelu(nn.Module):
"""3x3 convolution followed by ReLU activation building block."""
def __init__(self, num_in, num_out):
super().__init__()
self.block = nn.Conv2d(num_in, num_out, kernel_size=3, padding=1,
bias=False)
def forward(self, x):
return nn.functional.relu(self.block(x), inplace=True)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_in': 4, 'num_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn as nn
import torch.optim
import torch.backends.cudnn
import torch.onnx
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_relu_threshold_backward_0(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp3 = 0.0
tmp4 = tmp2 <= tmp3
tl.store(in_out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr0 + x0, tmp4, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 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_2, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1, buf2,
256, XBLOCK=256, num_warps=4, num_stages=1)
return buf1, primals_1, primals_2, buf2
class ConvReluNew(nn.Module):
"""3x3 convolution followed by ReLU activation building block."""
def __init__(self, num_in, num_out):
super().__init__()
self.block = nn.Conv2d(num_in, num_out, kernel_size=3, padding=1,
bias=False)
def forward(self, input_0):
primals_1 = self.block.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
jmargutt/automated-building-detection
|
ConvRelu
| false
| 15,714
|
[
"MIT"
] | 48
|
e1668a470b94252040f27d26098826c293fbb46d
|
https://github.com/jmargutt/automated-building-detection/tree/e1668a470b94252040f27d26098826c293fbb46d
|
ResBlockDiscriminator
|
import torch
import numpy as np
from torch import nn
from torch.nn import Parameter
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.name = name
self.power_iterations = power_iterations
if not self._made_params():
self._make_params()
def _update_u_v(self):
u = getattr(self.module, self.name + '_u')
v = getattr(self.module, self.name + '_v')
w = getattr(self.module, self.name + '_bar')
height = w.data.shape[0]
for _ in range(self.power_iterations):
v.data = l2normalize(torch.mv(torch.t(w.view(height, -1).data),
u.data))
u.data = l2normalize(torch.mv(w.view(height, -1).data, v.data))
sigma = u.dot(w.view(height, -1).mv(v))
setattr(self.module, self.name, w / sigma.expand_as(w))
def _made_params(self):
try:
getattr(self.module, self.name + '_u')
getattr(self.module, self.name + '_v')
getattr(self.module, self.name + '_bar')
return True
except AttributeError:
return False
def _make_params(self):
w = getattr(self.module, self.name)
height = w.data.shape[0]
width = w.view(height, -1).data.shape[1]
u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False)
u.data = l2normalize(u.data)
v.data = l2normalize(v.data)
w_bar = Parameter(w.data)
del self.module._parameters[self.name]
self.module.register_parameter(self.name + '_u', u)
self.module.register_parameter(self.name + '_v', v)
self.module.register_parameter(self.name + '_bar', w_bar)
def forward(self, *args):
self._update_u_v()
return self.module.forward(*args)
class ResBlockDiscriminator(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResBlockDiscriminator, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1)
nn.init.xavier_uniform_(self.conv1.weight.data, 1.0)
nn.init.xavier_uniform_(self.conv2.weight.data, 1.0)
if stride == 1:
self.model = nn.Sequential(nn.ReLU(), SpectralNorm(self.conv1),
nn.ReLU(), SpectralNorm(self.conv2))
else:
self.model = nn.Sequential(nn.ReLU(), SpectralNorm(self.conv1),
nn.ReLU(), SpectralNorm(self.conv2), nn.AvgPool2d(2, stride
=stride, padding=0))
self.bypass = nn.Sequential()
if stride != 1:
self.bypass_conv = nn.Conv2d(in_channels, out_channels, 1, 1,
padding=0)
nn.init.xavier_uniform_(self.bypass_conv.weight.data, np.sqrt(2))
self.bypass = nn.Sequential(SpectralNorm(self.bypass_conv), nn.
AvgPool2d(2, stride=stride, padding=0))
def forward(self, x):
return self.model(x) + self.bypass(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
from torch import nn
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
@triton.jit
def triton_poi_fused_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_per_fused_add_div_linalg_vector_norm_mv_1(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
rnumel = 36
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, :]
rmask = rindex < rnumel
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, rmask, other=0.0)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.load(in_ptr0 + (36 + r0), rmask, other=0.0)
tmp5 = tl.load(in_ptr1 + 1)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp9 = tl.load(in_ptr0 + (72 + r0), rmask, other=0.0)
tmp10 = tl.load(in_ptr1 + 2)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr0 + (108 + r0), rmask, other=0.0)
tmp15 = tl.load(in_ptr1 + 3)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp18 * tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp22 = tl.where(rmask, tmp20, 0)
tmp23 = tl.sum(tmp22, 1)[:, None]
tmp24 = libdevice.sqrt(tmp23)
tmp25 = 1e-12
tmp26 = tmp24 + tmp25
tmp27 = tmp18 / tmp26
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp18, rmask)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp26, None)
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp27, rmask)
@triton.jit
def triton_per_fused_div_mv_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 36
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, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 36 * x0), rmask & xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + r1, rmask, eviction_policy='evict_last', other=0.0
)
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp4 = tmp1 / tmp3
tmp5 = tmp0 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(rmask & xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tl.store(out_ptr0 + x0, tmp9, xmask)
@triton.jit
def triton_per_fused_add_div_linalg_vector_norm_3(in_ptr0, out_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.sum(tmp2, 1)[:, None]
tmp5 = libdevice.sqrt(tmp4)
tmp6 = 1e-12
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp8, None)
@triton.jit
def triton_per_fused_dot_4(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.sum(tmp3, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp5, None)
@triton.jit
def triton_poi_fused_div_5(in_ptr0, in_ptr1, 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_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 / tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_convolution_7(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x3, tmp4, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (36,), (1,))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (36,), (1,))
assert_size_stride(primals_8, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_9, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_relu_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((36,), (1,), torch.float32)
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
buf26 = empty_strided_cuda((36,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_mv_1[grid(1)](buf3,
primals_4, primals_2, buf1, buf26, 1, 36, XBLOCK=1, num_warps=2,
num_stages=1)
buf4 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_div_mv_2[grid(4)](primals_4, buf1, buf3, buf4, 4,
36, XBLOCK=1, num_warps=2, num_stages=1)
buf6 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_3[grid(1)](buf4, buf6,
1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf7 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_dot_4[grid(1)](buf6, buf4, buf7, 1, 4, XBLOCK=1,
num_warps=2, num_stages=1)
buf8 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
triton_poi_fused_div_5[grid(144)](primals_4, buf7, buf8, 144,
XBLOCK=128, num_warps=4, num_stages=1)
buf9 = extern_kernels.convolution(buf0, buf8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 4, 4), (64, 16, 4, 1))
buf10 = buf9
del buf9
triton_poi_fused_convolution_relu_6[grid(256)](buf10, primals_5,
256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf11 = empty_strided_cuda((36,), (1,), torch.float32)
buf12 = empty_strided_cuda((), (), torch.float32)
buf13 = buf12
del buf12
buf35 = empty_strided_cuda((36,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_mv_1[grid(1)](buf13,
primals_8, primals_6, buf11, buf35, 1, 36, XBLOCK=1, num_warps=
2, num_stages=1)
buf14 = buf4
del buf4
triton_per_fused_div_mv_2[grid(4)](primals_8, buf11, buf13, buf14,
4, 36, XBLOCK=1, num_warps=2, num_stages=1)
buf16 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_3[grid(1)](buf14, buf16,
1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf17 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_dot_4[grid(1)](buf16, buf14, buf17, 1, 4, XBLOCK=1,
num_warps=2, num_stages=1)
del buf14
buf18 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
triton_poi_fused_div_5[grid(144)](primals_8, buf17, buf18, 144,
XBLOCK=128, num_warps=4, num_stages=1)
buf19 = extern_kernels.convolution(buf10, buf18, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf19, (4, 4, 4, 4), (64, 16, 4, 1))
buf20 = buf19
del buf19
triton_poi_fused_add_convolution_7[grid(256)](buf20, primals_9,
primals_1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_9
buf21 = torch.ops.aten.set_.source_Tensor(primals_2, buf6)
assert_size_stride(buf21, (4,), (1,))
del buf1
buf27 = torch.ops.aten.set_.source_Tensor(primals_3, buf26)
assert_size_stride(buf27, (36,), (1,))
del primals_3
buf30 = torch.ops.aten.set_.source_Tensor(primals_6, buf16)
assert_size_stride(buf30, (4,), (1,))
del buf11
buf36 = torch.ops.aten.set_.source_Tensor(primals_7, buf35)
assert_size_stride(buf36, (36,), (1,))
del primals_7
return (buf20, buf8, buf18, primals_2, primals_4, primals_6, primals_8,
buf0, buf3, buf6, buf7, buf8, buf10, buf13, buf16, buf17, buf18)
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.name = name
self.power_iterations = power_iterations
if not self._made_params():
self._make_params()
def _update_u_v(self):
u = getattr(self.module, self.name + '_u')
v = getattr(self.module, self.name + '_v')
w = getattr(self.module, self.name + '_bar')
height = w.data.shape[0]
for _ in range(self.power_iterations):
v.data = l2normalize(torch.mv(torch.t(w.view(height, -1).data),
u.data))
u.data = l2normalize(torch.mv(w.view(height, -1).data, v.data))
sigma = u.dot(w.view(height, -1).mv(v))
setattr(self.module, self.name, w / sigma.expand_as(w))
def _made_params(self):
try:
getattr(self.module, self.name + '_u')
getattr(self.module, self.name + '_v')
getattr(self.module, self.name + '_bar')
return True
except AttributeError:
return False
def _make_params(self):
w = getattr(self.module, self.name)
height = w.data.shape[0]
width = w.view(height, -1).data.shape[1]
u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False)
u.data = l2normalize(u.data)
v.data = l2normalize(v.data)
w_bar = Parameter(w.data)
del self.module._parameters[self.name]
self.module.register_parameter(self.name + '_u', u)
self.module.register_parameter(self.name + '_v', v)
self.module.register_parameter(self.name + '_bar', w_bar)
def forward(self, *args):
self._update_u_v()
return self.module.forward(*args)
class ResBlockDiscriminatorNew(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResBlockDiscriminatorNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1)
nn.init.xavier_uniform_(self.conv1.weight.data, 1.0)
nn.init.xavier_uniform_(self.conv2.weight.data, 1.0)
if stride == 1:
self.model = nn.Sequential(nn.ReLU(), SpectralNorm(self.conv1),
nn.ReLU(), SpectralNorm(self.conv2))
else:
self.model = nn.Sequential(nn.ReLU(), SpectralNorm(self.conv1),
nn.ReLU(), SpectralNorm(self.conv2), nn.AvgPool2d(2, stride
=stride, padding=0))
self.bypass = nn.Sequential()
if stride != 1:
self.bypass_conv = nn.Conv2d(in_channels, out_channels, 1, 1,
padding=0)
nn.init.xavier_uniform_(self.bypass_conv.weight.data, np.sqrt(2))
self.bypass = nn.Sequential(SpectralNorm(self.bypass_conv), nn.
AvgPool2d(2, stride=stride, padding=0))
def forward(self, input_0):
primals_2 = self.conv1.bias
primals_5 = self.conv1.weight_u
primals_3 = self.conv1.weight_v
primals_4 = self.conv1.weight_bar
primals_6 = self.conv2.bias
primals_9 = self.conv2.weight_u
primals_7 = self.conv2.weight_v
primals_8 = self.conv2.weight_bar
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
jingyang2017/Face-and-Image-super-resolution
|
ResBlockDiscriminator
| false
| 15,715
|
[
"MIT"
] | 215
|
0351b5f7c71013f022a972306afd036f1af3a8e6
|
https://github.com/jingyang2017/Face-and-Image-super-resolution/tree/0351b5f7c71013f022a972306afd036f1af3a8e6
|
wide_basic
|
import torch
import torch.nn as nn
def get_norm(n_filters, norm):
if norm is None:
return Identity()
elif norm == 'batch':
return nn.BatchNorm2d(n_filters, momentum=0.9)
elif norm == 'instance':
return nn.InstanceNorm2d(n_filters, affine=True)
elif norm == 'layer':
return nn.GroupNorm(1, n_filters)
elif norm == 'act':
return norms.ActNorm(n_filters, False)
class Identity(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, x):
return x
class wide_basic(nn.Module):
def __init__(self, in_planes, planes, dropout_rate, stride=1, norm=None,
leak=0.2):
super(wide_basic, self).__init__()
self.lrelu = nn.LeakyReLU(leak)
self.bn1 = get_norm(in_planes, norm)
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1,
bias=True)
self.dropout = Identity() if dropout_rate == 0.0 else nn.Dropout(p=
dropout_rate)
self.bn2 = get_norm(planes, norm)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=True)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != planes:
self.shortcut = nn.Sequential(nn.Conv2d(in_planes, planes,
kernel_size=1, stride=stride, bias=True))
def forward(self, x):
out = self.dropout(self.conv1(self.lrelu(self.bn1(x))))
out = self.conv2(self.lrelu(self.bn2(out)))
out += self.shortcut(x)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_planes': 4, 'planes': 4, 'dropout_rate': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_leaky_relu_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 0.2
tmp4 = tmp0 * tmp3
tmp5 = tl.where(tmp2, tmp0, tmp4)
tl.store(out_ptr0 + x0, tmp5, xmask)
@triton.jit
def triton_poi_fused_convolution_leaky_relu_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
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_add_convolution_2(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x3, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x3, tmp4, xmask)
def call(args):
primals_1, primals_2, primals_3, 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, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(256)](primals_1, buf0, 256,
XBLOCK=256, 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, 4, 4, 4), (64, 16, 4, 1))
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_convolution_leaky_relu_1[grid(256)](buf1,
primals_3, buf2, buf3, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf1
del primals_3
buf4 = extern_kernels.convolution(buf3, 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, 4, 4, 4), (64, 16, 4, 1))
buf5 = buf4
del buf4
triton_poi_fused_add_convolution_2[grid(256)](buf5, primals_5,
primals_1, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_5
return buf5, primals_2, primals_4, buf0, buf2, buf3
def get_norm(n_filters, norm):
if norm is None:
return Identity()
elif norm == 'batch':
return nn.BatchNorm2d(n_filters, momentum=0.9)
elif norm == 'instance':
return nn.InstanceNorm2d(n_filters, affine=True)
elif norm == 'layer':
return nn.GroupNorm(1, n_filters)
elif norm == 'act':
return norms.ActNorm(n_filters, False)
class Identity(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, x):
return x
class wide_basicNew(nn.Module):
def __init__(self, in_planes, planes, dropout_rate, stride=1, norm=None,
leak=0.2):
super(wide_basicNew, self).__init__()
self.lrelu = nn.LeakyReLU(leak)
self.bn1 = get_norm(in_planes, norm)
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1,
bias=True)
self.dropout = Identity() if dropout_rate == 0.0 else nn.Dropout(p=
dropout_rate)
self.bn2 = get_norm(planes, norm)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=True)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != planes:
self.shortcut = nn.Sequential(nn.Conv2d(in_planes, planes,
kernel_size=1, stride=stride, bias=True))
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_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jliu/HDGE
|
wide_basic
| false
| 15,716
|
[
"Apache-2.0"
] | 69
|
1615d04d55ec038590fc7f18810344a8257edaa0
|
https://github.com/jliu/HDGE/tree/1615d04d55ec038590fc7f18810344a8257edaa0
|
ScaleDotProductAttention
|
import math
import torch
import torch.nn as nn
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
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
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from 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 = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = 0.5
tmp16 = tmp14 * tmp15
tmp17 = tl_math.exp(tmp16)
tl.store(out_ptr0 + x3, tmp17, 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 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x3, tmp8, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(arg1_1, (16, 4, 4), (16, 4, 1
), 0), reinterpret_tensor(arg0_1, (16, 4, 4), (16, 4, 1), 0),
out=buf0)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](buf0, buf1, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
triton_poi_fused__softmax_1[grid(256)](buf1, buf2, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf3 = reinterpret_tensor(buf1, (16, 4, 4), (16, 4, 1), 0)
del buf1
extern_kernels.bmm(reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(arg2_1, (16, 4, 4), (16, 4, 1), 0), out=buf3
)
del arg2_1
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0), buf2
class ScaleDotProductAttentionNew(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttentionNew, self).__init__()
self.softmax = nn.Softmax()
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]
|
jkimbf/transformer-1
|
ScaleDotProductAttention
| false
| 15,717
|
[
"Apache-2.0"
] | 233
|
6cd29731197822d6db641cdbfad3b045b8a294e4
|
https://github.com/jkimbf/transformer-1/tree/6cd29731197822d6db641cdbfad3b045b8a294e4
|
DecoderBlock
|
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim
import torch.backends.cudnn
import torch.onnx
import torch.autograd
class ConvRelu(nn.Module):
"""3x3 convolution followed by ReLU activation building block."""
def __init__(self, num_in, num_out):
super().__init__()
self.block = nn.Conv2d(num_in, num_out, kernel_size=3, padding=1,
bias=False)
def forward(self, x):
return nn.functional.relu(self.block(x), inplace=True)
class DecoderBlock(nn.Module):
"""Decoder building block upsampling resolution by a factor of two."""
def __init__(self, num_in, num_out):
super().__init__()
self.block = ConvRelu(num_in, num_out)
def forward(self, x):
return self.block(nn.functional.interpolate(x, scale_factor=2, mode
='nearest'))
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'num_in': 4, 'num_out': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.utils.data
import torch.nn as nn
import torch.optim
import torch.backends.cudnn
import torch.onnx
import torch.autograd
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__unsafe_index_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 8 % 8
x0 = xindex % 8
x2 = xindex // 64
x4 = xindex
tmp0 = x1
tmp1 = tmp0.to(tl.float32)
tmp2 = 0.5
tmp3 = tmp1 * tmp2
tmp4 = tmp3.to(tl.int32)
tmp5 = x0
tmp6 = tmp5.to(tl.float32)
tmp7 = tmp6 * tmp2
tmp8 = tmp7.to(tl.int32)
tmp9 = tl.load(in_ptr0 + (tmp8 + 4 * tmp4 + 16 * x2), xmask,
eviction_policy='evict_last')
tl.store(out_ptr0 + x4, tmp9, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
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, 3, 3), (36, 9, 3, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__unsafe_index_0[grid(1024)](primals_1, buf0, 1024,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 8, 8), (256, 64, 8, 1))
buf2 = buf1
del buf1
buf3 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(1024)](buf2, buf3,
1024, XBLOCK=128, num_warps=4, num_stages=1)
return buf2, primals_2, buf0, buf3
class ConvRelu(nn.Module):
"""3x3 convolution followed by ReLU activation building block."""
def __init__(self, num_in, num_out):
super().__init__()
self.block = nn.Conv2d(num_in, num_out, kernel_size=3, padding=1,
bias=False)
def forward(self, x):
return nn.functional.relu(self.block(x), inplace=True)
class DecoderBlockNew(nn.Module):
"""Decoder building block upsampling resolution by a factor of two."""
def __init__(self, num_in, num_out):
super().__init__()
self.block = ConvRelu(num_in, num_out)
def forward(self, input_0):
primals_2 = self.block.block.weight
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0]
|
jmargutt/automated-building-detection
|
DecoderBlock
| false
| 15,718
|
[
"MIT"
] | 48
|
e1668a470b94252040f27d26098826c293fbb46d
|
https://github.com/jmargutt/automated-building-detection/tree/e1668a470b94252040f27d26098826c293fbb46d
|
MultiHeadAttention
|
import math
import torch
import torch.nn as nn
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_head):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.attention = ScaleDotProductAttention()
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_concat = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)
q, k, v = self.split(q), self.split(k), self.split(v)
out, _attention = self.attention(q, k, v, mask=mask)
out = self.concat(out)
out = self.w_concat(out)
return out
def split(self, tensor):
"""
split tensor by number of head
:param tensor: [batch_size, length, d_model]
:return: [batch_size, head, length, d_tensor]
"""
batch_size, length, d_model = tensor.size()
d_tensor = d_model // self.n_head
tensor = tensor.view(batch_size, self.n_head, length, d_tensor)
return tensor
def concat(self, tensor):
"""
inverse function of self.split(tensor : torch.Tensor)
:param tensor: [batch_size, head, length, d_tensor]
:return: [batch_size, length, d_model]
"""
batch_size, head, length, d_tensor = tensor.size()
d_model = head * d_tensor
tensor = tensor.view(batch_size, length, d_model)
return tensor
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'d_model': 4, 'n_head': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp4 = tmp3 * tmp1
tmp6 = tmp5 * tmp1
tmp7 = triton_helpers.maximum(tmp4, tmp6)
tmp9 = tmp8 * tmp1
tmp10 = triton_helpers.maximum(tmp7, tmp9)
tmp12 = tmp11 * tmp1
tmp13 = triton_helpers.maximum(tmp10, tmp12)
tmp14 = tmp2 - tmp13
tmp15 = tmp14 * tmp1
tmp16 = tl_math.exp(tmp15)
tl.store(out_ptr0 + x3, tmp16, 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 = 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, 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, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (16,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (16,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_8, reinterpret_tensor(primals_9, (16,
4), (4, 1), 0), reinterpret_tensor(primals_7, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf2)
del primals_7
del primals_8
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 4, 1), (4, 1, 1),
0), reinterpret_tensor(buf1, (16, 1, 4), (4, 4, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__softmax_0[grid(256)](buf3, buf4, 256, XBLOCK=256,
num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del buf4
buf6 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0), out=buf6)
buf7 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_11, reinterpret_tensor(buf6, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf7)
del primals_11
return reinterpret_tensor(buf7, (4, 4, 4), (16, 4, 1), 0
), 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
), buf5, reinterpret_tensor(buf6, (16, 4), (4, 1), 0
), primals_10, reinterpret_tensor(buf2, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf0, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 4), 0)
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
class MultiHeadAttentionNew(nn.Module):
def __init__(self, d_model, n_head):
super(MultiHeadAttentionNew, self).__init__()
self.n_head = n_head
self.attention = ScaleDotProductAttention()
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_concat = nn.Linear(d_model, d_model)
def split(self, tensor):
"""
split tensor by number of head
:param tensor: [batch_size, length, d_model]
:return: [batch_size, head, length, d_tensor]
"""
batch_size, length, d_model = tensor.size()
d_tensor = d_model // self.n_head
tensor = tensor.view(batch_size, self.n_head, length, d_tensor)
return tensor
def concat(self, tensor):
"""
inverse function of self.split(tensor : torch.Tensor)
:param tensor: [batch_size, head, length, d_tensor]
:return: [batch_size, length, d_model]
"""
batch_size, head, length, d_tensor = tensor.size()
d_model = head * d_tensor
tensor = tensor.view(batch_size, length, d_model)
return tensor
def forward(self, input_0, input_1, input_2):
primals_1 = self.w_q.weight
primals_2 = self.w_q.bias
primals_4 = self.w_k.weight
primals_5 = self.w_k.bias
primals_7 = self.w_v.weight
primals_8 = self.w_v.bias
primals_10 = self.w_concat.weight
primals_11 = self.w_concat.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]
|
jkimbf/transformer-1
|
MultiHeadAttention
| false
| 15,719
|
[
"Apache-2.0"
] | 233
|
6cd29731197822d6db641cdbfad3b045b8a294e4
|
https://github.com/jkimbf/transformer-1/tree/6cd29731197822d6db641cdbfad3b045b8a294e4
|
EncoderSteenkiste
|
import torch
from torch import nn
class EncoderSteenkiste(nn.Module):
def __init__(self, signal_size, latent_dim=10):
"""
Parameters
----------
signal_size : int for length of signal. Defaults to 30
latent_dim : int
Dimensionality of latent output.
Model Architecture (transposed for decoder)
------------
- 4 convolutional layers (each with 32 channels), (4 x 4 kernel), (stride of 2)
- 2 fully connected layers (each of 256 units)
- Latent distribution:
- 1 fully connected layer of 20 units (log variance and mean for 10 Gaussians)
References:
[1] Burgess, Christopher P., et al. "Understanding disentangling in
$\\beta$-VAE." arXiv preprint arXiv:1804.03599 (2018).
"""
super(EncoderSteenkiste, self).__init__()
hidden_dim1 = 50
hidden_dim2 = 20
self.latent_dim = latent_dim
self.img_size = signal_size
signal_length = signal_size[2]
self.lin1 = nn.Linear(signal_length, hidden_dim1)
self.lin2 = nn.Linear(hidden_dim1, hidden_dim2)
self.lin3 = nn.Linear(hidden_dim2, latent_dim)
self.mu_logvar_gen = nn.Linear(latent_dim, self.latent_dim * 2)
def forward(self, x):
x = torch.relu(self.lin1(x))
x = torch.relu(self.lin2(x))
x = torch.relu(self.lin3(x))
mu_logvar = self.mu_logvar_gen(x)
mu, logvar = mu_logvar.view(-1, self.latent_dim, 2).unbind(-1)
return mu, logvar
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'signal_size': [4, 4, 4]}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
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 = 3200
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 50
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_1(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1280
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 20
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_2(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 640
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 10
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9) = args
args.clear()
assert_size_stride(primals_1, (50, 4), (4, 1))
assert_size_stride(primals_2, (50,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (20, 50), (50, 1))
assert_size_stride(primals_5, (20,), (1,))
assert_size_stride(primals_6, (10, 20), (20, 1))
assert_size_stride(primals_7, (10,), (1,))
assert_size_stride(primals_8, (20, 10), (10, 1))
assert_size_stride(primals_9, (20,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 50), (50, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_1, (4, 50), (1, 4), 0), out=buf0)
del primals_1
buf1 = reinterpret_tensor(buf0, (4, 4, 4, 50), (800, 200, 50, 1), 0)
del buf0
buf9 = empty_strided_cuda((4, 4, 4, 50), (800, 200, 50, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(3200)](buf1,
primals_2, buf9, 3200, XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = empty_strided_cuda((64, 20), (20, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (64, 50), (50, 1), 0),
reinterpret_tensor(primals_4, (50, 20), (1, 50), 0), out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 20), (320, 80, 20, 1), 0)
del buf2
buf8 = empty_strided_cuda((4, 4, 4, 20), (320, 80, 20, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_1[grid(1280)](buf3,
primals_5, buf8, 1280, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((64, 10), (10, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf3, (64, 20), (20, 1), 0),
reinterpret_tensor(primals_6, (20, 10), (1, 20), 0), out=buf4)
buf5 = reinterpret_tensor(buf4, (4, 4, 4, 10), (160, 40, 10, 1), 0)
del buf4
buf7 = empty_strided_cuda((4, 4, 4, 10), (160, 40, 10, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_2[grid(640)](buf5,
primals_7, buf7, 640, XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf6 = empty_strided_cuda((64, 20), (20, 1), torch.float32)
extern_kernels.addmm(primals_9, reinterpret_tensor(buf5, (64, 10),
(10, 1), 0), reinterpret_tensor(primals_8, (10, 20), (1, 10), 0
), alpha=1, beta=1, out=buf6)
del primals_9
return reinterpret_tensor(buf6, (64, 10), (20, 2), 0), reinterpret_tensor(
buf6, (64, 10), (20, 2), 1), reinterpret_tensor(primals_3, (64, 4),
(4, 1), 0), reinterpret_tensor(buf1, (64, 50), (50, 1), 0
), reinterpret_tensor(buf3, (64, 20), (20, 1), 0), reinterpret_tensor(
buf5, (64, 10), (10, 1), 0
), primals_8, buf7, primals_6, buf8, primals_4, buf9
class EncoderSteenkisteNew(nn.Module):
def __init__(self, signal_size, latent_dim=10):
"""
Parameters
----------
signal_size : int for length of signal. Defaults to 30
latent_dim : int
Dimensionality of latent output.
Model Architecture (transposed for decoder)
------------
- 4 convolutional layers (each with 32 channels), (4 x 4 kernel), (stride of 2)
- 2 fully connected layers (each of 256 units)
- Latent distribution:
- 1 fully connected layer of 20 units (log variance and mean for 10 Gaussians)
References:
[1] Burgess, Christopher P., et al. "Understanding disentangling in
$\\beta$-VAE." arXiv preprint arXiv:1804.03599 (2018).
"""
super(EncoderSteenkisteNew, self).__init__()
hidden_dim1 = 50
hidden_dim2 = 20
self.latent_dim = latent_dim
self.img_size = signal_size
signal_length = signal_size[2]
self.lin1 = nn.Linear(signal_length, hidden_dim1)
self.lin2 = nn.Linear(hidden_dim1, hidden_dim2)
self.lin3 = nn.Linear(hidden_dim2, latent_dim)
self.mu_logvar_gen = nn.Linear(latent_dim, self.latent_dim * 2)
def forward(self, input_0):
primals_1 = self.lin1.weight
primals_2 = self.lin1.bias
primals_4 = self.lin2.weight
primals_5 = self.lin2.bias
primals_6 = self.lin3.weight
primals_7 = self.lin3.bias
primals_8 = self.mu_logvar_gen.weight
primals_9 = self.mu_logvar_gen.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0], output[1]
|
jnsrch/disentangling-vae-cwt
|
EncoderSteenkiste
| false
| 15,720
|
[
"MIT"
] | 581
|
0e927bdcd3d149cadb30aa107331f0c071138c41
|
https://github.com/jnsrch/disentangling-vae-cwt/tree/0e927bdcd3d149cadb30aa107331f0c071138c41
|
ConvNet
|
import torch
import torch.nn as nn
class ConvNet(nn.Module):
"""
A network with a single convolution layer. This is used for testing flop
count for convolution layers.
"""
def __init__(self, conv_dim: 'int', input_dim: 'int', output_dim: 'int',
kernel_size: 'int', spatial_dim: 'int', stride: 'int', padding:
'int', groups_num: 'int') ->None:
super(ConvNet, self).__init__()
if conv_dim == 1:
convLayer = nn.Conv1d
elif conv_dim == 2:
convLayer = nn.Conv2d
else:
convLayer = nn.Conv3d
self.conv = convLayer(input_dim, output_dim, kernel_size, stride,
padding, groups=groups_num)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'conv_dim': 4, 'input_dim': 4, 'output_dim': 4,
'kernel_size': 4, 'spatial_dim': 4, 'stride': 1, 'padding': 4,
'groups_num': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
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 = 2916
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 729
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, 4, 4), (256, 64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(1, 1,
1), padding=(4, 4, 4), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 9, 9, 9), (2916, 729, 81, 9, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(2916)](buf1, primals_2, 2916,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 9, 9, 9), (729, 81, 9, 1), 0
), primals_1, reinterpret_tensor(primals_3, (1, 4, 4, 4, 4), (256,
64, 16, 4, 1), 0)
class ConvNetNew(nn.Module):
"""
A network with a single convolution layer. This is used for testing flop
count for convolution layers.
"""
def __init__(self, conv_dim: 'int', input_dim: 'int', output_dim: 'int',
kernel_size: 'int', spatial_dim: 'int', stride: 'int', padding:
'int', groups_num: 'int') ->None:
super(ConvNetNew, self).__init__()
if conv_dim == 1:
convLayer = nn.Conv1d
elif conv_dim == 2:
convLayer = nn.Conv2d
else:
convLayer = nn.Conv3d
self.conv = convLayer(input_dim, output_dim, kernel_size, stride,
padding, groups=groups_num)
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]
|
johnanthonyjose/fvcore
|
ConvNet
| false
| 15,721
|
[
"Apache-2.0"
] | 1,137
|
af30fd4028553c1d1e4e5d389f309f52e046e67d
|
https://github.com/johnanthonyjose/fvcore/tree/af30fd4028553c1d1e4e5d389f309f52e046e67d
|
ThreeNet
|
import torch
import torch.nn as nn
class ThreeNet(nn.Module):
"""
A network with three layers. This is used for testing a network with more
than one operation. The network has a convolution layer followed by two
fully connected layers.
"""
def __init__(self, input_dim: 'int', conv_dim: 'int', linear_dim: 'int'
) ->None:
super(ThreeNet, self).__init__()
self.conv = nn.Conv2d(input_dim, conv_dim, 1, 1)
out_dim = 1
self.pool = nn.AdaptiveAvgPool2d((out_dim, out_dim))
self.linear1 = nn.Linear(conv_dim, linear_dim)
self.linear2 = nn.Linear(linear_dim, 1)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv(x)
x = self.pool(x)
x = torch.flatten(x, 1)
x = self.linear1(x)
x = self.linear2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'conv_dim': 4, 'linear_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_convolution_mean_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
xnumel = 16
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r2 = rindex
x3 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + (r2 + 16 * x3), xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.where(xmask, tmp3, 0)
tmp6 = tl.sum(tmp5, 1)[:, None]
tmp7 = 16.0
tmp8 = tmp6 / tmp7
tl.debug_barrier()
tl.store(in_out_ptr0 + x3, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4), (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 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_convolution_mean_0[grid(16)](buf2, buf0, primals_2,
16, 16, XBLOCK=1, num_warps=2, num_stages=1)
del buf0
del primals_2
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (4, 4), (4,
1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha
=1, beta=1, out=buf3)
del primals_5
buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_7, buf3, reinterpret_tensor(primals_6,
(4, 1), (1, 4), 0), alpha=1, beta=1, out=buf5)
del primals_7
return buf5, primals_1, primals_3, reinterpret_tensor(buf2, (4, 4), (4,
1), 0), buf3, primals_6, primals_4
class ThreeNetNew(nn.Module):
"""
A network with three layers. This is used for testing a network with more
than one operation. The network has a convolution layer followed by two
fully connected layers.
"""
def __init__(self, input_dim: 'int', conv_dim: 'int', linear_dim: 'int'
) ->None:
super(ThreeNetNew, self).__init__()
self.conv = nn.Conv2d(input_dim, conv_dim, 1, 1)
out_dim = 1
self.pool = nn.AdaptiveAvgPool2d((out_dim, out_dim))
self.linear1 = nn.Linear(conv_dim, linear_dim)
self.linear2 = nn.Linear(linear_dim, 1)
def forward(self, input_0):
primals_1 = self.conv.weight
primals_2 = self.conv.bias
primals_4 = self.linear1.weight
primals_5 = self.linear1.bias
primals_6 = self.linear2.weight
primals_7 = self.linear2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
johnanthonyjose/fvcore
|
ThreeNet
| false
| 15,722
|
[
"Apache-2.0"
] | 1,137
|
af30fd4028553c1d1e4e5d389f309f52e046e67d
|
https://github.com/johnanthonyjose/fvcore/tree/af30fd4028553c1d1e4e5d389f309f52e046e67d
|
NestedNetInnerModule
|
import torch
import torch.nn as nn
from typing import Counter
from collections import Counter
class NestedNetInnerModule(nn.Module):
"""
A submodule for the nested net test module below.
"""
def __init__(self, lin_op: 'str'='addmm') ->None:
super().__init__()
conv_input_size = 2, 5
conv_in = 2
conv_out = 2
kernel_size = 1
padding = 0
fc_in = 10
fc_out = 10
self.conv = nn.Conv1d(in_channels=conv_in, out_channels=conv_out,
kernel_size=kernel_size, padding=padding)
self.fc = nn.Linear(in_features=fc_in, out_features=fc_out)
fc_flops = fc_in * fc_out
fc_flops = Counter({lin_op: fc_flops})
spatial_pos = conv_input_size[1] + 2 * padding - 2 * (kernel_size // 2)
conv_flops = spatial_pos * kernel_size * conv_in * conv_out
conv_flops = Counter({'conv': conv_flops})
model_flops = conv_flops + fc_flops
self.flops = {'': model_flops, 'fc': fc_flops, 'conv': conv_flops}
self.name_to_module = {'': self, 'fc': self.fc, 'conv': self.conv}
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = x.reshape(-1, 2, 5)
x = self.conv(x)
x = torch.flatten(x, 1)
x = 3 * self.fc(x) + 1
return x
def get_inputs():
return [torch.rand([4, 2, 5])]
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
from typing import Counter
from collections import Counter
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 40
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 5 % 2
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_mul_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 40
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 10
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 3.0
tmp4 = tmp2 * tmp3
tmp5 = 1.0
tmp6 = tmp4 + tmp5
tl.store(in_out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 2, 5), (10, 5, 1))
assert_size_stride(primals_2, (2, 2, 1), (2, 1, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (10, 10), (10, 1))
assert_size_stride(primals_5, (10,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 2, 5), (10, 5, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(40)](buf1, primals_3, 40,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((4, 10), (10, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf1, (4, 10), (10, 1), 0),
reinterpret_tensor(primals_4, (10, 10), (1, 10), 0), out=buf2)
buf3 = buf2
del buf2
triton_poi_fused_add_mul_1[grid(40)](buf3, primals_5, 40, XBLOCK=64,
num_warps=1, num_stages=1)
del primals_5
return buf3, primals_2, primals_1, reinterpret_tensor(buf1, (4, 10), (
10, 1), 0), primals_4
class NestedNetInnerModuleNew(nn.Module):
"""
A submodule for the nested net test module below.
"""
def __init__(self, lin_op: 'str'='addmm') ->None:
super().__init__()
conv_input_size = 2, 5
conv_in = 2
conv_out = 2
kernel_size = 1
padding = 0
fc_in = 10
fc_out = 10
self.conv = nn.Conv1d(in_channels=conv_in, out_channels=conv_out,
kernel_size=kernel_size, padding=padding)
self.fc = nn.Linear(in_features=fc_in, out_features=fc_out)
fc_flops = fc_in * fc_out
fc_flops = Counter({lin_op: fc_flops})
spatial_pos = conv_input_size[1] + 2 * padding - 2 * (kernel_size // 2)
conv_flops = spatial_pos * kernel_size * conv_in * conv_out
conv_flops = Counter({'conv': conv_flops})
model_flops = conv_flops + fc_flops
self.flops = {'': model_flops, 'fc': fc_flops, 'conv': conv_flops}
self.name_to_module = {'': self, 'fc': self.fc, 'conv': self.conv}
def forward(self, input_0):
primals_2 = self.conv.weight
primals_3 = self.conv.bias
primals_4 = self.fc.weight
primals_5 = self.fc.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
johnanthonyjose/fvcore
|
NestedNetInnerModule
| false
| 15,723
|
[
"Apache-2.0"
] | 1,137
|
af30fd4028553c1d1e4e5d389f309f52e046e67d
|
https://github.com/johnanthonyjose/fvcore/tree/af30fd4028553c1d1e4e5d389f309f52e046e67d
|
MemoryMoCo
|
import math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
class MemoryMoCo(nn.Module):
"""Fixed-size queue with momentum encoder"""
def __init__(self, feature_dim, queue_size, temperature=0.07, thresh=0):
super(MemoryMoCo, self).__init__()
self.queue_size = queue_size
self.temperature = temperature
self.index = 0
self.thresh = thresh
self.register_buffer('params', torch.tensor([-1]))
stdv = 1.0 / math.sqrt(feature_dim / 3)
memory = torch.rand(self.queue_size, feature_dim, requires_grad=False
).mul_(2 * stdv).add_(-stdv)
self.register_buffer('memory', memory)
def forward(self, q, k, k_all, update=False):
k = k.detach()
l_pos = (q * k).sum(dim=-1, keepdim=True)
l_neg = torch.mm(q, self.memory.clone().detach().t())
if self.thresh != 0:
prob_pos1 = l_pos
prob_pos_hard1 = prob_pos1 - self.thresh
N = l_pos.size(0)
Q = l_neg.size(1)
prob_pos_hard1 = torch.add(l_neg, -1, prob_pos_hard1.expand(N, Q))
l_neg[prob_pos_hard1 < 0] = 0
l_neg[l_neg <= 0].size(0) / N / Q
None
out = torch.cat((l_pos, l_neg), dim=1)
out = torch.div(out, self.temperature).contiguous()
if update:
with torch.no_grad():
all_size = k_all.shape[0]
out_ids = torch.fmod(torch.arange(all_size, dtype=torch.
long) + self.index, self.queue_size)
self.memory.index_copy_(0, out_ids, k_all)
self.index = (self.index + all_size) % self.queue_size
return out
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'feature_dim': 4, 'queue_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 math
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_div_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
xnumel, XBLOCK: tl.constexpr):
xnumel = 20
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x1 = xindex // 5
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 1, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + 4 * x1, tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + 4 * x1, tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tmp5 * tmp6
tmp8 = tl.load(in_ptr0 + (1 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp9 = tl.load(in_ptr1 + (1 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp10 = tmp8 * tmp9
tmp11 = tmp7 + tmp10
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp13 = tl.load(in_ptr1 + (2 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp14 = tmp12 * tmp13
tmp15 = tmp11 + tmp14
tmp16 = tl.load(in_ptr0 + (3 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp17 = tl.load(in_ptr1 + (3 + 4 * x1), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp18 = tmp16 * tmp17
tmp19 = tmp15 + tmp18
tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype)
tmp21 = tl.where(tmp4, tmp19, tmp20)
tmp22 = tmp0 >= tmp3
tl.full([1], 5, tl.int64)
tmp25 = tl.load(in_ptr2 + (4 * x1 + (-1 + x0)), tmp22 & xmask,
eviction_policy='evict_last', other=0.0)
tmp26 = tl.where(tmp4, tmp21, tmp25)
tmp27 = 14.285714285714285
tmp28 = tmp26 * tmp27
tl.store(in_out_ptr0 + x2, tmp28, xmask)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
assert_size_stride(arg2_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(arg1_1, reinterpret_tensor(arg2_1, (4, 4), (1, 4),
0), out=buf0)
del arg2_1
buf1 = empty_strided_cuda((4, 5), (5, 1), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_poi_fused_cat_div_0[grid(20)](buf2, arg1_1, arg0_1, buf0, 20,
XBLOCK=32, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
del buf0
return buf2,
class MemoryMoCoNew(nn.Module):
"""Fixed-size queue with momentum encoder"""
def __init__(self, feature_dim, queue_size, temperature=0.07, thresh=0):
super(MemoryMoCoNew, self).__init__()
self.queue_size = queue_size
self.temperature = temperature
self.index = 0
self.thresh = thresh
self.register_buffer('params', torch.tensor([-1]))
stdv = 1.0 / math.sqrt(feature_dim / 3)
memory = torch.rand(self.queue_size, feature_dim, requires_grad=False
).mul_(2 * stdv).add_(-stdv)
self.register_buffer('memory', memory)
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]
|
john-mlr/CLD-UnsupervisedLearning
|
MemoryMoCo
| false
| 15,724
|
[
"MIT"
] | 70
|
e0cf57dd62ffdcb702d6006278899d20f1d813d6
|
https://github.com/john-mlr/CLD-UnsupervisedLearning/tree/e0cf57dd62ffdcb702d6006278899d20f1d813d6
|
SmallConvNet
|
import torch
from typing import Tuple
import torch.nn as nn
from numpy import prod
class SmallConvNet(nn.Module):
"""
A network with three conv layers. This is used for testing convolution
layers for activation count.
"""
def __init__(self, input_dim: 'int') ->None:
super(SmallConvNet, self).__init__()
conv_dim1 = 8
conv_dim2 = 4
conv_dim3 = 2
self.conv1 = nn.Conv2d(input_dim, conv_dim1, 1, 1)
self.conv2 = nn.Conv2d(conv_dim1, conv_dim2, 1, 2)
self.conv3 = nn.Conv2d(conv_dim2, conv_dim3, 1, 2)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
return x
def get_gt_activation(self, x: 'torch.Tensor') ->Tuple[int, int, int]:
x = self.conv1(x)
count1 = prod(list(x.size()))
x = self.conv2(x)
count2 = prod(list(x.size()))
x = self.conv3(x)
count3 = prod(list(x.size()))
return count1, count2, count3
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 typing import Tuple
import torch.nn as nn
from numpy import prod
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 = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 8
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 2
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, 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, (8, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_2, (8,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 8, 1, 1), (8, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_7, (2,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 8, 4, 4), (128, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(512)](buf1, primals_2, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 2, 2), (16, 4, 2, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(64)](buf3, primals_5, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(2, 2),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 2, 1, 1), (2, 1, 1, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_2[grid(8)](buf5, primals_7, 8, XBLOCK=
8, num_warps=1, num_stages=1)
del primals_7
return buf5, primals_1, primals_3, primals_4, primals_6, buf1, buf3
class SmallConvNetNew(nn.Module):
"""
A network with three conv layers. This is used for testing convolution
layers for activation count.
"""
def __init__(self, input_dim: 'int') ->None:
super(SmallConvNetNew, self).__init__()
conv_dim1 = 8
conv_dim2 = 4
conv_dim3 = 2
self.conv1 = nn.Conv2d(input_dim, conv_dim1, 1, 1)
self.conv2 = nn.Conv2d(conv_dim1, conv_dim2, 1, 2)
self.conv3 = nn.Conv2d(conv_dim2, conv_dim3, 1, 2)
def get_gt_activation(self, x: 'torch.Tensor') ->Tuple[int, int, int]:
x = self.conv1(x)
count1 = prod(list(x.size()))
x = self.conv2(x)
count2 = prod(list(x.size()))
x = self.conv3(x)
count3 = prod(list(x.size()))
return count1, count2, count3
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_6 = self.conv3.weight
primals_7 = self.conv3.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
johnanthonyjose/fvcore
|
SmallConvNet
| false
| 15,725
|
[
"Apache-2.0"
] | 1,137
|
af30fd4028553c1d1e4e5d389f309f52e046e67d
|
https://github.com/johnanthonyjose/fvcore/tree/af30fd4028553c1d1e4e5d389f309f52e046e67d
|
GAT
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphAttentionLayer(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttentionLayer, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
self.W = nn.Parameter(torch.empty(size=(in_features, out_features)))
nn.init.xavier_uniform_(self.W.data, gain=1.414)
self.a = nn.Parameter(torch.empty(size=(2 * out_features, 1)))
nn.init.xavier_uniform_(self.a.data, gain=1.414)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, h, adj):
Wh = torch.mm(h, self.W)
a_input = self._prepare_attentional_mechanism_input(Wh)
e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))
zero_vec = -9000000000000000.0 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, Wh)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def _prepare_attentional_mechanism_input(self, Wh):
N = Wh.size()[0]
Wh_repeated_in_chunks = Wh.repeat_interleave(N, dim=0)
Wh_repeated_alternating = Wh.repeat(N, 1)
all_combinations_matrix = torch.cat([Wh_repeated_in_chunks,
Wh_repeated_alternating], dim=1)
return all_combinations_matrix.view(N, N, 2 * self.out_features)
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GAT(nn.Module):
def __init__(self, nfeat, nhid, output, dropout, alpha, nheads):
"""Dense version of GAT."""
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout,
alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
self.out_att = GraphAttentionLayer(nhid * nheads, output, dropout=
dropout, alpha=alpha, concat=False)
def forward(self, state, adj):
x = F.dropout(state, self.dropout, training=self.training)
x = torch.cat([att(x, adj) for att in self.attentions], dim=1)
x = F.dropout(x, self.dropout, training=self.training)
gat_state = F.elu(self.out_att(x, adj))
return gat_state
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'nfeat': 4, 'nhid': 4, 'output': 4, 'dropout': 0.5,
'alpha': 4, 'nheads': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import 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_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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 // 4) + x0), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr0 + (4 * (x1 % 4) + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x2, tmp10, xmask)
@triton.jit
def triton_poi_fused_leaky_relu_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_leaky_relu_mul_where_2(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, out_ptr0,
out_ptr1, out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6, out_ptr7,
xnumel, XBLOCK: tl.constexpr):
xnumel = 4
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp2 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp9 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp10 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp16 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp17 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp23 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp24 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp40 = tl.load(in_ptr3 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp41 = tl.load(in_ptr4 + 4 * x0, xmask, eviction_policy='evict_last')
tmp45 = tl.load(in_ptr3 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp46 = tl.load(in_ptr4 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp51 = tl.load(in_ptr3 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp52 = tl.load(in_ptr4 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp57 = tl.load(in_ptr3 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp58 = tl.load(in_ptr4 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp74 = tl.load(in_ptr5 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp75 = tl.load(in_ptr6 + 4 * x0, xmask, eviction_policy='evict_last')
tmp79 = tl.load(in_ptr5 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp80 = tl.load(in_ptr6 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp85 = tl.load(in_ptr5 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp86 = tl.load(in_ptr6 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp91 = tl.load(in_ptr5 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp92 = tl.load(in_ptr6 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp108 = tl.load(in_ptr7 + 4 * x0, xmask, eviction_policy='evict_last').to(
tl.int1)
tmp109 = tl.load(in_ptr8 + 4 * x0, xmask, eviction_policy='evict_last')
tmp113 = tl.load(in_ptr7 + (1 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp114 = tl.load(in_ptr8 + (1 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp119 = tl.load(in_ptr7 + (2 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp120 = tl.load(in_ptr8 + (2 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp125 = tl.load(in_ptr7 + (3 + 4 * x0), xmask, eviction_policy=
'evict_last').to(tl.int1)
tmp126 = tl.load(in_ptr8 + (3 + 4 * x0), xmask, eviction_policy=
'evict_last')
tmp3 = 4.0
tmp4 = tmp2 * tmp3
tmp5 = tl.where(tmp1, tmp2, tmp4)
tmp6 = -8999999815811072.0
tmp7 = tl.where(tmp0, tmp5, tmp6)
tmp11 = tmp10 * tmp3
tmp12 = tl.where(tmp9, tmp10, tmp11)
tmp13 = tl.where(tmp8, tmp12, tmp6)
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp18 = tmp17 * tmp3
tmp19 = tl.where(tmp16, tmp17, tmp18)
tmp20 = tl.where(tmp15, tmp19, tmp6)
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp25 = tmp24 * tmp3
tmp26 = tl.where(tmp23, tmp24, tmp25)
tmp27 = tl.where(tmp22, tmp26, tmp6)
tmp28 = triton_helpers.maximum(tmp21, tmp27)
tmp29 = tmp7 - tmp28
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp13 - tmp28
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp30 + tmp32
tmp34 = tmp20 - tmp28
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp33 + tmp35
tmp37 = tmp27 - tmp28
tmp38 = tl_math.exp(tmp37)
tmp39 = tmp36 + tmp38
tmp42 = tmp41 * tmp3
tmp43 = tl.where(tmp40, tmp41, tmp42)
tmp44 = tl.where(tmp0, tmp43, tmp6)
tmp47 = tmp46 * tmp3
tmp48 = tl.where(tmp45, tmp46, tmp47)
tmp49 = tl.where(tmp8, tmp48, tmp6)
tmp50 = triton_helpers.maximum(tmp44, tmp49)
tmp53 = tmp52 * tmp3
tmp54 = tl.where(tmp51, tmp52, tmp53)
tmp55 = tl.where(tmp15, tmp54, tmp6)
tmp56 = triton_helpers.maximum(tmp50, tmp55)
tmp59 = tmp58 * tmp3
tmp60 = tl.where(tmp57, tmp58, tmp59)
tmp61 = tl.where(tmp22, tmp60, tmp6)
tmp62 = triton_helpers.maximum(tmp56, tmp61)
tmp63 = tmp44 - tmp62
tmp64 = tl_math.exp(tmp63)
tmp65 = tmp49 - tmp62
tmp66 = tl_math.exp(tmp65)
tmp67 = tmp64 + tmp66
tmp68 = tmp55 - tmp62
tmp69 = tl_math.exp(tmp68)
tmp70 = tmp67 + tmp69
tmp71 = tmp61 - tmp62
tmp72 = tl_math.exp(tmp71)
tmp73 = tmp70 + tmp72
tmp76 = tmp75 * tmp3
tmp77 = tl.where(tmp74, tmp75, tmp76)
tmp78 = tl.where(tmp0, tmp77, tmp6)
tmp81 = tmp80 * tmp3
tmp82 = tl.where(tmp79, tmp80, tmp81)
tmp83 = tl.where(tmp8, tmp82, tmp6)
tmp84 = triton_helpers.maximum(tmp78, tmp83)
tmp87 = tmp86 * tmp3
tmp88 = tl.where(tmp85, tmp86, tmp87)
tmp89 = tl.where(tmp15, tmp88, tmp6)
tmp90 = triton_helpers.maximum(tmp84, tmp89)
tmp93 = tmp92 * tmp3
tmp94 = tl.where(tmp91, tmp92, tmp93)
tmp95 = tl.where(tmp22, tmp94, tmp6)
tmp96 = triton_helpers.maximum(tmp90, tmp95)
tmp97 = tmp78 - tmp96
tmp98 = tl_math.exp(tmp97)
tmp99 = tmp83 - tmp96
tmp100 = tl_math.exp(tmp99)
tmp101 = tmp98 + tmp100
tmp102 = tmp89 - tmp96
tmp103 = tl_math.exp(tmp102)
tmp104 = tmp101 + tmp103
tmp105 = tmp95 - tmp96
tmp106 = tl_math.exp(tmp105)
tmp107 = tmp104 + tmp106
tmp110 = tmp109 * tmp3
tmp111 = tl.where(tmp108, tmp109, tmp110)
tmp112 = tl.where(tmp0, tmp111, tmp6)
tmp115 = tmp114 * tmp3
tmp116 = tl.where(tmp113, tmp114, tmp115)
tmp117 = tl.where(tmp8, tmp116, tmp6)
tmp118 = triton_helpers.maximum(tmp112, tmp117)
tmp121 = tmp120 * tmp3
tmp122 = tl.where(tmp119, tmp120, tmp121)
tmp123 = tl.where(tmp15, tmp122, tmp6)
tmp124 = triton_helpers.maximum(tmp118, tmp123)
tmp127 = tmp126 * tmp3
tmp128 = tl.where(tmp125, tmp126, tmp127)
tmp129 = tl.where(tmp22, tmp128, tmp6)
tmp130 = triton_helpers.maximum(tmp124, tmp129)
tmp131 = tmp112 - tmp130
tmp132 = tl_math.exp(tmp131)
tmp133 = tmp117 - tmp130
tmp134 = tl_math.exp(tmp133)
tmp135 = tmp132 + tmp134
tmp136 = tmp123 - tmp130
tmp137 = tl_math.exp(tmp136)
tmp138 = tmp135 + tmp137
tmp139 = tmp129 - tmp130
tmp140 = tl_math.exp(tmp139)
tmp141 = tmp138 + tmp140
tl.store(out_ptr0 + x0, tmp28, xmask)
tl.store(out_ptr1 + x0, tmp39, xmask)
tl.store(out_ptr2 + x0, tmp62, xmask)
tl.store(out_ptr3 + x0, tmp73, xmask)
tl.store(out_ptr4 + x0, tmp96, xmask)
tl.store(out_ptr5 + x0, tmp107, xmask)
tl.store(out_ptr6 + x0, tmp130, xmask)
tl.store(out_ptr7 + x0, tmp141, xmask)
@triton.jit
def triton_poi_fused__softmax_leaky_relu_mul_where_3(in_out_ptr0,
in_out_ptr1, in_out_ptr2, in_out_ptr3, in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10,
in_ptr11, in_ptr12, 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).to(tl.int1)
tmp1 = tl.load(in_ptr1 + x2, xmask).to(tl.int1)
tmp2 = tl.load(in_out_ptr0 + x2, xmask)
tmp8 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp13 = tl.load(in_ptr4 + x2, xmask).to(tl.int1)
tmp14 = tl.load(in_out_ptr1 + x2, xmask)
tmp18 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr6 + x1, xmask, eviction_policy='evict_last')
tmp23 = tl.load(in_ptr7 + x2, xmask).to(tl.int1)
tmp24 = tl.load(in_out_ptr2 + x2, xmask)
tmp28 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last')
tmp31 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last')
tmp33 = tl.load(in_ptr10 + x2, xmask).to(tl.int1)
tmp34 = tl.load(in_out_ptr3 + x2, xmask)
tmp38 = tl.load(in_ptr11 + x1, xmask, eviction_policy='evict_last')
tmp41 = tl.load(in_ptr12 + x1, xmask, eviction_policy='evict_last')
tmp3 = 4.0
tmp4 = tmp2 * tmp3
tmp5 = tl.where(tmp1, tmp2, tmp4)
tmp6 = -8999999815811072.0
tmp7 = tl.where(tmp0, tmp5, tmp6)
tmp9 = tmp7 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tmp15 = tmp14 * tmp3
tmp16 = tl.where(tmp13, tmp14, tmp15)
tmp17 = tl.where(tmp0, tmp16, tmp6)
tmp19 = tmp17 - tmp18
tmp20 = tl_math.exp(tmp19)
tmp22 = tmp20 / tmp21
tmp25 = tmp24 * tmp3
tmp26 = tl.where(tmp23, tmp24, tmp25)
tmp27 = tl.where(tmp0, tmp26, tmp6)
tmp29 = tmp27 - tmp28
tmp30 = tl_math.exp(tmp29)
tmp32 = tmp30 / tmp31
tmp35 = tmp34 * tmp3
tmp36 = tl.where(tmp33, tmp34, tmp35)
tmp37 = tl.where(tmp0, tmp36, tmp6)
tmp39 = tmp37 - tmp38
tmp40 = tl_math.exp(tmp39)
tmp42 = tmp40 / tmp41
tl.store(in_out_ptr0 + x2, tmp12, xmask)
tl.store(in_out_ptr1 + x2, tmp22, xmask)
tl.store(in_out_ptr2 + x2, tmp32, xmask)
tl.store(in_out_ptr3 + x2, tmp42, xmask)
@triton.jit
def triton_poi_fused_cat_4(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = 0.0
tmp7 = tmp5 > tmp6
tmp8 = 1.0
tmp9 = tmp5 * tmp8
tmp10 = libdevice.expm1(tmp9)
tmp11 = tmp10 * tmp8
tmp12 = tl.where(tmp7, tmp9, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tmp16 = tl.full([1], 8, tl.int64)
tmp17 = tmp0 < tmp16
tmp18 = tmp15 & tmp17
tmp19 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp18 & xmask,
eviction_policy='evict_last', other=0.0)
tmp20 = tmp19 > tmp6
tmp21 = tmp19 * tmp8
tmp22 = libdevice.expm1(tmp21)
tmp23 = tmp22 * tmp8
tmp24 = tl.where(tmp20, tmp21, tmp23)
tmp25 = tl.full(tmp24.shape, 0.0, tmp24.dtype)
tmp26 = tl.where(tmp18, tmp24, tmp25)
tmp27 = tmp0 >= tmp16
tmp28 = tl.full([1], 12, tl.int64)
tmp29 = tmp0 < tmp28
tmp30 = tmp27 & tmp29
tmp31 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp30 & xmask,
eviction_policy='evict_last', other=0.0)
tmp32 = tmp31 > tmp6
tmp33 = tmp31 * tmp8
tmp34 = libdevice.expm1(tmp33)
tmp35 = tmp34 * tmp8
tmp36 = tl.where(tmp32, tmp33, tmp35)
tmp37 = tl.full(tmp36.shape, 0.0, tmp36.dtype)
tmp38 = tl.where(tmp30, tmp36, tmp37)
tmp39 = tmp0 >= tmp28
tl.full([1], 16, tl.int64)
tmp42 = tl.load(in_ptr3 + (4 * x1 + (-12 + x0)), tmp39 & xmask,
eviction_policy='evict_last', other=0.0)
tmp43 = tmp42 > tmp6
tmp44 = tmp42 * tmp8
tmp45 = libdevice.expm1(tmp44)
tmp46 = tmp45 * tmp8
tmp47 = tl.where(tmp43, tmp44, tmp46)
tmp48 = tl.full(tmp47.shape, 0.0, tmp47.dtype)
tmp49 = tl.where(tmp39, tmp47, tmp48)
tmp50 = tl.where(tmp30, tmp38, tmp49)
tmp51 = tl.where(tmp18, tmp26, tmp50)
tmp52 = tl.where(tmp4, tmp14, tmp51)
tl.store(out_ptr0 + x2, tmp52, xmask)
@triton.jit
def triton_poi_fused__softmax_leaky_relu_mul_where_5(in_ptr0, in_ptr1,
in_ptr2, 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').to(tl
.int1)
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last').to(tl
.int1)
tmp2 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp9 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp10 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp15 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp16 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp17 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp23 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
).to(tl.int1)
tmp24 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp3 = 4.0
tmp4 = tmp2 * tmp3
tmp5 = tl.where(tmp1, tmp2, tmp4)
tmp6 = -8999999815811072.0
tmp7 = tl.where(tmp0, tmp5, tmp6)
tmp11 = tmp10 * tmp3
tmp12 = tl.where(tmp9, tmp10, tmp11)
tmp13 = tl.where(tmp8, tmp12, tmp6)
tmp14 = triton_helpers.maximum(tmp7, tmp13)
tmp18 = tmp17 * tmp3
tmp19 = tl.where(tmp16, tmp17, tmp18)
tmp20 = tl.where(tmp15, tmp19, tmp6)
tmp21 = triton_helpers.maximum(tmp14, tmp20)
tmp25 = tmp24 * tmp3
tmp26 = tl.where(tmp23, tmp24, tmp25)
tmp27 = tl.where(tmp22, tmp26, tmp6)
tmp28 = triton_helpers.maximum(tmp21, tmp27)
tmp29 = tmp7 - tmp28
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp13 - tmp28
tmp32 = tl_math.exp(tmp31)
tmp33 = tmp30 + tmp32
tmp34 = tmp20 - tmp28
tmp35 = tl_math.exp(tmp34)
tmp36 = tmp33 + tmp35
tmp37 = tmp27 - tmp28
tmp38 = tl_math.exp(tmp37)
tmp39 = tmp36 + tmp38
tl.store(out_ptr0 + x0, tmp28, xmask)
tl.store(out_ptr1 + x0, tmp39, xmask)
@triton.jit
def triton_poi_fused__softmax_leaky_relu_mul_where_6(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + x2, xmask).to(tl.int1)
tmp2 = tl.load(in_out_ptr0 + x2, xmask)
tmp8 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp3 = 4.0
tmp4 = tmp2 * tmp3
tmp5 = tl.where(tmp1, tmp2, tmp4)
tmp6 = -8999999815811072.0
tmp7 = tl.where(tmp0, tmp5, tmp6)
tmp9 = tmp7 - tmp8
tmp10 = tl_math.exp(tmp9)
tmp12 = tmp10 / tmp11
tl.store(in_out_ptr0 + x2, tmp12, xmask)
@triton.jit
def triton_poi_fused_elu_7(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.0
tmp2 = tmp0 > tmp1
tmp3 = 1.0
tmp4 = tmp0 * tmp3
tmp5 = libdevice.expm1(tmp4)
tmp6 = tmp5 * tmp3
tmp7 = tl.where(tmp2, tmp4, tmp6)
tl.store(out_ptr0 + x0, tmp7, 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, 4), (4, 1))
assert_size_stride(primals_3, (8, 1), (1, 1))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4, 4), (4, 1))
assert_size_stride(primals_6, (8, 1), (1, 1))
assert_size_stride(primals_7, (4, 4), (4, 1))
assert_size_stride(primals_8, (8, 1), (1, 1))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (8, 1), (1, 1))
assert_size_stride(primals_11, (16, 4), (4, 1))
assert_size_stride(primals_12, (8, 1), (1, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_2, out=buf0)
del primals_2
buf1 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(128)](buf0, buf1, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf2 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf1, primals_3, out=buf2)
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_leaky_relu_1[grid(16)](buf2, buf3, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_leaky_relu_1[grid(16)](primals_4, buf4, 16, XBLOCK
=16, num_warps=1, num_stages=1)
del primals_4
buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_5, out=buf9)
del primals_5
buf10 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
triton_poi_fused_cat_0[grid(128)](buf9, buf10, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf11 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf10, primals_6, out=buf11)
buf12 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_leaky_relu_1[grid(16)](buf11, buf12, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_7, out=buf17)
del primals_7
buf18 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
triton_poi_fused_cat_0[grid(128)](buf17, buf18, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf19 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf18, primals_8, out=buf19)
buf20 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_leaky_relu_1[grid(16)](buf19, buf20, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf25 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(primals_1, primals_9, out=buf25)
del primals_9
buf26 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
triton_poi_fused_cat_0[grid(128)](buf25, buf26, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf27 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf26, primals_10, out=buf27)
buf28 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_leaky_relu_1[grid(16)](buf27, buf28, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf6 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf13 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf14 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf21 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf22 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf29 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
buf30 = empty_strided_cuda((4, 1), (1, 4), torch.float32)
triton_poi_fused__softmax_leaky_relu_mul_where_2[grid(4)](buf4,
buf3, buf2, buf12, buf11, buf20, buf19, buf28, buf27, buf5,
buf6, buf13, buf14, buf21, buf22, buf29, buf30, 4, XBLOCK=4,
num_warps=1, num_stages=1)
buf7 = reinterpret_tensor(buf2, (4, 4), (4, 1), 0)
del buf2
buf15 = reinterpret_tensor(buf11, (4, 4), (4, 1), 0)
del buf11
buf23 = reinterpret_tensor(buf19, (4, 4), (4, 1), 0)
del buf19
buf31 = reinterpret_tensor(buf27, (4, 4), (4, 1), 0)
del buf27
triton_poi_fused__softmax_leaky_relu_mul_where_3[grid(16)](buf7,
buf15, buf23, buf31, buf4, buf3, buf5, buf6, buf12, buf13,
buf14, buf20, buf21, buf22, buf28, buf29, buf30, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del buf13
del buf14
del buf21
del buf22
del buf29
del buf30
buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf7, buf0, out=buf8)
buf16 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf15, buf9, out=buf16)
buf24 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf23, buf17, out=buf24)
buf32 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf31, buf25, out=buf32)
buf33 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_poi_fused_cat_4[grid(64)](buf8, buf16, buf24, buf32, buf33,
64, XBLOCK=64, num_warps=1, num_stages=1)
buf34 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf33, primals_11, out=buf34)
buf35 = empty_strided_cuda((16, 8), (8, 1), torch.float32)
triton_poi_fused_cat_0[grid(128)](buf34, buf35, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf36 = empty_strided_cuda((16, 1), (1, 1), torch.float32)
extern_kernels.mm(buf35, primals_12, out=buf36)
buf37 = empty_strided_cuda((4, 4), (4, 1), torch.bool)
triton_poi_fused_leaky_relu_1[grid(16)](buf36, buf37, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf38 = buf6
del buf6
buf39 = buf5
del buf5
triton_poi_fused__softmax_leaky_relu_mul_where_5[grid(4)](buf4,
buf37, buf36, buf38, buf39, 4, XBLOCK=4, num_warps=1, num_stages=1)
buf40 = reinterpret_tensor(buf36, (4, 4), (4, 1), 0)
del buf36
triton_poi_fused__softmax_leaky_relu_mul_where_6[grid(16)](buf40,
buf4, buf37, buf38, buf39, 16, XBLOCK=16, num_warps=1, num_stages=1
)
del buf38
del buf39
buf41 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf40, buf34, out=buf41)
buf42 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused_elu_7[grid(16)](buf41, buf42, 16, XBLOCK=16,
num_warps=1, num_stages=1)
return (buf42, buf3, buf4, buf7, buf8, buf12, buf15, buf16, buf20,
buf23, buf24, buf28, buf31, buf32, buf37, buf40, buf41,
reinterpret_tensor(buf34, (4, 4), (1, 4), 0), reinterpret_tensor(
buf35, (8, 16), (1, 8), 0), reinterpret_tensor(primals_12, (1, 8),
(1, 1), 0), reinterpret_tensor(buf33, (16, 4), (1, 16), 0),
reinterpret_tensor(primals_11, (4, 16), (1, 4), 0),
reinterpret_tensor(buf25, (4, 4), (1, 4), 0), reinterpret_tensor(
buf26, (8, 16), (1, 8), 0), reinterpret_tensor(primals_10, (1, 8),
(1, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0),
reinterpret_tensor(buf17, (4, 4), (1, 4), 0), reinterpret_tensor(
buf18, (8, 16), (1, 8), 0), reinterpret_tensor(primals_8, (1, 8), (
1, 1), 0), reinterpret_tensor(buf9, (4, 4), (1, 4), 0),
reinterpret_tensor(buf10, (8, 16), (1, 8), 0), reinterpret_tensor(
primals_6, (1, 8), (1, 1), 0), reinterpret_tensor(buf0, (4, 4), (1,
4), 0), reinterpret_tensor(buf1, (8, 16), (1, 8), 0),
reinterpret_tensor(primals_3, (1, 8), (1, 1), 0))
class GraphAttentionLayer(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttentionLayer, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
self.W = nn.Parameter(torch.empty(size=(in_features, out_features)))
nn.init.xavier_uniform_(self.W.data, gain=1.414)
self.a = nn.Parameter(torch.empty(size=(2 * out_features, 1)))
nn.init.xavier_uniform_(self.a.data, gain=1.414)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, h, adj):
Wh = torch.mm(h, self.W)
a_input = self._prepare_attentional_mechanism_input(Wh)
e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))
zero_vec = -9000000000000000.0 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, Wh)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def _prepare_attentional_mechanism_input(self, Wh):
N = Wh.size()[0]
Wh_repeated_in_chunks = Wh.repeat_interleave(N, dim=0)
Wh_repeated_alternating = Wh.repeat(N, 1)
all_combinations_matrix = torch.cat([Wh_repeated_in_chunks,
Wh_repeated_alternating], dim=1)
return all_combinations_matrix.view(N, N, 2 * self.out_features)
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features
) + ' -> ' + str(self.out_features) + ')'
class GATNew(nn.Module):
def __init__(self, nfeat, nhid, output, dropout, alpha, nheads):
"""Dense version of GAT."""
super(GATNew, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout,
alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
self.out_att = GraphAttentionLayer(nhid * nheads, output, dropout=
dropout, alpha=alpha, concat=False)
def forward(self, input_0, input_1):
primals_1 = self.attention_0.W
primals_3 = self.attention_0.a
primals_2 = self.attention_1.W
primals_6 = self.attention_1.a
primals_4 = self.attention_2.W
primals_8 = self.attention_2.a
primals_5 = self.attention_3.W
primals_10 = self.attention_3.a
primals_11 = self.out_att.W
primals_12 = self.out_att.a
primals_7 = input_0
primals_9 = 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]
|
jk96491/SMAC
|
GAT
| false
| 15,726
|
[
"Apache-2.0"
] | 64
|
7aaf4673b0eecafc4ab25f381eea20fc762af56a
|
https://github.com/jk96491/SMAC/tree/7aaf4673b0eecafc4ab25f381eea20fc762af56a
|
AgentConvBlock
|
import torch
import torch.nn as nn
class AgentConvBlock(nn.Module):
def __init__(self, nin, nout, ksize=3):
super(AgentConvBlock, self).__init__()
self.conv1 = nn.Conv2d(nin, nout, ksize, padding=1)
self.lrelu1 = nn.LeakyReLU(0.2)
self.conv2 = nn.Conv2d(nout, nout, ksize, padding=1)
self.lrelu2 = nn.LeakyReLU(0.2)
self.pool = nn.AvgPool2d(2)
def forward(self, x):
h = self.lrelu1(self.conv1(x))
h = self.lrelu2(self.conv2(h))
return self.pool(h)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'nin': 4, 'nout': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr1 + x3, tmp7, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_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 % 2
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_leaky_relu_0[grid(256)](buf0,
primals_2, buf1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf5 = buf0
del buf0
triton_poi_fused_convolution_leaky_relu_0[grid(256)](buf3,
primals_5, buf4, buf5, 256, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
del primals_5
buf6 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused_avg_pool2d_1[grid(64)](buf5, buf6, 64, XBLOCK=64,
num_warps=1, num_stages=1)
return buf6, primals_1, primals_3, primals_4, buf1, buf2, buf4, buf5
class AgentConvBlockNew(nn.Module):
def __init__(self, nin, nout, ksize=3):
super(AgentConvBlockNew, self).__init__()
self.conv1 = nn.Conv2d(nin, nout, ksize, padding=1)
self.lrelu1 = nn.LeakyReLU(0.2)
self.conv2 = nn.Conv2d(nout, nout, ksize, padding=1)
self.lrelu2 = nn.LeakyReLU(0.2)
self.pool = nn.AvgPool2d(2)
def forward(self, input_0):
primals_1 = self.conv1.weight
primals_2 = self.conv1.bias
primals_4 = self.conv2.weight
primals_5 = self.conv2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jonhare/DifferentiableSketching
|
AgentConvBlock
| false
| 15,727
|
[
"BSD-3-Clause"
] | 100
|
462551ea2c8d07125352080b0c74e39c7fcbd49e
|
https://github.com/jonhare/DifferentiableSketching/tree/462551ea2c8d07125352080b0c74e39c7fcbd49e
|
Quantize
|
import torch
from torch import nn
from torch.nn import functional as F
class Quantize(nn.Module):
"""
Discretization bottleneck part of the VQ-VAE.
Inputs:
- n_e : number of embeddings
- e_dim : dimension of embedding
- beta : commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2
"""
def __init__(self, dim, n_embed, beta=0.25):
super().__init__()
self.n_e = n_embed
self.e_dim = dim
self.beta = beta
rand_range = 1.0 / self.n_e
self.embeddings = nn.Parameter(torch.rand(dim, n_embed).mul_(2 *
rand_range).sub_(rand_range))
def forward(self, input):
"""
Inputs the output of the encoder network z and maps it to a discrete
one-hot vector that is the index of the closest embedding vector e_j
z (continuous) -> z_q (discrete)
z.shape = (batch, channel, height, width)
quantization pipeline:
1. get encoder input (B,C,H,W)
2. flatten input to (B*H*W,C)
"""
x = input.permute(0, 2, 3, 1)
flatten = x.reshape(-1, x.size(-1))
dist = flatten.pow(2).sum(1, keepdim=True
) - 2 * flatten @ self.embeddings + self.embeddings.pow(2).sum(
0, keepdim=True)
_, embed_ind = (-dist).max(1)
embed_ind = embed_ind.view(*x.shape[:-1])
quantize = self.embed_code(embed_ind)
loss = torch.mean((quantize.detach() - input).pow(2)
) + self.beta * torch.mean((quantize - input.detach()).pow(2))
quantize = input + (quantize - input).detach()
return quantize, loss, embed_ind
def embed_code(self, embed_id):
codes = F.embedding(embed_id, self.embeddings.transpose(0, 1))
return codes.permute(0, 3, 1, 2).contiguous()
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4, 'n_embed': 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
from torch.nn import functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 64
x1 = xindex // 64
x2 = xindex
tmp0 = tl.load(in_ptr0 + (16 * x1 + 64 * (x0 // 16) + x0 % 16), xmask)
tmp1 = 2.0
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x2, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_pow_sub_sum_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
x1 = xindex // 4
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + (64 * (x1 // 16) + x1 % 16), xmask,
eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (16 + 64 * (x1 // 16) + x1 % 16), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (32 + 64 * (x1 // 16) + x1 % 16), xmask,
eviction_policy='evict_last')
tmp8 = tl.load(in_ptr0 + (48 + 64 * (x1 // 16) + x1 % 16), xmask,
eviction_policy='evict_last')
tmp11 = tl.load(in_out_ptr0 + x2, xmask)
tmp13 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
tmp18 = tl.load(in_ptr1 + (8 + x0), xmask, eviction_policy='evict_last')
tmp21 = tl.load(in_ptr1 + (12 + 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
tmp12 = tmp10 - tmp11
tmp14 = tmp13 * tmp13
tmp16 = tmp15 * tmp15
tmp17 = tmp14 + tmp16
tmp19 = tmp18 * tmp18
tmp20 = tmp17 + tmp19
tmp22 = tmp21 * tmp21
tmp23 = tmp20 + tmp22
tmp24 = tmp12 + tmp23
tl.store(in_out_ptr0 + x2, tmp24, xmask)
@triton.jit
def triton_poi_fused_max_neg_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 + 4 * x0, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp19 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp35 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp1 = -tmp0
tmp3 = -tmp2
tmp4 = tmp1 > tmp3
tmp5 = tmp1 == tmp3
tmp6 = tmp1 != tmp1
tmp7 = tmp3 != tmp3
tmp8 = tmp6 > tmp7
tmp9 = tmp4 | tmp8
tmp10 = tmp6 & tmp7
tmp11 = tmp5 | tmp10
tmp12 = tl.full([1], 0, tl.int64)
tmp13 = tl.full([1], 1, tl.int64)
tmp14 = tmp12 < tmp13
tmp15 = tmp11 & tmp14
tmp16 = tmp9 | tmp15
tmp17 = tl.where(tmp16, tmp1, tmp3)
tmp18 = tl.where(tmp16, tmp12, tmp13)
tmp20 = -tmp19
tmp21 = tmp17 > tmp20
tmp22 = tmp17 == tmp20
tmp23 = tmp17 != tmp17
tmp24 = tmp20 != tmp20
tmp25 = tmp23 > tmp24
tmp26 = tmp21 | tmp25
tmp27 = tmp23 & tmp24
tmp28 = tmp22 | tmp27
tmp29 = tl.full([1], 2, tl.int64)
tmp30 = tmp18 < tmp29
tmp31 = tmp28 & tmp30
tmp32 = tmp26 | tmp31
tmp33 = tl.where(tmp32, tmp17, tmp20)
tmp34 = tl.where(tmp32, tmp18, tmp29)
tmp36 = -tmp35
tmp37 = tmp33 > tmp36
tmp38 = tmp33 == tmp36
tmp39 = tmp33 != tmp33
tmp40 = tmp36 != tmp36
tmp41 = tmp39 > tmp40
tmp42 = tmp37 | tmp41
tmp43 = tmp39 & tmp40
tmp44 = tmp38 | tmp43
tmp45 = tl.full([1], 3, tl.int64)
tmp46 = tmp34 < tmp45
tmp47 = tmp44 & tmp46
tmp48 = tmp42 | tmp47
tl.where(tmp48, tmp33, tmp36)
tmp50 = tl.where(tmp48, tmp34, tmp45)
tl.store(out_ptr0 + x0, tmp50, xmask)
@triton.jit
def triton_red_fused_add_clone_mean_mul_pow_sub_3(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.
constexpr, RBLOCK: tl.constexpr):
rnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rbase = tl.arange(0, RBLOCK)[None, :]
_tmp11 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r0 = rindex % 16
r2 = rindex // 64
r1 = rindex // 16 % 4
r3 = rindex
tmp0 = tl.load(in_ptr0 + (r0 + 16 * r2), rmask, eviction_policy=
'evict_last', other=0.0)
tmp7 = tl.load(in_ptr2 + r3, rmask, eviction_policy='evict_first',
other=0.0)
tmp1 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
tmp2 = tmp0 + tmp1
tmp3 = tmp0 < 0
tmp4 = tl.where(tmp3, tmp2, tmp0)
tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~rmask,
'index out of bounds: 0 <= tmp4 < 4')
tmp6 = tl.load(in_ptr1 + (tmp4 + 4 * r1), rmask, eviction_policy=
'evict_last', other=0.0)
tmp8 = tmp6 - tmp7
tmp9 = tmp8 * tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = _tmp11 + tmp10
_tmp11 = tl.where(rmask, tmp12, _tmp11)
tmp13 = tmp7 + tmp8
tmp14 = 2.0
tmp15 = tmp8 * tmp14
tl.store(out_ptr0 + tl.broadcast_to(r3, [XBLOCK, RBLOCK]), tmp13, rmask
)
tl.store(out_ptr1 + tl.broadcast_to(r3, [XBLOCK, RBLOCK]), tmp15, rmask
)
tmp11 = tl.sum(_tmp11, 1)[:, None]
tmp16 = 256.0
tmp17 = tmp11 / tmp16
tmp18 = 0.25
tmp19 = tmp17 * tmp18
tmp20 = tmp17 + tmp19
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp20, None)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](primals_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, primals_2, out=buf1)
buf2 = buf1
del buf1
triton_poi_fused_add_pow_sub_sum_1[grid(256)](buf2, primals_1,
primals_2, 256, XBLOCK=256, num_warps=4, num_stages=1)
buf3 = empty_strided_cuda((64,), (1,), torch.int64)
triton_poi_fused_max_neg_2[grid(64)](buf2, buf3, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf4 = empty_strided_cuda((), (), torch.float32)
buf5 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf6 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf0
buf7 = buf4
del buf4
triton_red_fused_add_clone_mean_mul_pow_sub_3[grid(1)](buf7, buf3,
primals_2, primals_1, buf5, buf6, 1, 256, XBLOCK=1, RBLOCK=256,
num_warps=8, num_stages=1)
del primals_1
del primals_2
return buf5, buf7, reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0), buf6
class QuantizeNew(nn.Module):
"""
Discretization bottleneck part of the VQ-VAE.
Inputs:
- n_e : number of embeddings
- e_dim : dimension of embedding
- beta : commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2
"""
def __init__(self, dim, n_embed, beta=0.25):
super().__init__()
self.n_e = n_embed
self.e_dim = dim
self.beta = beta
rand_range = 1.0 / self.n_e
self.embeddings = nn.Parameter(torch.rand(dim, n_embed).mul_(2 *
rand_range).sub_(rand_range))
def embed_code(self, embed_id):
codes = F.embedding(embed_id, self.embeddings.transpose(0, 1))
return codes.permute(0, 3, 1, 2).contiguous()
def forward(self, input_0):
primals_2 = self.embeddings
primals_1 = input_0
output = call([primals_1, primals_2])
return output[0], output[1], output[2]
|
jkulhanek/viewformer
|
Quantize
| false
| 15,728
|
[
"MIT"
] | 87
|
9ad2c5a2f7abe4b7ff490ced0132bf3d2f07e29c
|
https://github.com/jkulhanek/viewformer/tree/9ad2c5a2f7abe4b7ff490ced0132bf3d2f07e29c
|
Actor
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, init_std=0.01, init_type='normal', activation=
'leaky_relu', squashing_function=False):
super(Actor, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.squashing_function = squashing_function
assert self.squashing_function is False
self.activation = activation
self.layers = nn.ModuleList()
last_hidden_layer_size = self.state_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(self.state_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.action_output_layer = nn.Linear(last_hidden_layer_size, self.
action_size)
self.action_parameters_output_layer = nn.Linear(last_hidden_layer_size,
self.action_parameter_size)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.action_output_layer.weight, std=init_std)
nn.init.zeros_(self.action_output_layer.bias)
nn.init.normal_(self.action_parameters_output_layer.weight, std=
init_std)
nn.init.zeros_(self.action_parameters_output_layer.bias)
self.action_parameters_passthrough_layer = nn.Linear(self.
state_size, self.action_parameter_size)
nn.init.zeros_(self.action_parameters_passthrough_layer.weight)
nn.init.zeros_(self.action_parameters_passthrough_layer.bias)
self.action_parameters_passthrough_layer.weight.requires_grad = False
self.action_parameters_passthrough_layer.bias.requires_grad = False
def forward(self, state):
negative_slope = 0.01
x = state
num_hidden_layers = len(self.layers)
for i in range(0, num_hidden_layers):
if self.activation == 'relu':
x = F.relu(self.layers[i](x))
elif self.activation == 'leaky_relu':
x = F.leaky_relu(self.layers[i](x), negative_slope)
else:
raise ValueError('Unknown activation function ' + str(self.
activation))
actions = self.action_output_layer(x)
action_params = self.action_parameters_output_layer(x)
action_params += self.action_parameters_passthrough_layer(state)
return actions, action_params
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'action_parameter_size': 4}
]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_view_0(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
x4 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x4, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x4, 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 + x4, 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, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 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.addmm(primals_3, reinterpret_tensor(primals_1, (64,
4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_2
del primals_3
buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1)
del primals_4
buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf1
buf4 = buf3
del buf3
get_raw_stream(0)
triton_poi_fused_add_view_0[grid(256)](buf4, primals_5, buf2,
primals_7, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf2
del primals_5
del primals_7
return reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0
), buf4, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0)
class ActorNew(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, init_std=0.01, init_type='normal', activation=
'leaky_relu', squashing_function=False):
super(ActorNew, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.squashing_function = squashing_function
assert self.squashing_function is False
self.activation = activation
self.layers = nn.ModuleList()
last_hidden_layer_size = self.state_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(self.state_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.action_output_layer = nn.Linear(last_hidden_layer_size, self.
action_size)
self.action_parameters_output_layer = nn.Linear(last_hidden_layer_size,
self.action_parameter_size)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.action_output_layer.weight, std=init_std)
nn.init.zeros_(self.action_output_layer.bias)
nn.init.normal_(self.action_parameters_output_layer.weight, std=
init_std)
nn.init.zeros_(self.action_parameters_output_layer.bias)
self.action_parameters_passthrough_layer = nn.Linear(self.
state_size, self.action_parameter_size)
nn.init.zeros_(self.action_parameters_passthrough_layer.weight)
nn.init.zeros_(self.action_parameters_passthrough_layer.bias)
self.action_parameters_passthrough_layer.weight.requires_grad = False
self.action_parameters_passthrough_layer.bias.requires_grad = False
def forward(self, input_0):
primals_2 = self.action_output_layer.weight
primals_3 = self.action_output_layer.bias
primals_4 = self.action_parameters_output_layer.weight
primals_5 = self.action_parameters_output_layer.bias
primals_6 = self.action_parameters_passthrough_layer.weight
primals_7 = self.action_parameters_passthrough_layer.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0], output[1]
|
jordiriu/MP-DQN
|
Actor
| false
| 15,729
|
[
"MIT"
] | 75
|
eec13eb9b4e2c0099649e0639f2a8b93d7d0d5be
|
https://github.com/jordiriu/MP-DQN/tree/eec13eb9b4e2c0099649e0639f2a8b93d7d0d5be
|
SpatialAttn
|
import torch
from torch import nn
class SpatialAttn(nn.Module):
"""Spatial Attention Layer"""
def __init__(self):
super(SpatialAttn, self).__init__()
def forward(self, x):
x = x.mean(1, keepdim=True)
h = x.size(2)
w = x.size(3)
x = x.view(x.size(0), -1)
z = x
for b in range(x.size(0)):
z[b] /= torch.sum(z[b])
z = z.view(x.size(0), 1, h, w)
return z
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_div_sum_0(in_ptr0, out_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)
tmp1 = tl.load(in_ptr0 + (16 + r0), None)
tmp3 = tl.load(in_ptr0 + (32 + r0), None)
tmp5 = tl.load(in_ptr0 + (48 + r0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.sum(tmp9, 1)[:, None]
tmp12 = tmp8 / tmp11
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp12, None)
@triton.jit
def triton_poi_fused_div_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
x1 = xindex // 16
x0 = xindex % 16
x2 = xindex
tmp3 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp7 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp9 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp0 = x1
tmp1 = tl.full([1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp10 = tmp8 + tmp9
tmp11 = 4.0
tmp12 = tmp10 / tmp11
tmp13 = tl.where(tmp2, tmp3, tmp12)
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_per_fused_div_sum_2(in_ptr0, out_ptr0, out_ptr2, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp3 = tl.load(in_ptr0 + (r0 + 4 * (r0 % 4 // 4)), None)
tmp4 = tl.load(in_ptr0 + (16 + r0 + 4 * (r0 % 4 // 4)), None)
tmp12 = tl.load(in_ptr0 + (r0 + 8 * (r0 % 4 // 4)), None)
tmp13 = tl.load(in_ptr0 + (16 + r0 + 8 * (r0 % 4 // 4)), None)
tmp18 = tl.load(in_ptr0 + (32 + r0 + 8 * (r0 % 4 // 4)), None)
tmp0 = tl.full([1, 1], 1, tl.int32)
tmp1 = tl.full([1, 1], 0, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tmp9 = tl.full([1, 1], 2, tl.int32)
tmp10 = tmp9 == tmp0
tmp11 = tmp0 == tmp0
tmp14 = tl.where(tmp2, tmp12, tmp13)
tmp15 = tmp14 / tmp8
tmp16 = tl.where(tmp11, tmp15, tmp14)
tmp17 = tmp9 == tmp1
tmp19 = tl.where(tmp17, tmp12, tmp18)
tmp20 = tl.where(tmp10, tmp15, tmp19)
tmp21 = tl.where(tmp10, tmp16, tmp20)
tmp22 = tl.broadcast_to(tmp21, [XBLOCK, RBLOCK])
tmp24 = tl.sum(tmp22, 1)[:, None]
tmp25 = tmp21 / tmp24
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp25, None)
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None)
@triton.jit
def triton_poi_fused_div_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16
x0 = xindex % 16
x2 = xindex
tmp3 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (x0 + 8 * (x0 % 4 // 4)), xmask,
eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + (16 + x0 + 8 * (x0 % 4 // 4)), xmask,
eviction_policy='evict_last')
tmp12 = tl.load(in_ptr2 + 0)
tmp13 = tl.broadcast_to(tmp12, [XBLOCK])
tmp17 = tl.load(in_ptr1 + (x0 + 8 * (x0 % 4 // 4) + 16 * x1), xmask)
tmp0 = x1
tmp1 = tl.full([1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp4 = tl.full([1], 1, tl.int32)
tmp5 = tmp0 == tmp4
tmp6 = tmp4 == tmp4
tmp7 = tl.full([1], 0, tl.int32)
tmp8 = tmp4 == tmp7
tmp11 = tl.where(tmp8, tmp9, tmp10)
tmp14 = tmp11 / tmp13
tmp15 = tl.where(tmp6, tmp14, tmp11)
tmp16 = tmp0 == tmp7
tmp18 = tl.where(tmp16, tmp9, tmp17)
tmp19 = tl.where(tmp5, tmp14, tmp18)
tmp20 = tl.where(tmp5, tmp15, tmp19)
tmp21 = tl.where(tmp2, tmp3, tmp20)
tl.store(out_ptr0 + x2, tmp21, xmask)
@triton.jit
def triton_per_fused_sum_4(in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.
constexpr):
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp3 = tl.load(in_ptr0 + (32 + r0 + 4 * (r0 % 4 // 4)), None)
tmp4 = tl.load(in_ptr0 + (48 + r0 + 4 * (r0 % 4 // 4)), None)
tmp0 = tl.full([1, 1], 3, tl.int32)
tmp1 = tl.full([1, 1], 2, tl.int32)
tmp2 = tmp0 == tmp1
tmp5 = tl.where(tmp2, tmp3, tmp4)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp8, None)
@triton.jit
def triton_poi_fused_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
x1 = xindex // 16
x0 = xindex % 16
x2 = xindex
tmp6 = tl.load(in_ptr0 + (32 + x0 + 8 * (x0 % 4 // 4)), xmask,
eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (48 + x0 + 8 * (x0 % 4 // 4)), xmask,
eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + 0)
tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
tmp14 = tl.load(in_ptr0 + (x0 + 8 * (x0 % 4 // 4) + 16 * x1), xmask)
tmp0 = x1
tmp1 = tl.full([1], 3, tl.int32)
tmp2 = tmp0 == tmp1
tmp3 = tmp1 == tmp1
tmp4 = tl.full([1], 2, tl.int32)
tmp5 = tmp1 == tmp4
tmp8 = tl.where(tmp5, tmp6, tmp7)
tmp11 = tmp8 / tmp10
tmp12 = tl.where(tmp3, tmp11, tmp8)
tmp13 = tmp0 == tmp4
tmp15 = tl.where(tmp13, tmp6, tmp14)
tmp16 = tl.where(tmp2, tmp11, tmp15)
tmp17 = tl.where(tmp2, tmp12, tmp16)
tl.store(out_ptr0 + x2, 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)
buf1 = empty_strided_cuda((16,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_div_sum_0[grid(1)](arg0_1, buf1, 1, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf2 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_poi_fused_div_1[grid(64)](buf1, arg0_1, buf2, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((), (), torch.float32)
buf5 = buf1
del buf1
triton_per_fused_div_sum_2[grid(1)](buf2, buf3, buf5, 1, 16, XBLOCK
=1, num_warps=2, num_stages=1)
buf6 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
triton_poi_fused_div_3[grid(64)](buf5, buf2, buf3, buf6, 64, XBLOCK
=64, num_warps=1, num_stages=1)
del buf5
buf7 = buf3
del buf3
triton_per_fused_sum_4[grid(1)](buf6, buf7, 1, 16, XBLOCK=1,
num_warps=2, num_stages=1)
buf8 = buf2
del buf2
triton_poi_fused_5[grid(64)](buf6, buf7, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf6
del buf7
return reinterpret_tensor(buf8, (4, 1, 4, 4), (16, 16, 4, 1), 0),
class SpatialAttnNew(nn.Module):
"""Spatial Attention Layer"""
def __init__(self):
super(SpatialAttnNew, self).__init__()
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
johnzhang1999/Spatial-Attention
|
SpatialAttn
| false
| 15,730
|
[
"MIT"
] | 228
|
9e8e90ba624e52dcccba47c7289bb305765f5da6
|
https://github.com/johnzhang1999/Spatial-Attention/tree/9e8e90ba624e52dcccba47c7289bb305765f5da6
|
TransferConv3
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
import torch.utils.data
class TransferConv3(nn.Module):
def __init__(self, n_channels, n_channels_in=None, residual=False):
super().__init__()
if n_channels_in is None:
n_channels_in = n_channels
self.conv1 = nn.Conv2d(n_channels_in, n_channels, kernel_size=3,
stride=1, padding=1)
self.conv2 = nn.Conv2d(n_channels, n_channels, kernel_size=3,
stride=1, padding=1)
self.residual = residual
self.n_channels = n_channels
def forward(self, x):
x_copy = x
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
if self.residual:
if x.shape != x_copy.shape:
x_copy = x_copy[:, :self.n_channels, :, :]
x = x + x_copy
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'n_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.optim
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_1(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_3, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
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, 4, 4, 4), (64, 16, 4, 1))
buf3 = buf2
del buf2
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_1[grid(256)](buf3,
primals_5, buf4, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_2, primals_4, buf1, buf4
class TransferConv3New(nn.Module):
def __init__(self, n_channels, n_channels_in=None, residual=False):
super().__init__()
if n_channels_in is None:
n_channels_in = n_channels
self.conv1 = nn.Conv2d(n_channels_in, n_channels, kernel_size=3,
stride=1, padding=1)
self.conv2 = nn.Conv2d(n_channels, n_channels, kernel_size=3,
stride=1, padding=1)
self.residual = residual
self.n_channels = n_channels
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_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jozhang97/Side-tuning
|
TransferConv3
| false
| 15,731
|
[
"MIT"
] | 56
|
dea345691fb7ee0230150fe56ddd644efdffa6ac
|
https://github.com/jozhang97/Side-tuning/tree/dea345691fb7ee0230150fe56ddd644efdffa6ac
|
EncoderLayer
|
import math
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
out = (x - mean) / (std + self.eps)
out = self.gamma * out + self.beta
return out
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_head):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.attention = ScaleDotProductAttention()
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_concat = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)
q, k, v = self.split(q), self.split(k), self.split(v)
out, _attention = self.attention(q, k, v, mask=mask)
out = self.concat(out)
out = self.w_concat(out)
return out
def split(self, tensor):
"""
split tensor by number of head
:param tensor: [batch_size, length, d_model]
:return: [batch_size, head, length, d_tensor]
"""
batch_size, length, d_model = tensor.size()
d_tensor = d_model // self.n_head
tensor = tensor.view(batch_size, self.n_head, length, d_tensor)
return tensor
def concat(self, tensor):
"""
inverse function of self.split(tensor : torch.Tensor)
:param tensor: [batch_size, head, length, d_tensor]
:return: [batch_size, length, d_model]
"""
batch_size, head, length, d_tensor = tensor.size()
d_model = head * d_tensor
tensor = tensor.view(batch_size, length, d_model)
return tensor
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, hidden, drop_prob=0.1):
super(PositionwiseFeedForward, self).__init__()
self.linear1 = nn.Linear(d_model, hidden)
self.linear2 = nn.Linear(hidden, d_model)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=drop_prob)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.linear2(x)
return x
class EncoderLayer(nn.Module):
def __init__(self, d_model, ffn_hidden, n_head, drop_prob):
super(EncoderLayer, self).__init__()
self.attention = MultiHeadAttention(d_model=d_model, n_head=n_head)
self.norm1 = LayerNorm(d_model=d_model)
self.dropout1 = nn.Dropout(p=drop_prob)
self.ffn = PositionwiseFeedForward(d_model=d_model, hidden=
ffn_hidden, drop_prob=drop_prob)
self.norm2 = LayerNorm(d_model=d_model)
self.dropout2 = nn.Dropout(p=drop_prob)
def forward(self, x, s_mask):
_x = x
x = self.attention(q=x, k=x, v=x, mask=s_mask)
x = self.norm1(x + _x)
x = self.dropout1(x)
_x = x
x = self.ffn(x)
x = self.norm2(x + _x)
x = self.dropout2(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'ffn_hidden': 4, 'n_head': 4, 'drop_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 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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_eq_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
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_div_masked_fill_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask).to(tl.int1)
tmp7 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp11 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask).to(tl.int1)
tmp12 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp16 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask).to(tl.int1)
tmp17 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = -9.999999960041972e-13
tmp5 = tl.where(tmp0, tmp4, tmp3)
tmp8 = tmp7 * tmp2
tmp9 = tl.where(tmp6, tmp4, tmp8)
tmp10 = triton_helpers.maximum(tmp5, tmp9)
tmp13 = tmp12 * tmp2
tmp14 = tl.where(tmp11, tmp4, tmp13)
tmp15 = triton_helpers.maximum(tmp10, tmp14)
tmp18 = tmp17 * tmp2
tmp19 = tl.where(tmp16, tmp4, tmp18)
tmp20 = triton_helpers.maximum(tmp15, tmp19)
tmp21 = tmp5 - tmp20
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp9 - tmp20
tmp24 = tl_math.exp(tmp23)
tmp25 = tmp22 + tmp24
tmp26 = tmp14 - tmp20
tmp27 = tl_math.exp(tmp26)
tmp28 = tmp25 + tmp27
tmp29 = tmp19 - tmp20
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp28 + tmp30
tl.store(out_ptr0 + x2, tmp20, xmask)
tl.store(out_ptr1 + x2, tmp31, xmask)
@triton.jit
def triton_poi_fused__softmax_div_masked_fill_2(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
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask).to(tl.int1)
tmp1 = tl.load(in_out_ptr0 + x3, xmask)
tmp6 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = -9.999999960041972e-13
tmp5 = tl.where(tmp0, tmp4, tmp3)
tmp7 = tmp5 - tmp6
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 / tmp9
tl.store(in_out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mean_std_3(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = 3.0
tmp29 = tmp27 / tmp28
tl.store(in_out_ptr0 + x0, tmp29, xmask)
tl.store(out_ptr0 + x0, tmp16, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_4(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x2, xmask)
tmp4 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 - tmp4
tmp7 = libdevice.sqrt(tmp6)
tmp8 = 1e-12
tmp9 = tmp7 + tmp8
tmp10 = tmp5 / tmp9
tmp11 = tmp0 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_5(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_add_6(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_7(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 4.0
tmp10 = tmp8 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = 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 = 1e-12
tmp27 = tmp25 + tmp26
tmp28 = tmp11 / tmp27
tmp29 = tmp0 * tmp28
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x2, tmp31, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17, primals_18
) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4, 4), (4, 1))
assert_size_stride(primals_14, (4,), (1,))
assert_size_stride(primals_15, (4, 4), (4, 1))
assert_size_stride(primals_16, (4,), (1,))
assert_size_stride(primals_17, (4,), (1,))
assert_size_stride(primals_18, (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_1, (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((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_1, (16,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(primals_1, (16,
4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf2)
del primals_6
del primals_7
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 4, 1), (4, 1, 1),
0), reinterpret_tensor(buf1, (16, 1, 4), (4, 4, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_0[grid(256)](primals_8, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_8
buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
triton_poi_fused__softmax_div_masked_fill_1[grid(64)](buf4, buf3,
buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf7 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused__softmax_div_masked_fill_2[grid(256)](buf7, buf4,
buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 1), 0)
del buf6
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0), out=buf8)
buf9 = reinterpret_tensor(buf5, (16, 4), (4, 1), 0)
del buf5
extern_kernels.addmm(primals_10, reinterpret_tensor(buf8, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_9, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf9)
del primals_10
buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf11 = buf10
del buf10
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_mean_std_3[grid(16)](buf11, buf9, primals_1,
buf12, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf13 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_4[grid(64)](primals_11,
buf9, primals_1, buf12, buf11, primals_12, buf13, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf11
del buf12
del primals_12
buf14 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf13, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_13, (4, 4), (1, 4), 0), out=buf14)
buf15 = reinterpret_tensor(buf14, (4, 4, 4), (16, 4, 1), 0)
del buf14
buf19 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_5[grid(64)](buf15,
primals_14, buf19, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_14
buf16 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf15, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_15, (4, 4), (1, 4), 0), out=buf16)
buf17 = reinterpret_tensor(buf16, (4, 4, 4), (16, 4, 1), 0)
del buf16
triton_poi_fused_add_6[grid(64)](buf17, primals_16, buf13, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_16
buf18 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_7[grid(64)](primals_17,
buf17, primals_18, buf18, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_18
return (buf18, primals_1, primals_11, primals_17, buf4, buf7,
reinterpret_tensor(buf8, (16, 4), (4, 1), 0), buf9,
reinterpret_tensor(buf13, (16, 4), (4, 1), 0), reinterpret_tensor(
buf15, (16, 4), (4, 1), 0), buf17, primals_15, buf19, primals_13,
primals_9, reinterpret_tensor(buf2, (16, 1, 4), (4, 1, 1), 0),
reinterpret_tensor(buf0, (16, 1, 4), (4, 1, 1), 0),
reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 4), 0))
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
out = (x - mean) / (std + self.eps)
out = self.gamma * out + self.beta
return out
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_head):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.attention = ScaleDotProductAttention()
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_concat = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)
q, k, v = self.split(q), self.split(k), self.split(v)
out, _attention = self.attention(q, k, v, mask=mask)
out = self.concat(out)
out = self.w_concat(out)
return out
def split(self, tensor):
"""
split tensor by number of head
:param tensor: [batch_size, length, d_model]
:return: [batch_size, head, length, d_tensor]
"""
batch_size, length, d_model = tensor.size()
d_tensor = d_model // self.n_head
tensor = tensor.view(batch_size, self.n_head, length, d_tensor)
return tensor
def concat(self, tensor):
"""
inverse function of self.split(tensor : torch.Tensor)
:param tensor: [batch_size, head, length, d_tensor]
:return: [batch_size, length, d_model]
"""
batch_size, head, length, d_tensor = tensor.size()
d_model = head * d_tensor
tensor = tensor.view(batch_size, length, d_model)
return tensor
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, hidden, drop_prob=0.1):
super(PositionwiseFeedForward, self).__init__()
self.linear1 = nn.Linear(d_model, hidden)
self.linear2 = nn.Linear(hidden, d_model)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=drop_prob)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.linear2(x)
return x
class EncoderLayerNew(nn.Module):
def __init__(self, d_model, ffn_hidden, n_head, drop_prob):
super(EncoderLayerNew, self).__init__()
self.attention = MultiHeadAttention(d_model=d_model, n_head=n_head)
self.norm1 = LayerNorm(d_model=d_model)
self.dropout1 = nn.Dropout(p=drop_prob)
self.ffn = PositionwiseFeedForward(d_model=d_model, hidden=
ffn_hidden, drop_prob=drop_prob)
self.norm2 = LayerNorm(d_model=d_model)
self.dropout2 = nn.Dropout(p=drop_prob)
def forward(self, input_0, input_1):
primals_2 = self.attention.w_q.weight
primals_3 = self.attention.w_q.bias
primals_4 = self.attention.w_k.weight
primals_5 = self.attention.w_k.bias
primals_6 = self.attention.w_v.weight
primals_7 = self.attention.w_v.bias
primals_9 = self.attention.w_concat.weight
primals_10 = self.attention.w_concat.bias
primals_11 = self.norm1.gamma
primals_12 = self.norm1.beta
primals_13 = self.ffn.linear1.weight
primals_14 = self.ffn.linear1.bias
primals_15 = self.ffn.linear2.weight
primals_16 = self.ffn.linear2.bias
primals_17 = self.norm2.gamma
primals_18 = self.norm2.beta
primals_1 = input_0
primals_8 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, primals_14,
primals_15, primals_16, primals_17, primals_18])
return output[0]
|
jkimbf/transformer-1
|
EncoderLayer
| false
| 15,732
|
[
"Apache-2.0"
] | 233
|
6cd29731197822d6db641cdbfad3b045b8a294e4
|
https://github.com/jkimbf/transformer-1/tree/6cd29731197822d6db641cdbfad3b045b8a294e4
|
DecoderLayer
|
import math
import torch
import torch.nn as nn
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
out = (x - mean) / (std + self.eps)
out = self.gamma * out + self.beta
return out
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_head):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.attention = ScaleDotProductAttention()
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_concat = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)
q, k, v = self.split(q), self.split(k), self.split(v)
out, _attention = self.attention(q, k, v, mask=mask)
out = self.concat(out)
out = self.w_concat(out)
return out
def split(self, tensor):
"""
split tensor by number of head
:param tensor: [batch_size, length, d_model]
:return: [batch_size, head, length, d_tensor]
"""
batch_size, length, d_model = tensor.size()
d_tensor = d_model // self.n_head
tensor = tensor.view(batch_size, self.n_head, length, d_tensor)
return tensor
def concat(self, tensor):
"""
inverse function of self.split(tensor : torch.Tensor)
:param tensor: [batch_size, head, length, d_tensor]
:return: [batch_size, length, d_model]
"""
batch_size, head, length, d_tensor = tensor.size()
d_model = head * d_tensor
tensor = tensor.view(batch_size, length, d_model)
return tensor
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, hidden, drop_prob=0.1):
super(PositionwiseFeedForward, self).__init__()
self.linear1 = nn.Linear(d_model, hidden)
self.linear2 = nn.Linear(hidden, d_model)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=drop_prob)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.linear2(x)
return x
class DecoderLayer(nn.Module):
def __init__(self, d_model, ffn_hidden, n_head, drop_prob):
super(DecoderLayer, self).__init__()
self.self_attention = MultiHeadAttention(d_model=d_model, n_head=n_head
)
self.norm1 = LayerNorm(d_model=d_model)
self.dropout1 = nn.Dropout(p=drop_prob)
self.enc_dec_attention = MultiHeadAttention(d_model=d_model, n_head
=n_head)
self.norm2 = LayerNorm(d_model=d_model)
self.dropout2 = nn.Dropout(p=drop_prob)
self.ffn = PositionwiseFeedForward(d_model=d_model, hidden=
ffn_hidden, drop_prob=drop_prob)
self.norm3 = LayerNorm(d_model=d_model)
self.dropout3 = nn.Dropout(p=drop_prob)
def forward(self, dec, enc, t_mask, s_mask):
_x = dec
x = self.self_attention(q=dec, k=dec, v=dec, mask=t_mask)
x = self.norm1(x + _x)
x = self.dropout1(x)
if enc is not None:
_x = x
x = self.enc_dec_attention(q=x, k=enc, v=enc, mask=s_mask)
x = self.norm2(x + _x)
x = self.dropout2(x)
_x = x
x = self.ffn(x)
x = self.norm3(x + _x)
x = self.dropout3(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4,
4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'d_model': 4, 'ffn_hidden': 4, 'n_head': 4, 'drop_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 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
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_eq_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
tl.store(out_ptr0 + x0, tmp2, xmask)
@triton.jit
def triton_poi_fused__softmax_div_masked_fill_1(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask).to(tl.int1)
tmp1 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
tmp6 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask).to(tl.int1)
tmp7 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
tmp11 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask).to(tl.int1)
tmp12 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
tmp16 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask).to(tl.int1)
tmp17 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = -9.999999960041972e-13
tmp5 = tl.where(tmp0, tmp4, tmp3)
tmp8 = tmp7 * tmp2
tmp9 = tl.where(tmp6, tmp4, tmp8)
tmp10 = triton_helpers.maximum(tmp5, tmp9)
tmp13 = tmp12 * tmp2
tmp14 = tl.where(tmp11, tmp4, tmp13)
tmp15 = triton_helpers.maximum(tmp10, tmp14)
tmp18 = tmp17 * tmp2
tmp19 = tl.where(tmp16, tmp4, tmp18)
tmp20 = triton_helpers.maximum(tmp15, tmp19)
tmp21 = tmp5 - tmp20
tmp22 = tl_math.exp(tmp21)
tmp23 = tmp9 - tmp20
tmp24 = tl_math.exp(tmp23)
tmp25 = tmp22 + tmp24
tmp26 = tmp14 - tmp20
tmp27 = tl_math.exp(tmp26)
tmp28 = tmp25 + tmp27
tmp29 = tmp19 - tmp20
tmp30 = tl_math.exp(tmp29)
tmp31 = tmp28 + tmp30
tl.store(out_ptr0 + x2, tmp20, xmask)
tl.store(out_ptr1 + x2, tmp31, xmask)
@triton.jit
def triton_poi_fused__softmax_div_masked_fill_2(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
x3 = xindex
x0 = xindex % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask).to(tl.int1)
tmp1 = tl.load(in_out_ptr0 + x3, xmask)
tmp6 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr2 + (x0 + 16 * x2), xmask, eviction_policy=
'evict_last')
tmp2 = 1.0
tmp3 = tmp1 * tmp2
tmp4 = -9.999999960041972e-13
tmp5 = tl.where(tmp0, tmp4, tmp3)
tmp7 = tmp5 - tmp6
tmp8 = tl_math.exp(tmp7)
tmp10 = tmp8 / tmp9
tl.store(in_out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_add_mean_std_3(in_out_ptr0, in_ptr0, in_ptr1, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 + tmp1
tmp5 = tmp3 + tmp4
tmp6 = tmp2 + tmp5
tmp9 = tmp7 + tmp8
tmp10 = tmp6 + tmp9
tmp13 = tmp11 + tmp12
tmp14 = tmp10 + tmp13
tmp15 = 4.0
tmp16 = tmp14 / tmp15
tmp17 = tmp2 - tmp16
tmp18 = tmp17 * tmp17
tmp19 = tmp5 - tmp16
tmp20 = tmp19 * tmp19
tmp21 = tmp18 + tmp20
tmp22 = tmp9 - tmp16
tmp23 = tmp22 * tmp22
tmp24 = tmp21 + tmp23
tmp25 = tmp13 - tmp16
tmp26 = tmp25 * tmp25
tmp27 = tmp24 + tmp26
tmp28 = 3.0
tmp29 = tmp27 / tmp28
tl.store(in_out_ptr0 + x0, tmp29, xmask)
tl.store(out_ptr0 + x0, tmp16, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_4(in_ptr0, in_ptr1, in_ptr2,
in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr2 + x2, xmask)
tmp4 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 - tmp4
tmp7 = libdevice.sqrt(tmp6)
tmp8 = 1e-12
tmp9 = tmp7 + tmp8
tmp10 = tmp5 / tmp9
tmp11 = tmp0 * tmp10
tmp13 = tmp11 + tmp12
tl.store(out_ptr0 + x2, tmp13, xmask)
@triton.jit
def triton_poi_fused_add_5(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(in_out_ptr0 + x2, tmp4, xmask)
@triton.jit
def triton_poi_fused_add_div_mean_mul_std_sub_6(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask)
tmp2 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp30 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp8 = tmp6 + tmp7
tmp9 = 4.0
tmp10 = tmp8 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = 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 = 1e-12
tmp27 = tmp25 + tmp26
tmp28 = tmp11 / tmp27
tmp29 = tmp0 * tmp28
tmp31 = tmp29 + tmp30
tl.store(out_ptr0 + x2, tmp31, xmask)
@triton.jit
def triton_poi_fused_relu_threshold_backward_7(in_out_ptr0, in_ptr0,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, 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) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4), (4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4), (4, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_9, (4, 4), (4, 1))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_14, (4, 4), (4, 1))
assert_size_stride(primals_15, (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, 1))
assert_size_stride(primals_19, (4,), (1,))
assert_size_stride(primals_20, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_21, (4, 4), (4, 1))
assert_size_stride(primals_22, (4,), (1,))
assert_size_stride(primals_23, (4,), (1,))
assert_size_stride(primals_24, (4,), (1,))
assert_size_stride(primals_25, (4, 4), (4, 1))
assert_size_stride(primals_26, (4,), (1,))
assert_size_stride(primals_27, (4, 4), (4, 1))
assert_size_stride(primals_28, (4,), (1,))
assert_size_stride(primals_29, (4,), (1,))
assert_size_stride(primals_30, (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_1, (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((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(primals_1, (16,
4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf1)
del primals_4
del primals_5
buf2 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(primals_1, (16,
4), (4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf2)
del primals_6
del primals_7
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf0, (16, 4, 1), (4, 1, 1),
0), reinterpret_tensor(buf1, (16, 1, 4), (4, 4, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_eq_0[grid(256)](primals_8, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_8
buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
buf6 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
triton_poi_fused__softmax_div_masked_fill_1[grid(64)](buf4, buf3,
buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf7 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused__softmax_div_masked_fill_2[grid(256)](buf7, buf4,
buf5, buf6, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf8 = reinterpret_tensor(buf6, (16, 4, 1), (4, 1, 1), 0)
del buf6
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0), out=buf8)
buf9 = reinterpret_tensor(buf5, (16, 4), (4, 1), 0)
del buf5
extern_kernels.addmm(primals_10, reinterpret_tensor(buf8, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_9, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf9)
del primals_10
buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf11 = buf10
del buf10
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_mean_std_3[grid(16)](buf11, buf9, primals_1,
buf12, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf13 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_4[grid(64)](primals_11,
buf9, primals_1, buf12, buf11, primals_12, buf13, 64, XBLOCK=64,
num_warps=1, num_stages=1)
del buf11
del buf12
del primals_12
buf14 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_15, reinterpret_tensor(buf13, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_14, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf14)
del primals_15
buf15 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_17, reinterpret_tensor(primals_13, (16,
4), (4, 1), 0), reinterpret_tensor(primals_16, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf15)
del primals_16
del primals_17
buf16 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_19, reinterpret_tensor(primals_13, (16,
4), (4, 1), 0), reinterpret_tensor(primals_18, (4, 4), (1, 4),
0), alpha=1, beta=1, out=buf16)
del primals_18
del primals_19
buf17 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf14, (16, 4, 1), (4, 1, 1),
0), reinterpret_tensor(buf15, (16, 1, 4), (4, 4, 1), 0), out=buf17)
buf18 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_eq_0[grid(256)](primals_20, buf18, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del primals_20
buf19 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
buf20 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32)
triton_poi_fused__softmax_div_masked_fill_1[grid(64)](buf18, buf17,
buf19, buf20, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf21 = reinterpret_tensor(buf17, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf17
triton_poi_fused__softmax_div_masked_fill_2[grid(256)](buf21, buf18,
buf19, buf20, 256, XBLOCK=128, num_warps=4, num_stages=1)
buf22 = reinterpret_tensor(buf20, (16, 4, 1), (4, 1, 1), 0)
del buf20
extern_kernels.bmm(reinterpret_tensor(buf21, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf16, (16, 4, 1), (4, 1, 1), 0), out=buf22)
buf23 = reinterpret_tensor(buf19, (16, 4), (4, 1), 0)
del buf19
extern_kernels.mm(reinterpret_tensor(buf22, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_21, (4, 4), (1, 4), 0), out=buf23)
buf24 = reinterpret_tensor(buf23, (4, 4, 4), (16, 4, 1), 0)
del buf23
triton_poi_fused_add_5[grid(64)](buf24, primals_22, buf13, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_22
buf25 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_6[grid(64)](primals_23,
buf24, primals_24, buf25, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_24
buf26 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf25, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_25, (4, 4), (1, 4), 0), out=buf26)
buf27 = reinterpret_tensor(buf26, (4, 4, 4), (16, 4, 1), 0)
del buf26
buf31 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool)
triton_poi_fused_relu_threshold_backward_7[grid(64)](buf27,
primals_26, buf31, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_26
buf28 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf27, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_27, (4, 4), (1, 4), 0), out=buf28)
buf29 = reinterpret_tensor(buf28, (4, 4, 4), (16, 4, 1), 0)
del buf28
triton_poi_fused_add_5[grid(64)](buf29, primals_28, buf25, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_28
buf30 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_div_mean_mul_std_sub_6[grid(64)](primals_29,
buf29, primals_30, buf30, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_30
return (buf30, primals_1, primals_11, primals_23, primals_29, buf4,
buf7, reinterpret_tensor(buf8, (16, 4), (4, 1), 0), buf9,
reinterpret_tensor(buf13, (16, 4), (4, 1), 0), reinterpret_tensor(
primals_13, (16, 4), (4, 1), 0), buf18, buf21, reinterpret_tensor(
buf22, (16, 4), (4, 1), 0), buf24, reinterpret_tensor(buf25, (16, 4
), (4, 1), 0), reinterpret_tensor(buf27, (16, 4), (4, 1), 0), buf29,
primals_27, buf31, primals_25, primals_21, reinterpret_tensor(buf16,
(16, 1, 4), (4, 1, 1), 0), reinterpret_tensor(buf14, (16, 1, 4), (4,
1, 1), 0), reinterpret_tensor(buf15, (16, 4, 1), (4, 1, 4), 0),
primals_14, primals_9, reinterpret_tensor(buf2, (16, 1, 4), (4, 1,
1), 0), reinterpret_tensor(buf0, (16, 1, 4), (4, 1, 1), 0),
reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 4), 0))
class LayerNorm(nn.Module):
def __init__(self, d_model, eps=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(d_model))
self.beta = nn.Parameter(torch.zeros(d_model))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
out = (x - mean) / (std + self.eps)
out = self.gamma * out + self.beta
return out
class ScaleDotProductAttention(nn.Module):
"""
compute scale dot product attention
Query : given sentence that we focused on (decoder)
Key : every sentence to check relationship with Qeury(encoder)
Value : every sentence same with Key (encoder)
"""
def __init__(self):
super(ScaleDotProductAttention, self).__init__()
self.softmax = nn.Softmax()
def forward(self, q, k, v, mask=None, e=1e-12):
batch_size, head, length, d_tensor = k.size()
k_t = k.view(batch_size, head, d_tensor, length)
score = q @ k_t / math.sqrt(d_tensor)
if mask is not None:
score = score.masked_fill(mask == 0, -e)
score = self.softmax(score)
v = score @ v
return v, score
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, n_head):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.attention = ScaleDotProductAttention()
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
self.w_concat = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
q, k, v = self.w_q(q), self.w_k(k), self.w_v(v)
q, k, v = self.split(q), self.split(k), self.split(v)
out, _attention = self.attention(q, k, v, mask=mask)
out = self.concat(out)
out = self.w_concat(out)
return out
def split(self, tensor):
"""
split tensor by number of head
:param tensor: [batch_size, length, d_model]
:return: [batch_size, head, length, d_tensor]
"""
batch_size, length, d_model = tensor.size()
d_tensor = d_model // self.n_head
tensor = tensor.view(batch_size, self.n_head, length, d_tensor)
return tensor
def concat(self, tensor):
"""
inverse function of self.split(tensor : torch.Tensor)
:param tensor: [batch_size, head, length, d_tensor]
:return: [batch_size, length, d_model]
"""
batch_size, head, length, d_tensor = tensor.size()
d_model = head * d_tensor
tensor = tensor.view(batch_size, length, d_model)
return tensor
class PositionwiseFeedForward(nn.Module):
def __init__(self, d_model, hidden, drop_prob=0.1):
super(PositionwiseFeedForward, self).__init__()
self.linear1 = nn.Linear(d_model, hidden)
self.linear2 = nn.Linear(hidden, d_model)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(p=drop_prob)
def forward(self, x):
x = self.linear1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.linear2(x)
return x
class DecoderLayerNew(nn.Module):
def __init__(self, d_model, ffn_hidden, n_head, drop_prob):
super(DecoderLayerNew, self).__init__()
self.self_attention = MultiHeadAttention(d_model=d_model, n_head=n_head
)
self.norm1 = LayerNorm(d_model=d_model)
self.dropout1 = nn.Dropout(p=drop_prob)
self.enc_dec_attention = MultiHeadAttention(d_model=d_model, n_head
=n_head)
self.norm2 = LayerNorm(d_model=d_model)
self.dropout2 = nn.Dropout(p=drop_prob)
self.ffn = PositionwiseFeedForward(d_model=d_model, hidden=
ffn_hidden, drop_prob=drop_prob)
self.norm3 = LayerNorm(d_model=d_model)
self.dropout3 = nn.Dropout(p=drop_prob)
def forward(self, input_0, input_1, input_2, input_3):
primals_2 = self.self_attention.w_q.weight
primals_3 = self.self_attention.w_q.bias
primals_4 = self.self_attention.w_k.weight
primals_5 = self.self_attention.w_k.bias
primals_6 = self.self_attention.w_v.weight
primals_7 = self.self_attention.w_v.bias
primals_9 = self.self_attention.w_concat.weight
primals_10 = self.self_attention.w_concat.bias
primals_11 = self.norm1.gamma
primals_12 = self.norm1.beta
primals_14 = self.enc_dec_attention.w_q.weight
primals_15 = self.enc_dec_attention.w_q.bias
primals_16 = self.enc_dec_attention.w_k.weight
primals_17 = self.enc_dec_attention.w_k.bias
primals_18 = self.enc_dec_attention.w_v.weight
primals_19 = self.enc_dec_attention.w_v.bias
primals_21 = self.enc_dec_attention.w_concat.weight
primals_22 = self.enc_dec_attention.w_concat.bias
primals_23 = self.norm2.gamma
primals_24 = self.norm2.beta
primals_25 = self.ffn.linear1.weight
primals_26 = self.ffn.linear1.bias
primals_27 = self.ffn.linear2.weight
primals_28 = self.ffn.linear2.bias
primals_29 = self.norm3.gamma
primals_30 = self.norm3.beta
primals_1 = input_0
primals_13 = input_1
primals_8 = input_2
primals_20 = input_3
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])
return output[0]
|
jkimbf/transformer-1
|
DecoderLayer
| false
| 15,733
|
[
"Apache-2.0"
] | 233
|
6cd29731197822d6db641cdbfad3b045b8a294e4
|
https://github.com/jkimbf/transformer-1/tree/6cd29731197822d6db641cdbfad3b045b8a294e4
|
FirstResBlockDiscriminator
|
import torch
import numpy as np
from torch import nn
from torch.nn import Parameter
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.name = name
self.power_iterations = power_iterations
if not self._made_params():
self._make_params()
def _update_u_v(self):
u = getattr(self.module, self.name + '_u')
v = getattr(self.module, self.name + '_v')
w = getattr(self.module, self.name + '_bar')
height = w.data.shape[0]
for _ in range(self.power_iterations):
v.data = l2normalize(torch.mv(torch.t(w.view(height, -1).data),
u.data))
u.data = l2normalize(torch.mv(w.view(height, -1).data, v.data))
sigma = u.dot(w.view(height, -1).mv(v))
setattr(self.module, self.name, w / sigma.expand_as(w))
def _made_params(self):
try:
getattr(self.module, self.name + '_u')
getattr(self.module, self.name + '_v')
getattr(self.module, self.name + '_bar')
return True
except AttributeError:
return False
def _make_params(self):
w = getattr(self.module, self.name)
height = w.data.shape[0]
width = w.view(height, -1).data.shape[1]
u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False)
u.data = l2normalize(u.data)
v.data = l2normalize(v.data)
w_bar = Parameter(w.data)
del self.module._parameters[self.name]
self.module.register_parameter(self.name + '_u', u)
self.module.register_parameter(self.name + '_v', v)
self.module.register_parameter(self.name + '_bar', w_bar)
def forward(self, *args):
self._update_u_v()
return self.module.forward(*args)
class FirstResBlockDiscriminator(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(FirstResBlockDiscriminator, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1)
self.bypass_conv = nn.Conv2d(in_channels, out_channels, 1, 1, padding=0
)
nn.init.xavier_uniform_(self.conv1.weight.data, 1.0)
nn.init.xavier_uniform_(self.conv2.weight.data, 1.0)
nn.init.xavier_uniform_(self.bypass_conv.weight.data, np.sqrt(2))
self.model = nn.Sequential(SpectralNorm(self.conv1), nn.ReLU(),
SpectralNorm(self.conv2), nn.AvgPool2d(2))
self.bypass = nn.Sequential(nn.AvgPool2d(2), SpectralNorm(self.
bypass_conv))
def forward(self, x):
return self.model(x) + self.bypass(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
from torch import nn
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
@triton.jit
def triton_per_fused_add_div_linalg_vector_norm_mv_0(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
rnumel = 36
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, :]
rmask = rindex < rnumel
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, rmask, other=0.0)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.load(in_ptr0 + (36 + r0), rmask, other=0.0)
tmp5 = tl.load(in_ptr1 + 1)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp9 = tl.load(in_ptr0 + (72 + r0), rmask, other=0.0)
tmp10 = tl.load(in_ptr1 + 2)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr0 + (108 + r0), rmask, other=0.0)
tmp15 = tl.load(in_ptr1 + 3)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp18 * tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp22 = tl.where(rmask, tmp20, 0)
tmp23 = tl.sum(tmp22, 1)[:, None]
tmp24 = libdevice.sqrt(tmp23)
tmp25 = 1e-12
tmp26 = tmp24 + tmp25
tmp27 = tmp18 / tmp26
tl.store(out_ptr0 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp18, rmask)
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp26, None)
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp27, rmask)
@triton.jit
def triton_per_fused_div_mv_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 36
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, :]
rmask = rindex < rnumel
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 36 * x0), rmask & xmask, other=0.0)
tmp1 = tl.load(in_ptr1 + r1, rmask, eviction_policy='evict_last', other=0.0
)
tmp2 = tl.load(in_ptr2 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp4 = tmp1 / tmp3
tmp5 = tmp0 * tmp4
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp8 = tl.where(rmask & xmask, tmp6, 0)
tmp9 = tl.sum(tmp8, 1)[:, None]
tl.store(out_ptr0 + x0, tmp9, xmask)
@triton.jit
def triton_per_fused_add_div_linalg_vector_norm_2(in_ptr0, out_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.sum(tmp2, 1)[:, None]
tmp5 = libdevice.sqrt(tmp4)
tmp6 = 1e-12
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp8, None)
@triton.jit
def triton_per_fused_dot_3(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + r0, None)
tmp2 = tmp0 * tmp1
tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
tmp5 = tl.sum(tmp3, 1)[:, None]
tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp5, None)
@triton.jit
def triton_poi_fused_div_4(in_ptr0, in_ptr1, 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_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 / tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_6(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_avg_pool2d_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
x0 = xindex % 2
x1 = xindex // 2
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x1), xmask, eviction_policy=
'evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_per_fused_add_div_linalg_vector_norm_mv_8(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
tmp0 = tl.load(in_ptr0 + r0, None)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.load(in_ptr0 + (4 + r0), None)
tmp5 = tl.load(in_ptr1 + 1)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp9 = tl.load(in_ptr0 + (8 + r0), None)
tmp10 = tl.load(in_ptr1 + 2)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr0 + (12 + r0), None)
tmp15 = tl.load(in_ptr1 + 3)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp18 * tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp22 = tl.sum(tmp20, 1)[:, None]
tmp23 = libdevice.sqrt(tmp22)
tmp24 = 1e-12
tmp25 = tmp23 + tmp24
tmp26 = tmp18 / tmp25
tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp26, None)
@triton.jit
def triton_per_fused_add_div_dot_linalg_vector_norm_mv_9(in_ptr0, in_ptr1,
out_ptr2, out_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 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr1 + 1)
tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
tmp9 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr1 + 2)
tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
tmp14 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
tmp15 = tl.load(in_ptr1 + 3)
tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
tmp3 = tmp0 * tmp2
tmp7 = tmp4 * tmp6
tmp8 = tmp3 + tmp7
tmp12 = tmp9 * tmp11
tmp13 = tmp8 + tmp12
tmp17 = tmp14 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tmp18 * tmp18
tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK])
tmp22 = tl.sum(tmp20, 1)[:, None]
tmp23 = libdevice.sqrt(tmp22)
tmp24 = 1e-12
tmp25 = tmp23 + tmp24
tmp26 = tmp18 / tmp25
tmp27 = tmp26 * tmp18
tmp28 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK])
tmp30 = tl.sum(tmp28, 1)[:, None]
tl.store(out_ptr3 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp26, None)
tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp30, None)
@triton.jit
def triton_poi_fused_div_10(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + 0)
tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
tmp3 = tmp0 / tmp2
tl.store(out_ptr0 + x0, tmp3, xmask)
@triton.jit
def triton_poi_fused_add_avg_pool2d_convolution_11(in_out_ptr0, in_ptr0,
in_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x4 = xindex // 2
x5 = xindex
x2 = xindex // 4 % 4
tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x4), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x4), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x4), xmask, eviction_policy=
'evict_last')
tmp5 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x4), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_out_ptr0 + x5, xmask)
tmp10 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp2 = tmp1 + tmp0
tmp4 = tmp3 + tmp2
tmp6 = tmp5 + tmp4
tmp7 = 0.25
tmp8 = tmp6 * tmp7
tmp11 = tmp9 + tmp10
tmp12 = tmp8 + tmp11
tl.store(in_out_ptr0 + x5, 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,))
assert_size_stride(primals_2, (36,), (1,))
assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (36,), (1,))
assert_size_stride(primals_8, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_13, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((36,), (1,), torch.float32)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
buf35 = empty_strided_cuda((36,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_add_div_linalg_vector_norm_mv_0[grid(1)](buf2,
primals_3, primals_1, buf0, buf35, 1, 36, XBLOCK=1, num_warps=2,
num_stages=1)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_div_mv_1[grid(4)](primals_3, buf0, buf2, buf3, 4,
36, XBLOCK=1, num_warps=2, num_stages=1)
buf5 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_2[grid(1)](buf3, buf5,
1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf6 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_dot_3[grid(1)](buf5, buf3, buf6, 1, 4, XBLOCK=1,
num_warps=2, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
triton_poi_fused_div_4[grid(144)](primals_3, buf6, buf7, 144,
XBLOCK=256, num_warps=4, num_stages=1)
buf8 = extern_kernels.convolution(primals_5, buf7, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 4, 4, 4), (64, 16, 4, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_5[grid(256)](buf9, primals_4, 256,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_4
buf10 = empty_strided_cuda((36,), (1,), torch.float32)
buf11 = empty_strided_cuda((), (), torch.float32)
buf12 = buf11
del buf11
buf44 = empty_strided_cuda((36,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_mv_0[grid(1)](buf12,
primals_8, primals_6, buf10, buf44, 1, 36, XBLOCK=1, num_warps=
2, num_stages=1)
buf13 = buf3
del buf3
triton_per_fused_div_mv_1[grid(4)](primals_8, buf10, buf12, buf13,
4, 36, XBLOCK=1, num_warps=2, num_stages=1)
buf15 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_div_linalg_vector_norm_2[grid(1)](buf13, buf15,
1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf16 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_dot_3[grid(1)](buf15, buf13, buf16, 1, 4, XBLOCK=1,
num_warps=2, num_stages=1)
buf17 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.float32)
triton_poi_fused_div_4[grid(144)](primals_8, buf16, buf17, 144,
XBLOCK=256, num_warps=4, num_stages=1)
buf18 = extern_kernels.convolution(buf9, buf17, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf18, (4, 4, 4, 4), (64, 16, 4, 1))
buf19 = buf18
del buf18
triton_poi_fused_convolution_6[grid(256)](buf19, primals_9, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf20 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
triton_poi_fused_avg_pool2d_7[grid(64)](primals_5, buf20, 64,
XBLOCK=64, num_warps=1, num_stages=1)
buf23 = buf13
del buf13
triton_per_fused_add_div_linalg_vector_norm_mv_8[grid(1)](primals_12,
primals_10, buf23, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
buf26 = empty_strided_cuda((), (), torch.float32)
buf48 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_add_div_dot_linalg_vector_norm_mv_9[grid(1)](
primals_12, buf23, buf26, buf48, 1, 4, XBLOCK=1, num_warps=2,
num_stages=1)
buf27 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32)
triton_poi_fused_div_10[grid(16)](primals_12, buf26, buf27, 16,
XBLOCK=16, num_warps=1, num_stages=1)
del buf26
buf28 = extern_kernels.convolution(buf20, buf27, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf28, (4, 4, 2, 2), (16, 4, 2, 1))
buf29 = buf28
del buf28
triton_poi_fused_add_avg_pool2d_convolution_11[grid(64)](buf29,
buf19, primals_13, 64, XBLOCK=64, num_warps=1, num_stages=1)
del primals_13
buf30 = torch.ops.aten.set_.source_Tensor(primals_1, buf5)
assert_size_stride(buf30, (4,), (1,))
del buf0
buf36 = torch.ops.aten.set_.source_Tensor(primals_2, buf35)
assert_size_stride(buf36, (36,), (1,))
del primals_2
buf39 = torch.ops.aten.set_.source_Tensor(primals_6, buf15)
assert_size_stride(buf39, (4,), (1,))
del buf10
buf45 = torch.ops.aten.set_.source_Tensor(primals_7, buf44)
assert_size_stride(buf45, (36,), (1,))
del primals_7
buf49 = torch.ops.aten.set_.source_Tensor(primals_10, buf48)
assert_size_stride(buf49, (4,), (1,))
del primals_10
buf53 = torch.ops.aten.set_.source_Tensor(primals_11, buf23)
assert_size_stride(buf53, (4,), (1,))
del primals_11
return (buf29, buf7, buf17, buf27, primals_1, primals_3, primals_5,
primals_6, primals_8, primals_12, buf2, buf5, buf6, buf7, buf9,
buf12, buf15, buf16, buf17, buf19, buf20, buf23, buf27)
def l2normalize(v, eps=1e-12):
return v / (v.norm() + eps)
class SpectralNorm(nn.Module):
def __init__(self, module, name='weight', power_iterations=1):
super(SpectralNorm, self).__init__()
self.module = module
self.name = name
self.power_iterations = power_iterations
if not self._made_params():
self._make_params()
def _update_u_v(self):
u = getattr(self.module, self.name + '_u')
v = getattr(self.module, self.name + '_v')
w = getattr(self.module, self.name + '_bar')
height = w.data.shape[0]
for _ in range(self.power_iterations):
v.data = l2normalize(torch.mv(torch.t(w.view(height, -1).data),
u.data))
u.data = l2normalize(torch.mv(w.view(height, -1).data, v.data))
sigma = u.dot(w.view(height, -1).mv(v))
setattr(self.module, self.name, w / sigma.expand_as(w))
def _made_params(self):
try:
getattr(self.module, self.name + '_u')
getattr(self.module, self.name + '_v')
getattr(self.module, self.name + '_bar')
return True
except AttributeError:
return False
def _make_params(self):
w = getattr(self.module, self.name)
height = w.data.shape[0]
width = w.view(height, -1).data.shape[1]
u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False)
v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False)
u.data = l2normalize(u.data)
v.data = l2normalize(v.data)
w_bar = Parameter(w.data)
del self.module._parameters[self.name]
self.module.register_parameter(self.name + '_u', u)
self.module.register_parameter(self.name + '_v', v)
self.module.register_parameter(self.name + '_bar', w_bar)
def forward(self, *args):
self._update_u_v()
return self.module.forward(*args)
class FirstResBlockDiscriminatorNew(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(FirstResBlockDiscriminatorNew, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, 1, padding=1)
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, 1, padding=1)
self.bypass_conv = nn.Conv2d(in_channels, out_channels, 1, 1, padding=0
)
nn.init.xavier_uniform_(self.conv1.weight.data, 1.0)
nn.init.xavier_uniform_(self.conv2.weight.data, 1.0)
nn.init.xavier_uniform_(self.bypass_conv.weight.data, np.sqrt(2))
self.model = nn.Sequential(SpectralNorm(self.conv1), nn.ReLU(),
SpectralNorm(self.conv2), nn.AvgPool2d(2))
self.bypass = nn.Sequential(nn.AvgPool2d(2), SpectralNorm(self.
bypass_conv))
def forward(self, input_0):
primals_1 = self.conv1.bias
primals_4 = self.conv1.weight_u
primals_2 = self.conv1.weight_v
primals_3 = self.conv1.weight_bar
primals_6 = self.conv2.bias
primals_9 = self.conv2.weight_u
primals_7 = self.conv2.weight_v
primals_8 = self.conv2.weight_bar
primals_10 = self.bypass_conv.bias
primals_11 = self.bypass_conv.weight_u
primals_13 = self.bypass_conv.weight_v
primals_12 = self.bypass_conv.weight_bar
primals_5 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13])
return output[0]
|
jingyang2017/Face-and-Image-super-resolution
|
FirstResBlockDiscriminator
| false
| 15,734
|
[
"MIT"
] | 215
|
0351b5f7c71013f022a972306afd036f1af3a8e6
|
https://github.com/jingyang2017/Face-and-Image-super-resolution/tree/0351b5f7c71013f022a972306afd036f1af3a8e6
|
Attention
|
import torch
import torch.nn as nn
class Encoder(nn.Module):
def __init__(self, dim, dim_embed):
super(Encoder, self).__init__()
self.embed = nn.Conv1d(dim, dim_embed, 1)
return
def forward(self, input):
input_2 = input.permute(0, 2, 1)
out = self.embed(input_2)
return out.permute(0, 2, 1)
class Attention(nn.Module):
def __init__(self, dim_embed, embeding_type='conv1d', tanh_exp=0):
super(Attention, self).__init__()
self.dim_embed = dim_embed
if embeding_type == 'conv1d':
self.proj = Encoder(dim_embed, dim_embed)
self.w_a = Encoder(dim_embed * 3, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
else:
self.proj = nn.Linear(dim_embed, dim_embed)
self.w_a = nn.Linear(dim_embed * 3, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
self.tanh_exp = tanh_exp
return
def forward(self, encoded_static, encoded_dynamic, decoder_output):
n_nodes = encoded_static.shape[1]
x_t = torch.cat((encoded_static, encoded_dynamic), dim=2)
proj_dec = self.proj(decoder_output.unsqueeze(1)).repeat(1, n_nodes, 1)
hidden = torch.cat((x_t, proj_dec), dim=2)
u_t = torch.matmul(self.v_a, torch.tanh(self.w_a(hidden)).permute(0,
2, 1))
if self.tanh_exp > 0:
logits = self.tanh_exp * torch.tanh(u_t)
else:
logits = u_t
return logits
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'dim_embed': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 192
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x3 = xindex // 12
x2 = xindex // 48
x4 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 8, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.full([1], 4, tl.int64)
tmp6 = tmp0 < tmp5
tmp7 = tmp6 & tmp4
tmp8 = tl.load(in_ptr0 + (4 * x3 + x0), tmp7 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp9 = tmp0 >= tmp5
tmp10 = tmp9 & tmp4
tmp11 = tl.load(in_ptr1 + (4 * x3 + (-4 + x0)), tmp10 & xmask,
eviction_policy='evict_last', other=0.0)
tmp12 = tl.where(tmp6, tmp8, tmp11)
tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
tmp14 = tl.where(tmp4, tmp12, tmp13)
tmp15 = tmp0 >= tmp3
tl.full([1], 12, tl.int64)
tmp18 = tl.load(in_ptr2 + (4 * x2 + (-8 + x0)), tmp15 & xmask,
eviction_policy='evict_last', other=0.0)
tmp19 = tl.load(in_ptr3 + (-8 + x0), tmp15 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp20 = tmp18 + tmp19
tmp21 = tl.full(tmp20.shape, 0.0, tmp20.dtype)
tmp22 = tl.where(tmp15, tmp20, tmp21)
tmp23 = tl.where(tmp4, tmp14, tmp22)
tl.store(out_ptr0 + x4, tmp23, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 48
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 % 12
y1 = yindex // 12
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_mv_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + (16 * (x0 // 4) + x0 % 4), xmask)
tmp2 = tl.load(in_ptr1 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp5 = tl.load(in_ptr0 + (4 + 16 * (x0 // 4) + x0 % 4), xmask)
tmp7 = tl.load(in_ptr1 + 1)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (8 + 16 * (x0 // 4) + x0 % 4), xmask)
tmp13 = tl.load(in_ptr1 + 2)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp17 = tl.load(in_ptr0 + (12 + 16 * (x0 // 4) + x0 % 4), xmask)
tmp19 = tl.load(in_ptr1 + 3)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp1 = libdevice.tanh(tmp0)
tmp4 = tmp1 * tmp3
tmp6 = libdevice.tanh(tmp5)
tmp9 = tmp6 * tmp8
tmp10 = tmp4 + tmp9
tmp12 = libdevice.tanh(tmp11)
tmp15 = tmp12 * tmp14
tmp16 = tmp10 + tmp15
tmp18 = libdevice.tanh(tmp17)
tmp21 = tmp18 * tmp20
tmp22 = tmp16 + tmp21
tl.store(out_ptr0 + x0, tmp22, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 12, 1), (12, 1, 1))
assert_size_stride(primals_8, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (4,
4, 1), (4, 1, 4), 0), primals_4, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (4, 4, 1), (4, 1, 1))
buf1 = empty_strided_cuda((4, 4, 12), (48, 12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(192)](primals_1, primals_2, buf0,
primals_5, buf1, 192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_2
del primals_5
buf2 = empty_strided_cuda((4, 12, 4), (48, 4, 1), torch.float32)
triton_poi_fused_convolution_1[grid(48, 4)](buf1, buf2, 48, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
buf3 = extern_kernels.convolution(buf2, primals_7, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4), (16, 4, 1))
del buf2
buf4 = buf3
del buf3
triton_poi_fused_convolution_2[grid(64)](buf4, primals_8, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_8
buf5 = reinterpret_tensor(buf0, (16,), (1,), 0)
del buf0
triton_poi_fused_mv_3[grid(16)](buf4, primals_6, buf5, 16, XBLOCK=
16, num_warps=1, num_stages=1)
return reinterpret_tensor(buf5, (4, 4), (4, 1), 0
), primals_4, primals_6, primals_7, reinterpret_tensor(primals_3, (
4, 4, 1), (4, 1, 4), 0), reinterpret_tensor(buf1, (4, 12, 4), (48,
1, 12), 0), buf4
class Encoder(nn.Module):
def __init__(self, dim, dim_embed):
super(Encoder, self).__init__()
self.embed = nn.Conv1d(dim, dim_embed, 1)
return
def forward(self, input):
input_2 = input.permute(0, 2, 1)
out = self.embed(input_2)
return out.permute(0, 2, 1)
class AttentionNew(nn.Module):
def __init__(self, dim_embed, embeding_type='conv1d', tanh_exp=0):
super(AttentionNew, self).__init__()
self.dim_embed = dim_embed
if embeding_type == 'conv1d':
self.proj = Encoder(dim_embed, dim_embed)
self.w_a = Encoder(dim_embed * 3, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
else:
self.proj = nn.Linear(dim_embed, dim_embed)
self.w_a = nn.Linear(dim_embed * 3, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
self.tanh_exp = tanh_exp
return
def forward(self, input_0, input_1, input_2):
primals_5 = self.v_a
primals_4 = self.proj.embed.weight
primals_6 = self.proj.embed.bias
primals_7 = self.w_a.embed.weight
primals_8 = self.w_a.embed.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
jomavera/DRL_HFV
|
Attention
| false
| 15,735
|
[
"MIT"
] | 114
|
043e32805ec79fd35281b864659c194d7b89f5bc
|
https://github.com/jomavera/DRL_HFV/tree/043e32805ec79fd35281b864659c194d7b89f5bc
|
ShortWave
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalConv1d(nn.Conv1d):
def __init__(self, input_size, hidden_size, kernel_size, stride=1,
dilation=1, groups=1, bias=True, sigmoid=None, tanh=None):
self.left_padding = (kernel_size - 1) * dilation
super(CausalConv1d, self).__init__(input_size, hidden_size,
kernel_size, stride=stride, padding=0, dilation=dilation,
groups=groups, bias=bias)
def forward(self, input):
x = F.pad(input.permute(1, 2, 0), (self.left_padding, 0))
conv_out = super(CausalConv1d, self).forward(x)
return conv_out.permute(2, 0, 1)
class ShortWave(nn.Module):
def __init__(self, input_size, hidden_size, layers=3):
super(ShortWave, self).__init__()
self.layers = []
prev_size = input_size
for layer in range(layers):
conv = CausalConv1d(prev_size, hidden_size, kernel_size=2,
dilation=1)
self.layers.append(conv)
self.add_module('layer' + str(layer), conv)
prev_size = hidden_size
def forward(self, data):
for layer in self.layers:
data = layer(data)
return data
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_constant_pad_nd_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 5
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 = -1 + x1
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.load(in_ptr0 + (-16 + y0 + 16 * x1), tmp2 & xmask & ymask,
eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x1 + 5 * y0), tmp3, xmask & ymask)
@triton.jit
def triton_poi_fused_constant_pad_nd_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 80
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 5
x3 = xindex // 5
x1 = xindex // 5 % 4
x4 = xindex
tmp0 = -1 + x0
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.load(in_ptr0 + (-1 + x0 + 4 * x3), tmp2 & xmask, other=0.0)
tmp4 = tl.load(in_ptr1 + x1, tmp2 & xmask, eviction_policy='evict_last',
other=0.0)
tmp5 = tmp3 + tmp4
tmp6 = tl.full(tmp5.shape, 0.0, tmp5.dtype)
tmp7 = tl.where(tmp2, tmp5, tmp6)
tl.store(out_ptr0 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(16, 5)](primals_1, buf0, 16,
5, XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf2 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
triton_poi_fused_constant_pad_nd_1[grid(80)](buf1, primals_3, buf2,
80, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_3
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4), (16, 4, 1))
buf4 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
triton_poi_fused_constant_pad_nd_1[grid(80)](buf3, primals_5, buf4,
80, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
del primals_5
buf5 = extern_kernels.convolution(buf4, primals_6, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf5, (4, 4, 4), (16, 4, 1))
buf6 = buf5
del buf5
triton_poi_fused_convolution_2[grid(64)](buf6, primals_7, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_7
return reinterpret_tensor(buf6, (4, 4, 4), (1, 16, 4), 0
), primals_2, primals_4, primals_6, buf0, buf2, buf4
class CausalConv1d(nn.Conv1d):
def __init__(self, input_size, hidden_size, kernel_size, stride=1,
dilation=1, groups=1, bias=True, sigmoid=None, tanh=None):
self.left_padding = (kernel_size - 1) * dilation
super(CausalConv1d, self).__init__(input_size, hidden_size,
kernel_size, stride=stride, padding=0, dilation=dilation,
groups=groups, bias=bias)
def forward(self, input):
x = F.pad(input.permute(1, 2, 0), (self.left_padding, 0))
conv_out = super(CausalConv1d, self).forward(x)
return conv_out.permute(2, 0, 1)
class ShortWaveNew(nn.Module):
def __init__(self, input_size, hidden_size, layers=3):
super(ShortWaveNew, self).__init__()
self.layers = []
prev_size = input_size
for layer in range(layers):
conv = CausalConv1d(prev_size, hidden_size, kernel_size=2,
dilation=1)
self.layers.append(conv)
self.add_module('layer' + str(layer), conv)
prev_size = hidden_size
def forward(self, input_0):
primals_2 = self.layer0.weight
primals_3 = self.layer0.bias
primals_4 = self.layer1.weight
primals_5 = self.layer1.bias
primals_6 = self.layer2.weight
primals_7 = self.layer2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
jpeg729/pytorch-bits
|
ShortWave
| false
| 15,736
|
[
"MIT"
] | 73
|
5d107094042c27472dfb7dee77506b603f5d3e45
|
https://github.com/jpeg729/pytorch-bits/tree/5d107094042c27472dfb7dee77506b603f5d3e45
|
CausalConv1d
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalConv1d(nn.Conv1d):
def __init__(self, input_size, hidden_size, kernel_size, stride=1,
dilation=1, groups=1, bias=True, sigmoid=None, tanh=None):
self.left_padding = (kernel_size - 1) * dilation
super(CausalConv1d, self).__init__(input_size, hidden_size,
kernel_size, stride=stride, padding=0, dilation=dilation,
groups=groups, bias=bias)
def forward(self, input):
x = F.pad(input.permute(1, 2, 0), (self.left_padding, 0))
conv_out = super(CausalConv1d, self).forward(x)
return conv_out.permute(2, 0, 1)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4, 'kernel_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_constant_pad_nd_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 7
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x1 = xindex
y0 = yindex
tmp0 = -3 + x1
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.load(in_ptr0 + (-48 + y0 + 16 * x1), tmp2 & xmask & ymask,
eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x1 + 7 * y0), tmp3, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 7), (28, 7, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(16, 7)](primals_1, buf0, 16,
7, XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
return reinterpret_tensor(buf2, (4, 4, 4), (1, 16, 4), 0), primals_2, buf0
class CausalConv1dNew(nn.Conv1d):
def __init__(self, input_size, hidden_size, kernel_size, stride=1,
dilation=1, groups=1, bias=True, sigmoid=None, tanh=None):
self.left_padding = (kernel_size - 1) * dilation
super(CausalConv1dNew, self).__init__(input_size, hidden_size,
kernel_size, stride=stride, padding=0, dilation=dilation,
groups=groups, bias=bias)
def forward(self, input_0):
primals_1 = self.weight
primals_3 = self.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jpeg729/pytorch-bits
|
CausalConv1d
| false
| 15,737
|
[
"MIT"
] | 73
|
5d107094042c27472dfb7dee77506b603f5d3e45
|
https://github.com/jpeg729/pytorch-bits/tree/5d107094042c27472dfb7dee77506b603f5d3e45
|
SparseGate
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
import torch.optim
import torch.utils.data
class SparseGate(nn.Module):
def __init__(self, in_features, n_experts, k=2):
"""
Returns a sparsely gated noisy softmax.
See OUTRAGEOUSLY LARGE NEURAL NETWORKS:
THE SPARSELY-GATED MIXTURE-OF-EXPERTS LAYER
Shazeer et. al
Link: https://arxiv.org/pdf/1701.06538.pdf
"""
assert k > 1, 'Need k >= 1. If k == 1, then derivatives are zero everywhere.'
super(SparseGate, self).__init__()
self.gate_weights = Parameter(torch.Tensor(n_experts, in_features))
self.noise_weights = Parameter(torch.Tensor(n_experts, in_features))
self.n_experts = n_experts
self.n_selected = k
self.reset_parameters()
def forward(self, x):
batch_size = x.size(0)
noise = x.new_empty((batch_size, self.n_experts)).normal_()
expert_weights = F.linear(x, self.gate_weights, None
) + noise * F.softplus(F.linear(x, self.noise_weights, None))
top_k, indices = torch.topk(expert_weights, self.n_selected)
top_k_softmax = F.softmax(top_k, dim=1)
res = x.new_full((batch_size, self.n_experts), 0.0)
return res.scatter_(1, indices, top_k_softmax)
def reset_parameters(self):
nn.init.constant_(self.gate_weights, 0.0)
nn.init.constant_(self.noise_weights, 0.0)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_features': 4, 'n_experts': 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
from torch.nn import Parameter
import torch.optim
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mul_softplus_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x0, xmask)
tmp2 = 20.0
tmp3 = tmp1 > tmp2
tmp4 = tl_math.exp(tmp1)
tmp5 = libdevice.log1p(tmp4)
tmp6 = tl.where(tmp3, tmp1, tmp5)
tmp7 = tmp0 * tmp6
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_poi_fused_new_full_scatter_1(out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = 0.0
tl.store(out_ptr0 + x0, tmp0, xmask)
@triton.jit
def triton_poi_fused__softmax_new_full_scatter_2(in_ptr0, in_ptr1, out_ptr0,
out_ptr1, xnumel, XBLOCK: tl.constexpr):
xnumel = 8
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 2
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 2 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 2 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr1 + x2, xmask)
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp4 = tmp0 - tmp3
tmp5 = tl_math.exp(tmp4)
tmp6 = tmp1 - tmp3
tmp7 = tl_math.exp(tmp6)
tmp8 = tmp2 - tmp3
tmp9 = tl_math.exp(tmp8)
tmp10 = tmp7 + tmp9
tmp11 = tmp5 / tmp10
tl.device_assert((0 <= tmp12) & (tmp12 < 4) | ~xmask,
'index out of bounds: 0 <= tmp12 < 4')
tl.store(out_ptr0 + x2, tmp11, xmask)
tl.store(out_ptr1 + (tmp12 + 4 * x1), tmp11, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = torch.ops.aten.normal_functional.default(buf0)
buf2 = buf1
del buf1
buf3 = buf0
del buf0
extern_kernels.mm(primals_1, reinterpret_tensor(primals_3, (4, 4),
(1, 4), 0), out=buf3)
del primals_3
buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_softplus_0[grid(16)](buf2, buf3, buf4, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(buf4, primals_1, reinterpret_tensor(primals_2,
(4, 4), (1, 4), 0), alpha=1, beta=1, out=buf5)
del buf4
del primals_2
buf6 = torch.ops.aten.topk.default(buf5, 2)
buf7 = buf6[0]
buf8 = buf6[1]
del buf6
buf10 = buf5
del buf5
triton_poi_fused_new_full_scatter_1[grid(16)](buf10, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((4, 2), (2, 1), torch.float32)
triton_poi_fused__softmax_new_full_scatter_2[grid(8)](buf7, buf8,
buf9, buf10, 8, XBLOCK=8, num_warps=1, num_stages=1)
del buf7
return buf10, primals_1, buf2, buf3, buf8, buf9
class SparseGateNew(nn.Module):
def __init__(self, in_features, n_experts, k=2):
"""
Returns a sparsely gated noisy softmax.
See OUTRAGEOUSLY LARGE NEURAL NETWORKS:
THE SPARSELY-GATED MIXTURE-OF-EXPERTS LAYER
Shazeer et. al
Link: https://arxiv.org/pdf/1701.06538.pdf
"""
assert k > 1, 'Need k >= 1. If k == 1, then derivatives are zero everywhere.'
super(SparseGateNew, self).__init__()
self.gate_weights = Parameter(torch.Tensor(n_experts, in_features))
self.noise_weights = Parameter(torch.Tensor(n_experts, in_features))
self.n_experts = n_experts
self.n_selected = k
self.reset_parameters()
def reset_parameters(self):
nn.init.constant_(self.gate_weights, 0.0)
nn.init.constant_(self.noise_weights, 0.0)
def forward(self, input_0):
primals_1 = self.gate_weights
primals_2 = self.noise_weights
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jozhang97/Side-tuning
|
SparseGate
| false
| 15,738
|
[
"MIT"
] | 56
|
dea345691fb7ee0230150fe56ddd644efdffa6ac
|
https://github.com/jozhang97/Side-tuning/tree/dea345691fb7ee0230150fe56ddd644efdffa6ac
|
KL_loss
|
import torch
import torch.nn.functional
class KL_loss(torch.nn.Module):
def __init__(self):
super(KL_loss, self).__init__()
def forward(self, mu, logvar):
KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar
)
KLD = torch.sum(KLD_element).mul_(-0.5)
return KLD
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.functional
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_exp_mul_pow_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp2 = tl.load(in_ptr1 + r0, None)
tmp1 = tmp0 * tmp0
tmp3 = tl_math.exp(tmp2)
tmp4 = tmp1 + tmp3
tmp5 = -1.0
tmp6 = tmp4 * tmp5
tmp7 = 1.0
tmp8 = tmp6 + tmp7
tmp9 = tmp8 + tmp2
tmp10 = tl.broadcast_to(tmp9, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp13 = -0.5
tmp14 = tmp12 * tmp13
tl.debug_barrier()
tl.store(in_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)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_add_exp_mul_pow_sum_0[grid(1)](buf1, arg0_1,
arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class KL_lossNew(torch.nn.Module):
def __init__(self):
super(KL_lossNew, 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]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
KL_loss
| false
| 15,739
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
VGGBase
|
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from itertools import product as product
def decimate(tensor, m):
"""
Decimate a tensor by a factor 'm', i.e. downsample by keeping every 'm'th value.
This is used when we convert FC layers to equivalent Convolutional layers, BUT of a smaller size.
:param tensor: tensor to be decimated
:param m: list of decimation factors for each dimension of the tensor; None if not to be decimated along a dimension
:return: decimated tensor
"""
assert tensor.dim() == len(m)
for d in range(tensor.dim()):
if m[d] is not None:
tensor = tensor.index_select(dim=d, index=torch.arange(start=0,
end=tensor.size(d), step=m[d]).long())
return tensor
class VGGBase(nn.Module):
"""
VGG base convolutions to produce lower-level feature maps.
"""
def __init__(self):
super(VGGBase, self).__init__()
self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, padding=1)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, padding=1)
self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)
self.conv7 = nn.Conv2d(1024, 1024, kernel_size=1)
def forward(self, image):
"""
Forward propagation.
:param image: images, a tensor of dimensions (N, 3, 300, 300)
:return: lower-level feature maps conv4_3 and conv7
"""
out = F.relu(self.conv1_1(image))
out = F.relu(self.conv1_2(out))
out = self.pool1(out)
out = F.relu(self.conv2_1(out))
out = F.relu(self.conv2_2(out))
out = self.pool2(out)
out = F.relu(self.conv3_1(out))
out = F.relu(self.conv3_2(out))
out = F.relu(self.conv3_3(out))
out = self.pool3(out)
out = F.relu(self.conv4_1(out))
out = F.relu(self.conv4_2(out))
out = F.relu(self.conv4_3(out))
conv4_3_feats = out
out = self.pool4(out)
out = F.relu(self.conv5_1(out))
out = F.relu(self.conv5_2(out))
out = F.relu(self.conv5_3(out))
out = self.pool5(out)
out = F.relu(self.conv6(out))
conv7_feats = F.relu(self.conv7(out))
return conv4_3_feats, conv7_feats
def load_pretrained_layers(self):
"""
As in the paper, we use a VGG-16 pretrained on the ImageNet task as the base network.
There's one available in PyTorch, see https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.vgg16
We copy these parameters into our network. It's straightforward for conv1 to conv5.
However, the original VGG-16 does not contain the conv6 and con7 layers.
Therefore, we convert fc6 and fc7 into convolutional layers, and subsample by decimation. See 'decimate' in utils.py.
"""
state_dict = self.state_dict()
param_names = list(state_dict.keys())
pretrained_state_dict = torchvision.models.vgg16(pretrained=True
).state_dict()
pretrained_param_names = list(pretrained_state_dict.keys())
for i, param in enumerate(param_names[:-4]):
state_dict[param] = pretrained_state_dict[pretrained_param_names[i]
]
conv_fc6_weight = pretrained_state_dict['classifier.0.weight'].view(
4096, 512, 7, 7)
conv_fc6_bias = pretrained_state_dict['classifier.0.bias']
state_dict['conv6.weight'] = decimate(conv_fc6_weight, m=[4, None,
3, 3])
state_dict['conv6.bias'] = decimate(conv_fc6_bias, m=[4])
conv_fc7_weight = pretrained_state_dict['classifier.3.weight'].view(
4096, 4096, 1, 1)
conv_fc7_bias = pretrained_state_dict['classifier.3.bias']
state_dict['conv7.weight'] = decimate(conv_fc7_weight, m=[4, 4,
None, None])
state_dict['conv7.bias'] = decimate(conv_fc7_bias, m=[4])
self.load_state_dict(state_dict)
None
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 torchvision
import torch.nn as nn
from itertools import product as product
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 192
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 3
y1 = yindex // 3
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 3 * x2 + 27 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_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 % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 64
y1 = yindex // 64
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 64 * x2 + 576 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_4(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_6(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 256
y1 = yindex // 256
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_8(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 512 * x2 + 4608 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_9(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
)
tl.store(out_ptr0 + (y0 + 512 * x2 + 4608 * y1), tmp0, xmask)
@triton.jit
def triton_poi_fused_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)
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_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 % 64
x1 = xindex // 64 % 32
x2 = xindex // 2048
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 128 * x1 + 8192 * x2), None)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 128 * x1 + 8192 * x2), None)
tmp3 = tl.load(in_ptr0 + (4096 + x0 + 128 * x1 + 8192 * x2), None)
tmp5 = tl.load(in_ptr0 + (4160 + x0 + 128 * x1 + 8192 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_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)
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_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 % 128
x1 = xindex // 128 % 16
x2 = xindex // 2048
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * x1 + 8192 * x2), None)
tmp1 = tl.load(in_ptr0 + (128 + x0 + 256 * x1 + 8192 * x2), None)
tmp3 = tl.load(in_ptr0 + (4096 + x0 + 256 * x1 + 8192 * x2), None)
tmp5 = tl.load(in_ptr0 + (4224 + x0 + 256 * x1 + 8192 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_14(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 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_15(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x0 = xindex % 256
x1 = xindex // 256 % 8
x2 = xindex // 2048
x3 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 512 * x1 + 8192 * x2), None)
tmp1 = tl.load(in_ptr0 + (256 + x0 + 512 * x1 + 8192 * x2), None)
tmp3 = tl.load(in_ptr0 + (4096 + x0 + 512 * x1 + 8192 * x2), None)
tmp5 = tl.load(in_ptr0 + (4352 + x0 + 512 * x1 + 8192 * x2), None)
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1], 1, tl.int8)
tmp9 = tl.full([1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + x3, tmp6, None)
tl.store(out_ptr1 + x3, tmp16, None)
@triton.jit
def triton_poi_fused_convolution_relu_16(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_17(in_ptr0, in_ptr1, out_ptr0, ynumel,
xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 64
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 + 32768 * 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)
tl.store(out_ptr0 + (x2 + 64 * y3), tmp4, xmask)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_18(in_ptr0, 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 % 4
x3 = xindex // 4
y4 = yindex
x5 = xindex
y0 = yindex % 512
y1 = yindex // 512
tmp0 = tl.load(in_ptr0 + (2 * x2 + 16 * x3 + 64 * y4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x2 + 16 * x3 + 64 * y4), xmask,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (8 + 2 * x2 + 16 * x3 + 64 * y4), xmask,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (9 + 2 * x2 + 16 * x3 + 64 * y4), xmask,
eviction_policy='evict_last')
tmp2 = triton_helpers.maximum(tmp1, tmp0)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp6 = triton_helpers.maximum(tmp5, tmp4)
tmp7 = tmp1 > tmp0
tmp8 = tl.full([1, 1], 1, tl.int8)
tmp9 = tl.full([1, 1], 0, tl.int8)
tmp10 = tl.where(tmp7, tmp8, tmp9)
tmp11 = tmp3 > tmp2
tmp12 = tl.full([1, 1], 2, tl.int8)
tmp13 = tl.where(tmp11, tmp12, tmp10)
tmp14 = tmp5 > tmp4
tmp15 = tl.full([1, 1], 3, tl.int8)
tmp16 = tl.where(tmp14, tmp15, tmp13)
tl.store(out_ptr0 + (y0 + 512 * x5 + 8192 * y1), tmp6, xmask)
tl.store(out_ptr1 + (y0 + 512 * x5 + 8192 * y1), tmp16, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_19(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex
x0 = xindex % 512
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_max_pool2d_with_indices_20(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x2 = xindex // 2048 % 4
x1 = xindex // 512 % 4
x6 = xindex
tmp0 = -1 + x2
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 + x1
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-2560 + x6), tmp10, other=float('-inf'))
tmp12 = x1
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-2048 + x6), tmp16, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + x1
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-1536 + x6), tmp23, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = x2
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (-512 + x6), tmp30, other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + x6, tmp33, other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (512 + x6), tmp36, other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = 1 + x2
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (1536 + x6), tmp43, other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp38)
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (2048 + x6), tmp46, other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (2560 + x6), tmp49, other=float('-inf'))
tmp51 = triton_helpers.maximum(tmp50, tmp48)
tmp52 = tmp17 > tmp11
tmp53 = tl.full([1], 1, tl.int8)
tmp54 = tl.full([1], 0, tl.int8)
tmp55 = tl.where(tmp52, tmp53, tmp54)
tmp56 = tmp24 > tmp18
tmp57 = tl.full([1], 2, tl.int8)
tmp58 = tl.where(tmp56, tmp57, tmp55)
tmp59 = tmp31 > tmp25
tmp60 = tl.full([1], 3, tl.int8)
tmp61 = tl.where(tmp59, tmp60, tmp58)
tmp62 = tmp34 > tmp32
tmp63 = tl.full([1], 4, tl.int8)
tmp64 = tl.where(tmp62, tmp63, tmp61)
tmp65 = tmp37 > tmp35
tmp66 = tl.full([1], 5, tl.int8)
tmp67 = tl.where(tmp65, tmp66, tmp64)
tmp68 = tmp44 > tmp38
tmp69 = tl.full([1], 6, tl.int8)
tmp70 = tl.where(tmp68, tmp69, tmp67)
tmp71 = tmp47 > tmp45
tmp72 = tl.full([1], 7, tl.int8)
tmp73 = tl.where(tmp71, tmp72, tmp70)
tmp74 = tmp50 > tmp48
tmp75 = tl.full([1], 8, tl.int8)
tmp76 = tl.where(tmp74, tmp75, tmp73)
tl.store(out_ptr0 + x6, tmp51, None)
tl.store(out_ptr1 + x6, tmp76, None)
@triton.jit
def triton_poi_fused_convolution_relu_21(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 % 1024
tmp0 = tl.load(in_out_ptr0 + x2, None)
tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x2, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_22(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 % 1024
y1 = yindex // 1024
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 1024 * x2 + 16384 * 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 + 1024 * x2 + 16384 * y1), tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31) = args
args.clear()
assert_size_stride(primals_1, (64, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 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, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_9, (128,), (1,))
assert_size_stride(primals_10, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_11, (256,), (1,))
assert_size_stride(primals_12, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_13, (256,), (1,))
assert_size_stride(primals_14, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_15, (256,), (1,))
assert_size_stride(primals_16, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_17, (512,), (1,))
assert_size_stride(primals_18, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_19, (512,), (1,))
assert_size_stride(primals_20, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_21, (512,), (1,))
assert_size_stride(primals_22, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_23, (512,), (1,))
assert_size_stride(primals_24, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_25, (512,), (1,))
assert_size_stride(primals_26, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_27, (512,), (1,))
assert_size_stride(primals_28, (1024, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_29, (1024,), (1,))
assert_size_stride(primals_30, (1024, 1024, 1, 1), (1024, 1, 1, 1))
assert_size_stride(primals_31, (1024,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 3, 3, 3), (27, 1, 9, 3), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(192, 9)](primals_1, buf0, 192, 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, 64, 3, 3), (576, 1, 192, 64), torch.
float32)
triton_poi_fused_2[grid(4096, 9)](primals_4, buf2, 4096, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = empty_strided_cuda((128, 64, 3, 3), (576, 1, 192, 64), torch
.float32)
triton_poi_fused_3[grid(8192, 9)](primals_6, buf3, 8192, 9, XBLOCK=
16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_6
buf4 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_4[grid(16384, 9)](primals_8, buf4, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_8
buf5 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_5[grid(32768, 9)](primals_10, buf5, 32768, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_10
buf6 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_6[grid(65536, 9)](primals_12, buf6, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_12
buf7 = empty_strided_cuda((256, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_6[grid(65536, 9)](primals_14, buf7, 65536, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_14
buf8 = empty_strided_cuda((512, 256, 3, 3), (2304, 1, 768, 256),
torch.float32)
triton_poi_fused_7[grid(131072, 9)](primals_16, buf8, 131072, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_16
buf9 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_18, buf9, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_18
buf10 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_20, buf10, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_20
buf11 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_22, buf11, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_22
buf12 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_24, buf12, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_24
buf13 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_8[grid(262144, 9)](primals_26, buf13, 262144, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_26
buf14 = empty_strided_cuda((1024, 512, 3, 3), (4608, 1, 1536, 512),
torch.float32)
triton_poi_fused_9[grid(524288, 9)](primals_28, buf14, 524288, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_28
buf15 = 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(buf15, (4, 64, 64, 64), (262144, 1, 4096, 64))
buf16 = buf15
del buf15
triton_poi_fused_convolution_relu_10[grid(1048576)](buf16,
primals_2, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_2
buf17 = extern_kernels.convolution(buf16, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf17, (4, 64, 64, 64), (262144, 1, 4096, 64))
buf18 = buf17
del buf17
triton_poi_fused_convolution_relu_10[grid(1048576)](buf18,
primals_5, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_5
buf19 = empty_strided_cuda((4, 64, 32, 32), (65536, 1, 2048, 64),
torch.float32)
buf20 = empty_strided_cuda((4, 64, 32, 32), (65536, 1, 2048, 64),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_11[grid(262144)](buf18,
buf19, buf20, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
buf21 = extern_kernels.convolution(buf19, buf3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf21, (4, 128, 32, 32), (131072, 1, 4096, 128))
buf22 = buf21
del buf21
triton_poi_fused_convolution_relu_12[grid(524288)](buf22, primals_7,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf23 = extern_kernels.convolution(buf22, buf4, 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, 1, 4096, 128))
buf24 = buf23
del buf23
triton_poi_fused_convolution_relu_12[grid(524288)](buf24, primals_9,
524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf25 = empty_strided_cuda((4, 128, 16, 16), (32768, 1, 2048, 128),
torch.float32)
buf26 = empty_strided_cuda((4, 128, 16, 16), (32768, 1, 2048, 128),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_13[grid(131072)](buf24,
buf25, buf26, 131072, XBLOCK=512, num_warps=8, num_stages=1)
buf27 = extern_kernels.convolution(buf25, buf5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 256, 16, 16), (65536, 1, 4096, 256))
buf28 = buf27
del buf27
triton_poi_fused_convolution_relu_14[grid(262144)](buf28,
primals_11, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_11
buf29 = extern_kernels.convolution(buf28, buf6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf29, (4, 256, 16, 16), (65536, 1, 4096, 256))
buf30 = buf29
del buf29
triton_poi_fused_convolution_relu_14[grid(262144)](buf30,
primals_13, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_13
buf31 = extern_kernels.convolution(buf30, buf7, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf31, (4, 256, 16, 16), (65536, 1, 4096, 256))
buf32 = buf31
del buf31
triton_poi_fused_convolution_relu_14[grid(262144)](buf32,
primals_15, 262144, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_15
buf33 = empty_strided_cuda((4, 256, 8, 8), (16384, 1, 2048, 256),
torch.float32)
buf34 = empty_strided_cuda((4, 256, 8, 8), (16384, 1, 2048, 256),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_15[grid(65536)](buf32,
buf33, buf34, 65536, XBLOCK=512, num_warps=4, num_stages=1)
buf35 = extern_kernels.convolution(buf33, buf8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf35, (4, 512, 8, 8), (32768, 1, 4096, 512))
buf36 = buf35
del buf35
triton_poi_fused_convolution_relu_16[grid(131072)](buf36,
primals_17, 131072, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_17
buf37 = extern_kernels.convolution(buf36, buf9, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf37, (4, 512, 8, 8), (32768, 1, 4096, 512))
buf38 = buf37
del buf37
triton_poi_fused_convolution_relu_16[grid(131072)](buf38,
primals_19, 131072, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_19
buf39 = extern_kernels.convolution(buf38, buf10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf39, (4, 512, 8, 8), (32768, 1, 4096, 512))
buf40 = empty_strided_cuda((4, 512, 8, 8), (32768, 64, 8, 1), torch
.float32)
triton_poi_fused_convolution_relu_17[grid(2048, 64)](buf39,
primals_21, buf40, 2048, 64, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
del buf39
del primals_21
buf41 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512),
torch.float32)
buf42 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_18[grid(2048, 16)](buf40,
buf41, buf42, 2048, 16, XBLOCK=16, YBLOCK=16, num_warps=4,
num_stages=1)
buf43 = extern_kernels.convolution(buf41, buf11, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf43, (4, 512, 4, 4), (8192, 1, 2048, 512))
buf44 = buf43
del buf43
triton_poi_fused_convolution_relu_19[grid(32768)](buf44, primals_23,
32768, XBLOCK=128, num_warps=4, num_stages=1)
del primals_23
buf45 = extern_kernels.convolution(buf44, buf12, 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, 4, 4), (8192, 1, 2048, 512))
buf46 = buf45
del buf45
triton_poi_fused_convolution_relu_19[grid(32768)](buf46, primals_25,
32768, XBLOCK=128, num_warps=4, num_stages=1)
del primals_25
buf47 = extern_kernels.convolution(buf46, buf13, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf47, (4, 512, 4, 4), (8192, 1, 2048, 512))
buf48 = buf47
del buf47
triton_poi_fused_convolution_relu_19[grid(32768)](buf48, primals_27,
32768, XBLOCK=128, num_warps=4, num_stages=1)
del primals_27
buf49 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512),
torch.float32)
buf50 = empty_strided_cuda((4, 512, 4, 4), (8192, 1, 2048, 512),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_20[grid(32768)](buf48,
buf49, buf50, 32768, XBLOCK=256, num_warps=4, num_stages=1)
buf51 = extern_kernels.convolution(buf49, buf14, stride=(1, 1),
padding=(6, 6), dilation=(6, 6), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf51, (4, 1024, 4, 4), (16384, 1, 4096, 1024))
buf52 = buf51
del buf51
triton_poi_fused_convolution_relu_21[grid(65536)](buf52, primals_29,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_29
buf53 = extern_kernels.convolution(buf52, primals_30, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf53, (4, 1024, 4, 4), (16384, 1, 4096, 1024))
buf54 = empty_strided_cuda((4, 1024, 4, 4), (16384, 16, 4, 1),
torch.float32)
buf55 = empty_strided_cuda((4, 1024, 4, 4), (16384, 1, 4096, 1024),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_22[grid(4096, 16)
](buf53, primals_31, buf54, buf55, 4096, 16, XBLOCK=16, YBLOCK=
64, num_warps=4, num_stages=1)
del buf53
del primals_31
return (buf40, buf54, buf0, buf1, buf2, buf3, buf4, buf5, buf6, buf7,
buf8, buf9, buf10, buf11, buf12, buf13, buf14, primals_30, buf16,
buf18, buf19, buf20, buf22, buf24, buf25, buf26, buf28, buf30,
buf32, buf33, buf34, buf36, buf38, buf40, buf41, buf42, buf44,
buf46, buf48, buf49, buf50, buf52, buf55)
def decimate(tensor, m):
"""
Decimate a tensor by a factor 'm', i.e. downsample by keeping every 'm'th value.
This is used when we convert FC layers to equivalent Convolutional layers, BUT of a smaller size.
:param tensor: tensor to be decimated
:param m: list of decimation factors for each dimension of the tensor; None if not to be decimated along a dimension
:return: decimated tensor
"""
assert tensor.dim() == len(m)
for d in range(tensor.dim()):
if m[d] is not None:
tensor = tensor.index_select(dim=d, index=torch.arange(start=0,
end=tensor.size(d), step=m[d]).long())
return tensor
class VGGBaseNew(nn.Module):
"""
VGG base convolutions to produce lower-level feature maps.
"""
def __init__(self):
super(VGGBaseNew, self).__init__()
self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, padding=1)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, padding=1)
self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)
self.conv7 = nn.Conv2d(1024, 1024, kernel_size=1)
def load_pretrained_layers(self):
"""
As in the paper, we use a VGG-16 pretrained on the ImageNet task as the base network.
There's one available in PyTorch, see https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.vgg16
We copy these parameters into our network. It's straightforward for conv1 to conv5.
However, the original VGG-16 does not contain the conv6 and con7 layers.
Therefore, we convert fc6 and fc7 into convolutional layers, and subsample by decimation. See 'decimate' in utils.py.
"""
state_dict = self.state_dict()
param_names = list(state_dict.keys())
pretrained_state_dict = torchvision.models.vgg16(pretrained=True
).state_dict()
pretrained_param_names = list(pretrained_state_dict.keys())
for i, param in enumerate(param_names[:-4]):
state_dict[param] = pretrained_state_dict[pretrained_param_names[i]
]
conv_fc6_weight = pretrained_state_dict['classifier.0.weight'].view(
4096, 512, 7, 7)
conv_fc6_bias = pretrained_state_dict['classifier.0.bias']
state_dict['conv6.weight'] = decimate(conv_fc6_weight, m=[4, None,
3, 3])
state_dict['conv6.bias'] = decimate(conv_fc6_bias, m=[4])
conv_fc7_weight = pretrained_state_dict['classifier.3.weight'].view(
4096, 4096, 1, 1)
conv_fc7_bias = pretrained_state_dict['classifier.3.bias']
state_dict['conv7.weight'] = decimate(conv_fc7_weight, m=[4, 4,
None, None])
state_dict['conv7.bias'] = decimate(conv_fc7_bias, m=[4])
self.load_state_dict(state_dict)
None
def forward(self, input_0):
primals_1 = self.conv1_1.weight
primals_2 = self.conv1_1.bias
primals_4 = self.conv1_2.weight
primals_5 = self.conv1_2.bias
primals_6 = self.conv2_1.weight
primals_7 = self.conv2_1.bias
primals_8 = self.conv2_2.weight
primals_9 = self.conv2_2.bias
primals_10 = self.conv3_1.weight
primals_11 = self.conv3_1.bias
primals_12 = self.conv3_2.weight
primals_13 = self.conv3_2.bias
primals_14 = self.conv3_3.weight
primals_15 = self.conv3_3.bias
primals_16 = self.conv4_1.weight
primals_17 = self.conv4_1.bias
primals_18 = self.conv4_2.weight
primals_19 = self.conv4_2.bias
primals_20 = self.conv4_3.weight
primals_21 = self.conv4_3.bias
primals_22 = self.conv5_1.weight
primals_23 = self.conv5_1.bias
primals_24 = self.conv5_2.weight
primals_25 = self.conv5_2.bias
primals_26 = self.conv5_3.weight
primals_27 = self.conv5_3.bias
primals_28 = self.conv6.weight
primals_29 = self.conv6.bias
primals_30 = self.conv7.weight
primals_31 = self.conv7.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])
return output[0], output[1]
|
ildoonet/ai-starthon-2019
|
VGGBase
| false
| 15,740
|
[
"MIT"
] | 69
|
148855adcb731741938a86545a2d3282287f0a50
|
https://github.com/ildoonet/ai-starthon-2019/tree/148855adcb731741938a86545a2d3282287f0a50
|
SelfAttentionWide
|
import torch
from torch import nn
import torch.nn.functional as F
def mask_(matrices, maskval=0.0, mask_diagonal=True):
"""
Masks out all values in the given batch of matrices where i <= j holds,
i < j if mask_diagonal is false
In place operation
:param tns:
:return:
"""
h, w = matrices.size(-2), matrices.size(-1)
indices = torch.triu_indices(h, w, offset=0 if mask_diagonal else 1)
matrices[..., indices[0], indices[1]] = maskval
class SelfAttentionWide(nn.Module):
"""
A self-attention with a larger number of parameters than the standard one.
Uses a full-size embedding vector for each head.
"""
def __init__(self, emb, heads=8, mask=False):
"""
:param emb:
:param heads:
:param mask:
"""
super().__init__()
self.emb = emb
self.heads = heads
self.mask = mask
self.tokeys = nn.Linear(emb, emb * heads, bias=False)
self.toqueries = nn.Linear(emb, emb * heads, bias=False)
self.tovalues = nn.Linear(emb, emb * heads, bias=False)
self.unifyheads = nn.Linear(heads * emb, emb)
def forward(self, x):
b, t, e = x.size()
h = self.heads
assert e == self.emb, f'Input embedding dim ({e}) should match layer embedding dim ({self.emb})'
keys = self.tokeys(x).view(b, t, h, e)
queries = self.toqueries(x).view(b, t, h, e)
values = self.tovalues(x).view(b, t, h, e)
keys = keys.transpose(1, 2).contiguous().view(b * h, t, e)
queries = queries.transpose(1, 2).contiguous().view(b * h, t, e)
values = values.transpose(1, 2).contiguous().view(b * h, t, e)
queries = queries / e ** (1 / 4)
keys = keys / e ** (1 / 4)
dot = torch.bmm(queries, keys.transpose(1, 2))
assert dot.size() == (b * h, t, t)
if self.mask:
mask_(dot, maskval=float('-inf'), mask_diagonal=False)
dot = F.softmax(dot, dim=2)
out = torch.bmm(dot, values).view(b, h, t, e)
out = out.transpose(1, 2).contiguous().view(b, t, h * e)
return self.unifyheads(out)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'emb': 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_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)](buf1, buf3, 512, XBLOCK=256,
num_warps=4, num_stages=1)
buf4 = reinterpret_tensor(buf1, (32, 4, 4), (16, 4, 1), 0)
del buf1
triton_poi_fused_div_1[grid(512)](buf0, buf4, 512, XBLOCK=256,
num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf0, (32, 4, 4), (16, 4, 1), 0)
del buf0
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
def mask_(matrices, maskval=0.0, mask_diagonal=True):
"""
Masks out all values in the given batch of matrices where i <= j holds,
i < j if mask_diagonal is false
In place operation
:param tns:
:return:
"""
h, w = matrices.size(-2), matrices.size(-1)
indices = torch.triu_indices(h, w, offset=0 if mask_diagonal else 1)
matrices[..., indices[0], indices[1]] = maskval
class SelfAttentionWideNew(nn.Module):
"""
A self-attention with a larger number of parameters than the standard one.
Uses a full-size embedding vector for each head.
"""
def __init__(self, emb, heads=8, mask=False):
"""
:param emb:
:param heads:
:param mask:
"""
super().__init__()
self.emb = emb
self.heads = heads
self.mask = mask
self.tokeys = nn.Linear(emb, emb * heads, bias=False)
self.toqueries = nn.Linear(emb, emb * heads, bias=False)
self.tovalues = nn.Linear(emb, emb * heads, bias=False)
self.unifyheads = nn.Linear(heads * emb, emb)
def forward(self, input_0):
primals_2 = self.tokeys.weight
primals_3 = self.toqueries.weight
primals_4 = self.tovalues.weight
primals_5 = self.unifyheads.weight
primals_6 = self.unifyheads.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
jplasser/former
|
SelfAttentionWide
| false
| 15,741
|
[
"MIT"
] | 674
|
7dabf7b355e94f2f0af966bd0daead539a30675a
|
https://github.com/jplasser/former/tree/7dabf7b355e94f2f0af966bd0daead539a30675a
|
SSD300
|
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
from itertools import product as product
def decimate(tensor, m):
"""
Decimate a tensor by a factor 'm', i.e. downsample by keeping every 'm'th value.
This is used when we convert FC layers to equivalent Convolutional layers, BUT of a smaller size.
:param tensor: tensor to be decimated
:param m: list of decimation factors for each dimension of the tensor; None if not to be decimated along a dimension
:return: decimated tensor
"""
assert tensor.dim() == len(m)
for d in range(tensor.dim()):
if m[d] is not None:
tensor = tensor.index_select(dim=d, index=torch.arange(start=0,
end=tensor.size(d), step=m[d]).long())
return tensor
def cxcy_to_xywh(cxcy):
"""
Convert bounding boxes from center-size coordinates (c_x, c_y, w, h) to boundary coordinates (x_min, y_min, x_max, y_max).
:param cxcy: bounding boxes in center-size coordinates, a tensor of size (n_boxes, 4)
:return: bounding boxes in boundary coordinates, a tensor of size (n_boxes, 4)
"""
return torch.cat([cxcy[:, :2] - cxcy[:, 2:] / 2, cxcy[:, 2:]], 1)
def gcxgcy_to_cxcy(gcxgcy, priors_cxcy):
"""
Decode bounding box coordinates predicted by the model, since they are encoded in the form mentioned above.
They are decoded into center-size coordinates.
This is the inverse of the function above.
:param gcxgcy: encoded bounding boxes, i.e. output of the model, a tensor of size (n_priors, 4)
:param priors_cxcy: prior boxes with respect to which the encoding is defined, a tensor of size (n_priors, 4)
:return: decoded bounding boxes in center-size form, a tensor of size (n_priors, 4)
"""
return torch.cat([gcxgcy[:, :2] * priors_cxcy[:, 2:] / 10 + priors_cxcy
[:, :2], torch.exp(gcxgcy[:, 2:] / 5) * priors_cxcy[:, 2:]], 1)
class VGGBase(nn.Module):
"""
VGG base convolutions to produce lower-level feature maps.
"""
def __init__(self):
super(VGGBase, self).__init__()
self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, padding=1)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, padding=1)
self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)
self.conv7 = nn.Conv2d(1024, 1024, kernel_size=1)
def forward(self, image):
"""
Forward propagation.
:param image: images, a tensor of dimensions (N, 3, 300, 300)
:return: lower-level feature maps conv4_3 and conv7
"""
out = F.relu(self.conv1_1(image))
out = F.relu(self.conv1_2(out))
out = self.pool1(out)
out = F.relu(self.conv2_1(out))
out = F.relu(self.conv2_2(out))
out = self.pool2(out)
out = F.relu(self.conv3_1(out))
out = F.relu(self.conv3_2(out))
out = F.relu(self.conv3_3(out))
out = self.pool3(out)
out = F.relu(self.conv4_1(out))
out = F.relu(self.conv4_2(out))
out = F.relu(self.conv4_3(out))
conv4_3_feats = out
out = self.pool4(out)
out = F.relu(self.conv5_1(out))
out = F.relu(self.conv5_2(out))
out = F.relu(self.conv5_3(out))
out = self.pool5(out)
out = F.relu(self.conv6(out))
conv7_feats = F.relu(self.conv7(out))
return conv4_3_feats, conv7_feats
def load_pretrained_layers(self):
"""
As in the paper, we use a VGG-16 pretrained on the ImageNet task as the base network.
There's one available in PyTorch, see https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.vgg16
We copy these parameters into our network. It's straightforward for conv1 to conv5.
However, the original VGG-16 does not contain the conv6 and con7 layers.
Therefore, we convert fc6 and fc7 into convolutional layers, and subsample by decimation. See 'decimate' in utils.py.
"""
state_dict = self.state_dict()
param_names = list(state_dict.keys())
pretrained_state_dict = torchvision.models.vgg16(pretrained=True
).state_dict()
pretrained_param_names = list(pretrained_state_dict.keys())
for i, param in enumerate(param_names[:-4]):
state_dict[param] = pretrained_state_dict[pretrained_param_names[i]
]
conv_fc6_weight = pretrained_state_dict['classifier.0.weight'].view(
4096, 512, 7, 7)
conv_fc6_bias = pretrained_state_dict['classifier.0.bias']
state_dict['conv6.weight'] = decimate(conv_fc6_weight, m=[4, None,
3, 3])
state_dict['conv6.bias'] = decimate(conv_fc6_bias, m=[4])
conv_fc7_weight = pretrained_state_dict['classifier.3.weight'].view(
4096, 4096, 1, 1)
conv_fc7_bias = pretrained_state_dict['classifier.3.bias']
state_dict['conv7.weight'] = decimate(conv_fc7_weight, m=[4, 4,
None, None])
state_dict['conv7.bias'] = decimate(conv_fc7_bias, m=[4])
self.load_state_dict(state_dict)
None
class AuxiliaryConvolutions(nn.Module):
"""
Additional convolutions to produce higher-level feature maps.
"""
def __init__(self):
super(AuxiliaryConvolutions, self).__init__()
self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0)
self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1)
self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0)
self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)
self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0)
self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0)
self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0)
self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0)
self.init_conv2d()
def init_conv2d(self):
"""
Initialize convolution parameters.
"""
for c in self.children():
if isinstance(c, nn.Conv2d):
nn.init.xavier_uniform_(c.weight)
nn.init.constant_(c.bias, 0.0)
def forward(self, conv7_feats):
"""
Forward propagation.
:param conv7_feats: lower-level conv7 feature map, a tensor of dimensions (N, 1024, 19, 19)
:return: higher-level feature maps conv8_2, conv9_2, conv10_2, and conv11_2
"""
out = F.relu(self.conv8_1(conv7_feats))
out = F.relu(self.conv8_2(out))
conv8_2_feats = out
out = F.relu(self.conv9_1(out))
out = F.relu(self.conv9_2(out))
conv9_2_feats = out
out = F.relu(self.conv10_1(out))
out = F.relu(self.conv10_2(out))
conv10_2_feats = out
out = F.relu(self.conv11_1(out))
conv11_2_feats = F.relu(self.conv11_2(out))
return conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats
class PredictionConvolutions(nn.Module):
"""
Convolutions to predict class scores and bounding boxes using lower and higher-level feature maps.
The bounding boxes (locations) are predicted as encoded offsets w.r.t each of the 8732 prior (default) boxes.
See 'cxcy_to_gcxgcy' in utils.py for the encoding definition.
The class scores represent the scores of each object class in each of the 8732 bounding boxes located.
A high score for 'background' = no object.
"""
def __init__(self, n_classes):
"""
:param n_classes: number of different types of objects
"""
super(PredictionConvolutions, self).__init__()
self.n_classes = n_classes
n_boxes = {'conv4_3': 4, 'conv7': 6, 'conv8_2': 6, 'conv9_2': 6,
'conv10_2': 4, 'conv11_2': 4}
self.loc_conv4_3 = nn.Conv2d(512, n_boxes['conv4_3'] * 4,
kernel_size=3, padding=1)
self.loc_conv7 = nn.Conv2d(1024, n_boxes['conv7'] * 4, kernel_size=
3, padding=1)
self.loc_conv8_2 = nn.Conv2d(512, n_boxes['conv8_2'] * 4,
kernel_size=3, padding=1)
self.loc_conv9_2 = nn.Conv2d(256, n_boxes['conv9_2'] * 4,
kernel_size=3, padding=1)
self.loc_conv10_2 = nn.Conv2d(256, n_boxes['conv10_2'] * 4,
kernel_size=3, padding=1)
self.loc_conv11_2 = nn.Conv2d(256, n_boxes['conv11_2'] * 4,
kernel_size=3, padding=1)
self.cl_conv4_3 = nn.Conv2d(512, n_boxes['conv4_3'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv7 = nn.Conv2d(1024, n_boxes['conv7'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv8_2 = nn.Conv2d(512, n_boxes['conv8_2'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv9_2 = nn.Conv2d(256, n_boxes['conv9_2'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv10_2 = nn.Conv2d(256, n_boxes['conv10_2'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv11_2 = nn.Conv2d(256, n_boxes['conv11_2'] * n_classes,
kernel_size=3, padding=1)
self.init_conv2d()
def init_conv2d(self):
"""
Initialize convolution parameters.
"""
for c in self.children():
if isinstance(c, nn.Conv2d):
nn.init.xavier_uniform_(c.weight)
nn.init.constant_(c.bias, 0.0)
def forward(self, conv4_3_feats, conv7_feats, conv8_2_feats,
conv9_2_feats, conv10_2_feats, conv11_2_feats):
"""
Forward propagation.
:param conv4_3_feats: conv4_3 feature map, a tensor of dimensions (N, 512, 38, 38)
:param conv7_feats: conv7 feature map, a tensor of dimensions (N, 1024, 19, 19)
:param conv8_2_feats: conv8_2 feature map, a tensor of dimensions (N, 512, 10, 10)
:param conv9_2_feats: conv9_2 feature map, a tensor of dimensions (N, 256, 5, 5)
:param conv10_2_feats: conv10_2 feature map, a tensor of dimensions (N, 256, 3, 3)
:param conv11_2_feats: conv11_2 feature map, a tensor of dimensions (N, 256, 1, 1)
:return: 8732 locations and class scores (i.e. w.r.t each prior box) for each image
"""
batch_size = conv4_3_feats.size(0)
l_conv4_3 = self.loc_conv4_3(conv4_3_feats)
l_conv4_3 = l_conv4_3.permute(0, 2, 3, 1).contiguous()
l_conv4_3 = l_conv4_3.view(batch_size, -1, 4)
l_conv7 = self.loc_conv7(conv7_feats)
l_conv7 = l_conv7.permute(0, 2, 3, 1).contiguous()
l_conv7 = l_conv7.view(batch_size, -1, 4)
l_conv8_2 = self.loc_conv8_2(conv8_2_feats)
l_conv8_2 = l_conv8_2.permute(0, 2, 3, 1).contiguous()
l_conv8_2 = l_conv8_2.view(batch_size, -1, 4)
l_conv9_2 = self.loc_conv9_2(conv9_2_feats)
l_conv9_2 = l_conv9_2.permute(0, 2, 3, 1).contiguous()
l_conv9_2 = l_conv9_2.view(batch_size, -1, 4)
l_conv10_2 = self.loc_conv10_2(conv10_2_feats)
l_conv10_2 = l_conv10_2.permute(0, 2, 3, 1).contiguous()
l_conv10_2 = l_conv10_2.view(batch_size, -1, 4)
l_conv11_2 = self.loc_conv11_2(conv11_2_feats)
l_conv11_2 = l_conv11_2.permute(0, 2, 3, 1).contiguous()
l_conv11_2 = l_conv11_2.view(batch_size, -1, 4)
c_conv4_3 = self.cl_conv4_3(conv4_3_feats)
c_conv4_3 = c_conv4_3.permute(0, 2, 3, 1).contiguous()
c_conv4_3 = c_conv4_3.view(batch_size, -1, self.n_classes)
c_conv7 = self.cl_conv7(conv7_feats)
c_conv7 = c_conv7.permute(0, 2, 3, 1).contiguous()
c_conv7 = c_conv7.view(batch_size, -1, self.n_classes)
c_conv8_2 = self.cl_conv8_2(conv8_2_feats)
c_conv8_2 = c_conv8_2.permute(0, 2, 3, 1).contiguous()
c_conv8_2 = c_conv8_2.view(batch_size, -1, self.n_classes)
c_conv9_2 = self.cl_conv9_2(conv9_2_feats)
c_conv9_2 = c_conv9_2.permute(0, 2, 3, 1).contiguous()
c_conv9_2 = c_conv9_2.view(batch_size, -1, self.n_classes)
c_conv10_2 = self.cl_conv10_2(conv10_2_feats)
c_conv10_2 = c_conv10_2.permute(0, 2, 3, 1).contiguous()
c_conv10_2 = c_conv10_2.view(batch_size, -1, self.n_classes)
c_conv11_2 = self.cl_conv11_2(conv11_2_feats)
c_conv11_2 = c_conv11_2.permute(0, 2, 3, 1).contiguous()
c_conv11_2 = c_conv11_2.view(batch_size, -1, self.n_classes)
locs = torch.cat([l_conv4_3, l_conv7, l_conv8_2, l_conv9_2,
l_conv10_2, l_conv11_2], dim=1)
classes_scores = torch.cat([c_conv4_3, c_conv7, c_conv8_2,
c_conv9_2, c_conv10_2, c_conv11_2], dim=1)
return locs, classes_scores
class SSD300(nn.Module):
"""
The SSD300 network - encapsulates the base VGG network, auxiliary, and prediction convolutions.
"""
def __init__(self, n_classes):
super(SSD300, self).__init__()
self.n_classes = n_classes
self.base = VGGBase()
self.aux_convs = AuxiliaryConvolutions()
self.pred_convs = PredictionConvolutions(n_classes)
self.rescale_factors = nn.Parameter(torch.FloatTensor(1, 512, 1, 1))
nn.init.constant_(self.rescale_factors, 20)
self.priors_cxcy = self.create_prior_boxes()
def forward(self, image):
"""
Forward propagation.
:param image: images, a tensor of dimensions (N, 3, 300, 300)
:return: 8732 locations and class scores (i.e. w.r.t each prior box) for each image
"""
conv4_3_feats, conv7_feats = self.base(image)
norm = conv4_3_feats.pow(2).sum(dim=1, keepdim=True).sqrt()
conv4_3_feats = conv4_3_feats / norm
conv4_3_feats = conv4_3_feats * self.rescale_factors
conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats = (self
.aux_convs(conv7_feats))
locs, classes_scores = self.pred_convs(conv4_3_feats, conv7_feats,
conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats)
return locs, classes_scores
def create_prior_boxes(self):
"""
Create the 8732 prior (default) boxes for the SSD300, as defined in the paper.
:return: prior boxes in center-size coordinates, a tensor of dimensions (8732, 4)
"""
fmap_dims = {'conv4_3': 38, 'conv7': 19, 'conv8_2': 10, 'conv9_2':
5, 'conv10_2': 3, 'conv11_2': 1}
obj_scales = {'conv4_3': 0.1, 'conv7': 0.2, 'conv8_2': 0.375,
'conv9_2': 0.55, 'conv10_2': 0.725, 'conv11_2': 0.9}
aspect_ratios = {'conv4_3': [1.0, 2.0, 0.5], 'conv7': [1.0, 2.0,
3.0, 0.5, 0.333], 'conv8_2': [1.0, 2.0, 3.0, 0.5, 0.333],
'conv9_2': [1.0, 2.0, 3.0, 0.5, 0.333], 'conv10_2': [1.0, 2.0,
0.5], 'conv11_2': [1.0, 2.0, 0.5]}
fmaps = list(fmap_dims.keys())
prior_boxes = []
for k, fmap in enumerate(fmaps):
for i in range(fmap_dims[fmap]):
for j in range(fmap_dims[fmap]):
cx = (j + 0.5) / fmap_dims[fmap]
cy = (i + 0.5) / fmap_dims[fmap]
for ratio in aspect_ratios[fmap]:
prior_boxes.append([cx, cy, obj_scales[fmap] * sqrt
(ratio), obj_scales[fmap] / sqrt(ratio)])
if ratio == 1.0:
try:
additional_scale = sqrt(obj_scales[fmap] *
obj_scales[fmaps[k + 1]])
except IndexError:
additional_scale = 1.0
prior_boxes.append([cx, cy, additional_scale,
additional_scale])
prior_boxes = torch.FloatTensor(prior_boxes)
prior_boxes.clamp_(0, 1)
return prior_boxes
def detect_objects(self, predicted_locs, predicted_scores):
"""
Decipher the 8732 locations and class scores (output of ths SSD300) to detect objects.
For each class, perform Non-Maximum Suppression (NMS) on boxes that are above a minimum threshold.
:param predicted_locs: predicted locations/boxes w.r.t the 8732 prior boxes, a tensor of dimensions (N, 8732, 4)
:param predicted_scores: class scores for each of the encoded locations/boxes, a tensor of dimensions (N, 8732, n_classes)
:param min_score: minimum threshold for a box to be considered a match for a certain class
:param max_overlap: maximum overlap two boxes can have so that the one with the lower score is not suppressed via NMS
:param top_k: if there are a lot of resulting detection across all classes, keep only the top 'k'
:return: detections (boxes, labels, and scores), lists of length batch_size
"""
batch_size = predicted_locs.size(0)
n_priors = self.priors_cxcy.size(0)
predicted_scores = F.softmax(predicted_scores, dim=2)
all_images_boxes = list()
scores = list()
assert n_priors == predicted_locs.size(1) == predicted_scores.size(1)
for i in range(batch_size):
decoded_locs = cxcy_to_xywh(gcxgcy_to_cxcy(predicted_locs[i],
self.priors_cxcy))
c = 1
class_scores = predicted_scores[i][:, c]
score_above_min_score = class_scores > 0.0
n_above_min_score = score_above_min_score.sum().item()
if n_above_min_score == 0:
continue
class_scores = class_scores[score_above_min_score]
class_decoded_locs = decoded_locs[score_above_min_score]
class_scores, sort_ind = class_scores.sort(dim=0, descending=True)
class_decoded_locs = class_decoded_locs[sort_ind]
best_loc = class_decoded_locs[0]
all_images_boxes.append(best_loc)
scores.append(class_scores[sort_ind][0])
return all_images_boxes, scores
def get_inputs():
return [torch.rand([4, 3, 512, 512])]
def get_init_inputs():
return [[], {'n_classes': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from math import sqrt
from itertools import product as product
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_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 // 262144 % 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 % 256
x1 = xindex // 256
x2 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 1024 * x1), None, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 1024 * x1), None,
eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (512 + 2 * x0 + 1024 * x1), None,
eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (513 + 2 * x0 + 1024 * 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 // 65536 % 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_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 % 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_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 // 16384 % 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_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 % 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_6(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 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_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 % 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_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 // 1024 % 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)
x1 = xindex // 32 % 32
x0 = xindex % 32
x4 = xindex
tmp0 = -1 + x1
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.full([1], 32, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tmp2 & tmp4
tmp6 = -1 + x0
tmp7 = tmp6 >= tmp1
tmp8 = tmp6 < tmp3
tmp9 = tmp7 & tmp8
tmp10 = tmp5 & tmp9
tmp11 = tl.load(in_ptr0 + (-33 + x4), tmp10, other=float('-inf'))
tmp12 = x0
tmp13 = tmp12 >= tmp1
tmp14 = tmp12 < tmp3
tmp15 = tmp13 & tmp14
tmp16 = tmp5 & tmp15
tmp17 = tl.load(in_ptr0 + (-32 + x4), tmp16, other=float('-inf'))
tmp18 = triton_helpers.maximum(tmp17, tmp11)
tmp19 = 1 + x0
tmp20 = tmp19 >= tmp1
tmp21 = tmp19 < tmp3
tmp22 = tmp20 & tmp21
tmp23 = tmp5 & tmp22
tmp24 = tl.load(in_ptr0 + (-31 + x4), tmp23, other=float('-inf'))
tmp25 = triton_helpers.maximum(tmp24, tmp18)
tmp26 = x1
tmp27 = tmp26 >= tmp1
tmp28 = tmp26 < tmp3
tmp29 = tmp27 & tmp28
tmp30 = tmp29 & tmp9
tmp31 = tl.load(in_ptr0 + (-1 + x4), tmp30, other=float('-inf'))
tmp32 = triton_helpers.maximum(tmp31, tmp25)
tmp33 = tmp29 & tmp15
tmp34 = tl.load(in_ptr0 + x4, tmp33, other=float('-inf'))
tmp35 = triton_helpers.maximum(tmp34, tmp32)
tmp36 = tmp29 & tmp22
tmp37 = tl.load(in_ptr0 + (1 + x4), tmp36, other=float('-inf'))
tmp38 = triton_helpers.maximum(tmp37, tmp35)
tmp39 = 1 + x1
tmp40 = tmp39 >= tmp1
tmp41 = tmp39 < tmp3
tmp42 = tmp40 & tmp41
tmp43 = tmp42 & tmp9
tmp44 = tl.load(in_ptr0 + (31 + x4), tmp43, other=float('-inf'))
tmp45 = triton_helpers.maximum(tmp44, tmp38)
tmp46 = tmp42 & tmp15
tmp47 = tl.load(in_ptr0 + (32 + x4), tmp46, other=float('-inf'))
tmp48 = triton_helpers.maximum(tmp47, tmp45)
tmp49 = tmp42 & tmp22
tmp50 = tl.load(in_ptr0 + (33 + x4), tmp49, other=float('-inf'))
tmp51 = triton_helpers.maximum(tmp50, tmp48)
tmp52 = tmp17 > tmp11
tmp53 = tl.full([1], 1, tl.int8)
tmp54 = tl.full([1], 0, tl.int8)
tmp55 = tl.where(tmp52, tmp53, tmp54)
tmp56 = tmp24 > tmp18
tmp57 = tl.full([1], 2, tl.int8)
tmp58 = tl.where(tmp56, tmp57, tmp55)
tmp59 = tmp31 > tmp25
tmp60 = tl.full([1], 3, tl.int8)
tmp61 = tl.where(tmp59, tmp60, tmp58)
tmp62 = tmp34 > tmp32
tmp63 = tl.full([1], 4, tl.int8)
tmp64 = tl.where(tmp62, tmp63, tmp61)
tmp65 = tmp37 > tmp35
tmp66 = tl.full([1], 5, tl.int8)
tmp67 = tl.where(tmp65, tmp66, tmp64)
tmp68 = tmp44 > tmp38
tmp69 = tl.full([1], 6, tl.int8)
tmp70 = tl.where(tmp68, tmp69, tmp67)
tmp71 = tmp47 > tmp45
tmp72 = tl.full([1], 7, tl.int8)
tmp73 = tl.where(tmp71, tmp72, tmp70)
tmp74 = tmp50 > tmp48
tmp75 = tl.full([1], 8, tl.int8)
tmp76 = tl.where(tmp74, tmp75, tmp73)
tl.store(out_ptr0 + x4, tmp51, None)
tl.store(out_ptr1 + x4, tmp76, 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 // 1024 % 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_red_fused_pow_sqrt_sum_11(in_out_ptr0, in_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
rnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex % 4096
x1 = xindex // 4096
_tmp3 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
x3 = xindex
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r2 = rindex
tmp0 = tl.load(in_ptr0 + (x0 + 4096 * r2 + 2097152 * x1), rmask,
eviction_policy='evict_first', other=0.0)
tmp1 = tmp0 * tmp0
tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp4 = _tmp3 + tmp2
_tmp3 = tl.where(rmask, tmp4, _tmp3)
tmp3 = tl.sum(_tmp3, 1)[:, None]
tmp5 = libdevice.sqrt(tmp3)
tl.debug_barrier()
tl.store(in_out_ptr0 + x3, tmp5, None)
@triton.jit
def triton_poi_fused_div_mul_12(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
x0 = xindex % 4096
x2 = xindex // 2097152
x1 = xindex // 4096 % 512
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + (x0 + 4096 * x2), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 / tmp1
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + x3, tmp2, None)
tl.store(out_ptr1 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_13(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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_convolution_relu_14(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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_convolution_relu_15(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 % 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_relu_16(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 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_17(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 64 % 128
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
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_18(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 36 % 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_19(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 // 36 % 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_relu_20(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
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_cat_21(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, in_ptr10, in_ptr11,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 394496
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 24656
x0 = xindex % 4
x2 = xindex // 98624
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 16384, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4096 * ((x0 + 4 * x1) % 16) + 65536 * ((x0 +
4 * x1 + 65536 * x2) // 65536 % 4) + (x0 + 4 * x1) // 16 % 4096),
tmp4 & xmask, eviction_policy='evict_last', other=0.0)
tmp6 = tl.load(in_ptr1 + (x0 + 4 * x1) % 16, tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp7 = tmp5 + tmp6
tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype)
tmp9 = tl.where(tmp4, tmp7, tmp8)
tmp10 = tmp0 >= tmp3
tmp11 = tl.full([1], 22528, tl.int64)
tmp12 = tmp0 < tmp11
tmp13 = tmp10 & tmp12
tmp14 = tl.load(in_ptr2 + (1024 * ((x0 + 4 * (-16384 + x1)) % 24) +
24576 * ((x0 + 4 * (-16384 + x1) + 24576 * x2) // 24576 % 4) + (x0 +
4 * (-16384 + x1)) // 24 % 1024), tmp13 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp15 = tl.load(in_ptr3 + (x0 + 4 * (-16384 + x1)) % 24, tmp13 & xmask,
eviction_policy='evict_last', other=0.0)
tmp16 = tmp14 + tmp15
tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype)
tmp18 = tl.where(tmp13, tmp16, tmp17)
tmp19 = tmp0 >= tmp11
tmp20 = tl.full([1], 24064, tl.int64)
tmp21 = tmp0 < tmp20
tmp22 = tmp19 & tmp21
tmp23 = tl.load(in_ptr4 + (256 * ((x0 + 4 * (-22528 + x1)) % 24) + 6144 *
((x0 + 4 * (-22528 + x1) + 6144 * x2) // 6144 % 4) + (x0 + 4 * (-
22528 + x1)) // 24 % 256), tmp22 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp24 = tl.load(in_ptr5 + (x0 + 4 * (-22528 + x1)) % 24, tmp22 & xmask,
eviction_policy='evict_last', other=0.0)
tmp25 = tmp23 + tmp24
tmp26 = tl.full(tmp25.shape, 0.0, tmp25.dtype)
tmp27 = tl.where(tmp22, tmp25, tmp26)
tmp28 = tmp0 >= tmp20
tmp29 = tl.full([1], 24448, tl.int64)
tmp30 = tmp0 < tmp29
tmp31 = tmp28 & tmp30
tmp32 = tl.load(in_ptr6 + (64 * ((x0 + 4 * (-24064 + x1)) % 24) + 1536 *
((x0 + 4 * (-24064 + x1) + 1536 * x2) // 1536 % 4) + (x0 + 4 * (-
24064 + x1)) // 24 % 64), tmp31 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp33 = tl.load(in_ptr7 + (x0 + 4 * (-24064 + x1)) % 24, tmp31 & xmask,
eviction_policy='evict_last', other=0.0)
tmp34 = tmp32 + tmp33
tmp35 = tl.full(tmp34.shape, 0.0, tmp34.dtype)
tmp36 = tl.where(tmp31, tmp34, tmp35)
tmp37 = tmp0 >= tmp29
tmp38 = tl.full([1], 24592, tl.int64)
tmp39 = tmp0 < tmp38
tmp40 = tmp37 & tmp39
tmp41 = tl.load(in_ptr8 + (36 * ((x0 + 4 * (-24448 + x1)) % 16) + 576 *
((x0 + 4 * (-24448 + x1) + 576 * x2) // 576 % 4) + (x0 + 4 * (-
24448 + x1)) // 16 % 36), tmp40 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp42 = tl.load(in_ptr9 + (x0 + 4 * (-24448 + x1)) % 16, tmp40 & xmask,
eviction_policy='evict_last', other=0.0)
tmp43 = tmp41 + tmp42
tmp44 = tl.full(tmp43.shape, 0.0, tmp43.dtype)
tmp45 = tl.where(tmp40, tmp43, tmp44)
tmp46 = tmp0 >= tmp38
tl.full([1], 24656, tl.int64)
tmp49 = tl.load(in_ptr10 + (16 * ((x0 + 4 * (-24592 + x1)) % 16) + 256 *
((x0 + 4 * (-24592 + x1) + 256 * x2) // 256 % 4) + (x0 + 4 * (-
24592 + x1)) // 16 % 16), tmp46 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp50 = tl.load(in_ptr11 + (x0 + 4 * (-24592 + x1)) % 16, tmp46 & xmask,
eviction_policy='evict_last', other=0.0)
tmp51 = tmp49 + tmp50
tmp52 = tl.full(tmp51.shape, 0.0, tmp51.dtype)
tmp53 = tl.where(tmp46, tmp51, tmp52)
tmp54 = tl.where(tmp40, tmp45, tmp53)
tmp55 = tl.where(tmp31, tmp36, tmp54)
tmp56 = tl.where(tmp22, tmp27, tmp55)
tmp57 = tl.where(tmp13, tmp18, tmp56)
tmp58 = tl.where(tmp4, tmp9, tmp57)
tl.store(out_ptr0 + x3, tmp58, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47,
primals_48, primals_49, primals_50, primals_51, primals_52,
primals_53, primals_54, primals_55, primals_56, primals_57,
primals_58, primals_59, primals_60, primals_61, primals_62,
primals_63, primals_64, primals_65, primals_66, primals_67,
primals_68, primals_69, primals_70, primals_71, primals_72) = args
args.clear()
assert_size_stride(primals_1, (64, 3, 3, 3), (27, 9, 3, 1))
assert_size_stride(primals_2, (64,), (1,))
assert_size_stride(primals_3, (4, 3, 512, 512), (786432, 262144, 512, 1))
assert_size_stride(primals_4, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (128, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (128,), (1,))
assert_size_stride(primals_8, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_9, (128,), (1,))
assert_size_stride(primals_10, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_11, (256,), (1,))
assert_size_stride(primals_12, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_13, (256,), (1,))
assert_size_stride(primals_14, (256, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_15, (256,), (1,))
assert_size_stride(primals_16, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_17, (512,), (1,))
assert_size_stride(primals_18, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_19, (512,), (1,))
assert_size_stride(primals_20, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_21, (512,), (1,))
assert_size_stride(primals_22, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_23, (512,), (1,))
assert_size_stride(primals_24, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_25, (512,), (1,))
assert_size_stride(primals_26, (512, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_27, (512,), (1,))
assert_size_stride(primals_28, (1024, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_29, (1024,), (1,))
assert_size_stride(primals_30, (1024, 1024, 1, 1), (1024, 1, 1, 1))
assert_size_stride(primals_31, (1024,), (1,))
assert_size_stride(primals_32, (1, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_33, (256, 1024, 1, 1), (1024, 1, 1, 1))
assert_size_stride(primals_34, (256,), (1,))
assert_size_stride(primals_35, (512, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_36, (512,), (1,))
assert_size_stride(primals_37, (128, 512, 1, 1), (512, 1, 1, 1))
assert_size_stride(primals_38, (128,), (1,))
assert_size_stride(primals_39, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_40, (256,), (1,))
assert_size_stride(primals_41, (128, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_42, (128,), (1,))
assert_size_stride(primals_43, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_44, (256,), (1,))
assert_size_stride(primals_45, (128, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_46, (128,), (1,))
assert_size_stride(primals_47, (256, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_48, (256,), (1,))
assert_size_stride(primals_49, (16, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_50, (16,), (1,))
assert_size_stride(primals_51, (24, 1024, 3, 3), (9216, 9, 3, 1))
assert_size_stride(primals_52, (24,), (1,))
assert_size_stride(primals_53, (24, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_54, (24,), (1,))
assert_size_stride(primals_55, (24, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_56, (24,), (1,))
assert_size_stride(primals_57, (16, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_58, (16,), (1,))
assert_size_stride(primals_59, (16, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_60, (16,), (1,))
assert_size_stride(primals_61, (16, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_62, (16,), (1,))
assert_size_stride(primals_63, (24, 1024, 3, 3), (9216, 9, 3, 1))
assert_size_stride(primals_64, (24,), (1,))
assert_size_stride(primals_65, (24, 512, 3, 3), (4608, 9, 3, 1))
assert_size_stride(primals_66, (24,), (1,))
assert_size_stride(primals_67, (24, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_68, (24,), (1,))
assert_size_stride(primals_69, (16, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_70, (16,), (1,))
assert_size_stride(primals_71, (16, 256, 3, 3), (2304, 9, 3, 1))
assert_size_stride(primals_72, (16,), (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, 512, 512), (16777216, 262144, 512, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(67108864)](buf1, primals_2,
67108864, 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, 64, 512, 512), (16777216, 262144, 512, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(67108864)](buf3, primals_5,
67108864, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 64, 256, 256), (4194304, 65536, 256,
1), torch.float32)
buf5 = empty_strided_cuda((4, 64, 256, 256), (4194304, 65536, 256,
1), torch.int8)
triton_poi_fused_max_pool2d_with_indices_1[grid(16777216)](buf3,
buf4, buf5, 16777216, XBLOCK=512, num_warps=8, num_stages=1)
buf6 = extern_kernels.convolution(buf4, primals_6, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 128, 256, 256), (8388608, 65536, 256, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_2[grid(33554432)](buf7, primals_7,
33554432, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_7
buf8 = extern_kernels.convolution(buf7, primals_8, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 128, 256, 256), (8388608, 65536, 256, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_relu_2[grid(33554432)](buf9, primals_9,
33554432, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_9
buf10 = empty_strided_cuda((4, 128, 128, 128), (2097152, 16384, 128,
1), torch.float32)
buf11 = empty_strided_cuda((4, 128, 128, 128), (2097152, 16384, 128,
1), torch.int8)
triton_poi_fused_max_pool2d_with_indices_3[grid(8388608)](buf9,
buf10, buf11, 8388608, XBLOCK=512, num_warps=8, num_stages=1)
buf12 = extern_kernels.convolution(buf10, primals_10, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 256, 128, 128), (4194304, 16384, 128, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_relu_4[grid(16777216)](buf13,
primals_11, 16777216, XBLOCK=512, num_warps=8, num_stages=1)
del primals_11
buf14 = extern_kernels.convolution(buf13, primals_12, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 256, 128, 128), (4194304, 16384, 128, 1))
buf15 = buf14
del buf14
triton_poi_fused_convolution_relu_4[grid(16777216)](buf15,
primals_13, 16777216, XBLOCK=512, num_warps=8, num_stages=1)
del primals_13
buf16 = extern_kernels.convolution(buf15, primals_14, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf16, (4, 256, 128, 128), (4194304, 16384, 128, 1))
buf17 = buf16
del buf16
triton_poi_fused_convolution_relu_4[grid(16777216)](buf17,
primals_15, 16777216, XBLOCK=512, num_warps=8, num_stages=1)
del primals_15
buf18 = empty_strided_cuda((4, 256, 64, 64), (1048576, 4096, 64, 1),
torch.float32)
buf19 = empty_strided_cuda((4, 256, 64, 64), (1048576, 4096, 64, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_5[grid(4194304)](buf17,
buf18, buf19, 4194304, XBLOCK=512, num_warps=8, num_stages=1)
buf20 = extern_kernels.convolution(buf18, primals_16, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf20, (4, 512, 64, 64), (2097152, 4096, 64, 1))
buf21 = buf20
del buf20
triton_poi_fused_convolution_relu_6[grid(8388608)](buf21,
primals_17, 8388608, XBLOCK=512, num_warps=8, num_stages=1)
del primals_17
buf22 = extern_kernels.convolution(buf21, primals_18, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf22, (4, 512, 64, 64), (2097152, 4096, 64, 1))
buf23 = buf22
del buf22
triton_poi_fused_convolution_relu_6[grid(8388608)](buf23,
primals_19, 8388608, XBLOCK=512, num_warps=8, num_stages=1)
del primals_19
buf24 = extern_kernels.convolution(buf23, primals_20, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf24, (4, 512, 64, 64), (2097152, 4096, 64, 1))
buf25 = buf24
del buf24
triton_poi_fused_convolution_relu_6[grid(8388608)](buf25,
primals_21, 8388608, XBLOCK=512, num_warps=8, num_stages=1)
del primals_21
buf26 = empty_strided_cuda((4, 512, 32, 32), (524288, 1024, 32, 1),
torch.float32)
buf27 = empty_strided_cuda((4, 512, 32, 32), (524288, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_7[grid(2097152)](buf25,
buf26, buf27, 2097152, XBLOCK=512, num_warps=8, num_stages=1)
buf28 = extern_kernels.convolution(buf26, primals_22, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf28, (4, 512, 32, 32), (524288, 1024, 32, 1))
buf29 = buf28
del buf28
triton_poi_fused_convolution_relu_8[grid(2097152)](buf29,
primals_23, 2097152, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_23
buf30 = extern_kernels.convolution(buf29, primals_24, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf30, (4, 512, 32, 32), (524288, 1024, 32, 1))
buf31 = buf30
del buf30
triton_poi_fused_convolution_relu_8[grid(2097152)](buf31,
primals_25, 2097152, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_25
buf32 = extern_kernels.convolution(buf31, primals_26, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf32, (4, 512, 32, 32), (524288, 1024, 32, 1))
buf33 = buf32
del buf32
triton_poi_fused_convolution_relu_8[grid(2097152)](buf33,
primals_27, 2097152, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_27
buf34 = empty_strided_cuda((4, 512, 32, 32), (524288, 1024, 32, 1),
torch.float32)
buf35 = empty_strided_cuda((4, 512, 32, 32), (524288, 1024, 32, 1),
torch.int8)
triton_poi_fused_max_pool2d_with_indices_9[grid(2097152)](buf33,
buf34, buf35, 2097152, XBLOCK=512, num_warps=8, num_stages=1)
buf36 = extern_kernels.convolution(buf34, primals_28, stride=(1, 1),
padding=(6, 6), dilation=(6, 6), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf36, (4, 1024, 32, 32), (1048576, 1024, 32, 1))
buf37 = buf36
del buf36
triton_poi_fused_convolution_relu_10[grid(4194304)](buf37,
primals_29, 4194304, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_29
buf38 = extern_kernels.convolution(buf37, primals_30, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf38, (4, 1024, 32, 32), (1048576, 1024, 32, 1))
buf39 = buf38
del buf38
triton_poi_fused_convolution_relu_10[grid(4194304)](buf39,
primals_31, 4194304, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_31
buf40 = empty_strided_cuda((4, 1, 64, 64), (4096, 16384, 64, 1),
torch.float32)
buf41 = reinterpret_tensor(buf40, (4, 1, 64, 64), (4096, 4096, 64,
1), 0)
del buf40
triton_red_fused_pow_sqrt_sum_11[grid(16384)](buf41, buf25, 16384,
512, XBLOCK=64, RBLOCK=8, num_warps=4, num_stages=1)
buf42 = empty_strided_cuda((4, 512, 64, 64), (2097152, 4096, 64, 1),
torch.float32)
buf43 = empty_strided_cuda((4, 512, 64, 64), (2097152, 4096, 64, 1),
torch.float32)
triton_poi_fused_div_mul_12[grid(8388608)](buf25, buf41, primals_32,
buf42, buf43, 8388608, XBLOCK=512, num_warps=8, num_stages=1)
buf44 = extern_kernels.convolution(buf39, primals_33, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf44, (4, 256, 32, 32), (262144, 1024, 32, 1))
buf45 = buf44
del buf44
triton_poi_fused_convolution_relu_13[grid(1048576)](buf45,
primals_34, 1048576, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_34
buf46 = extern_kernels.convolution(buf45, primals_35, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf46, (4, 512, 16, 16), (131072, 256, 16, 1))
buf47 = buf46
del buf46
triton_poi_fused_convolution_relu_14[grid(524288)](buf47,
primals_36, 524288, XBLOCK=1024, num_warps=4, num_stages=1)
del primals_36
buf48 = extern_kernels.convolution(buf47, primals_37, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf48, (4, 128, 16, 16), (32768, 256, 16, 1))
buf49 = buf48
del buf48
triton_poi_fused_convolution_relu_15[grid(131072)](buf49,
primals_38, 131072, XBLOCK=512, num_warps=8, num_stages=1)
del primals_38
buf50 = extern_kernels.convolution(buf49, primals_39, stride=(2, 2),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf50, (4, 256, 8, 8), (16384, 64, 8, 1))
buf51 = buf50
del buf50
triton_poi_fused_convolution_relu_16[grid(65536)](buf51, primals_40,
65536, XBLOCK=256, num_warps=4, num_stages=1)
del primals_40
buf52 = extern_kernels.convolution(buf51, primals_41, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf52, (4, 128, 8, 8), (8192, 64, 8, 1))
buf53 = buf52
del buf52
triton_poi_fused_convolution_relu_17[grid(32768)](buf53, primals_42,
32768, XBLOCK=256, num_warps=4, num_stages=1)
del primals_42
buf54 = extern_kernels.convolution(buf53, primals_43, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf54, (4, 256, 6, 6), (9216, 36, 6, 1))
buf55 = buf54
del buf54
triton_poi_fused_convolution_relu_18[grid(36864)](buf55, primals_44,
36864, XBLOCK=512, num_warps=4, num_stages=1)
del primals_44
buf56 = extern_kernels.convolution(buf55, primals_45, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf56, (4, 128, 6, 6), (4608, 36, 6, 1))
buf57 = buf56
del buf56
triton_poi_fused_convolution_relu_19[grid(18432)](buf57, primals_46,
18432, XBLOCK=256, num_warps=4, num_stages=1)
del primals_46
buf58 = extern_kernels.convolution(buf57, primals_47, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf58, (4, 256, 4, 4), (4096, 16, 4, 1))
buf59 = buf58
del buf58
triton_poi_fused_convolution_relu_20[grid(16384)](buf59, primals_48,
16384, XBLOCK=256, num_warps=4, num_stages=1)
del primals_48
buf60 = extern_kernels.convolution(buf43, primals_49, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf60, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf61 = extern_kernels.convolution(buf39, primals_51, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf61, (4, 24, 32, 32), (24576, 1024, 32, 1))
buf62 = extern_kernels.convolution(buf47, primals_53, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf62, (4, 24, 16, 16), (6144, 256, 16, 1))
buf63 = extern_kernels.convolution(buf51, primals_55, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf63, (4, 24, 8, 8), (1536, 64, 8, 1))
buf64 = extern_kernels.convolution(buf55, primals_57, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf64, (4, 16, 6, 6), (576, 36, 6, 1))
buf65 = extern_kernels.convolution(buf59, primals_59, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf65, (4, 16, 4, 4), (256, 16, 4, 1))
buf66 = extern_kernels.convolution(buf43, primals_61, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf66, (4, 16, 64, 64), (65536, 4096, 64, 1))
buf67 = extern_kernels.convolution(buf39, primals_63, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf67, (4, 24, 32, 32), (24576, 1024, 32, 1))
buf68 = extern_kernels.convolution(buf47, primals_65, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf68, (4, 24, 16, 16), (6144, 256, 16, 1))
buf69 = extern_kernels.convolution(buf51, primals_67, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf69, (4, 24, 8, 8), (1536, 64, 8, 1))
buf70 = extern_kernels.convolution(buf55, primals_69, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf70, (4, 16, 6, 6), (576, 36, 6, 1))
buf71 = extern_kernels.convolution(buf59, primals_71, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf71, (4, 16, 4, 4), (256, 16, 4, 1))
buf72 = empty_strided_cuda((4, 24656, 4), (98624, 4, 1), torch.float32)
triton_poi_fused_cat_21[grid(394496)](buf60, primals_50, buf61,
primals_52, buf62, primals_54, buf63, primals_56, buf64,
primals_58, buf65, primals_60, buf72, 394496, XBLOCK=512,
num_warps=8, num_stages=1)
del buf60
del buf61
del buf62
del buf63
del buf64
del buf65
del primals_50
del primals_52
del primals_54
del primals_56
del primals_58
del primals_60
buf73 = empty_strided_cuda((4, 24656, 4), (98624, 4, 1), torch.float32)
triton_poi_fused_cat_21[grid(394496)](buf66, primals_62, buf67,
primals_64, buf68, primals_66, buf69, primals_68, buf70,
primals_70, buf71, primals_72, buf73, 394496, XBLOCK=512,
num_warps=8, num_stages=1)
del buf66
del buf67
del buf68
del buf69
del buf70
del buf71
del primals_62
del primals_64
del primals_66
del primals_68
del primals_70
del primals_72
return (buf72, buf73, 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_33, primals_35,
primals_37, primals_39, primals_41, primals_43, primals_45,
primals_47, primals_49, primals_51, primals_53, primals_55,
primals_57, primals_59, primals_61, primals_63, primals_65,
primals_67, primals_69, primals_71, buf1, buf3, buf4, buf5, buf7,
buf9, buf10, buf11, buf13, buf15, buf17, buf18, buf19, buf21, buf23,
buf25, buf26, buf27, buf29, buf31, buf33, buf34, buf35, buf37,
buf39, buf41, buf42, buf43, buf45, buf47, buf49, buf51, buf53,
buf55, buf57, buf59)
def decimate(tensor, m):
"""
Decimate a tensor by a factor 'm', i.e. downsample by keeping every 'm'th value.
This is used when we convert FC layers to equivalent Convolutional layers, BUT of a smaller size.
:param tensor: tensor to be decimated
:param m: list of decimation factors for each dimension of the tensor; None if not to be decimated along a dimension
:return: decimated tensor
"""
assert tensor.dim() == len(m)
for d in range(tensor.dim()):
if m[d] is not None:
tensor = tensor.index_select(dim=d, index=torch.arange(start=0,
end=tensor.size(d), step=m[d]).long())
return tensor
def cxcy_to_xywh(cxcy):
"""
Convert bounding boxes from center-size coordinates (c_x, c_y, w, h) to boundary coordinates (x_min, y_min, x_max, y_max).
:param cxcy: bounding boxes in center-size coordinates, a tensor of size (n_boxes, 4)
:return: bounding boxes in boundary coordinates, a tensor of size (n_boxes, 4)
"""
return torch.cat([cxcy[:, :2] - cxcy[:, 2:] / 2, cxcy[:, 2:]], 1)
def gcxgcy_to_cxcy(gcxgcy, priors_cxcy):
"""
Decode bounding box coordinates predicted by the model, since they are encoded in the form mentioned above.
They are decoded into center-size coordinates.
This is the inverse of the function above.
:param gcxgcy: encoded bounding boxes, i.e. output of the model, a tensor of size (n_priors, 4)
:param priors_cxcy: prior boxes with respect to which the encoding is defined, a tensor of size (n_priors, 4)
:return: decoded bounding boxes in center-size form, a tensor of size (n_priors, 4)
"""
return torch.cat([gcxgcy[:, :2] * priors_cxcy[:, 2:] / 10 + priors_cxcy
[:, :2], torch.exp(gcxgcy[:, 2:] / 5) * priors_cxcy[:, 2:]], 1)
class VGGBase(nn.Module):
"""
VGG base convolutions to produce lower-level feature maps.
"""
def __init__(self):
super(VGGBase, self).__init__()
self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, padding=1)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, padding=1)
self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
self.conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)
self.conv7 = nn.Conv2d(1024, 1024, kernel_size=1)
def forward(self, image):
"""
Forward propagation.
:param image: images, a tensor of dimensions (N, 3, 300, 300)
:return: lower-level feature maps conv4_3 and conv7
"""
out = F.relu(self.conv1_1(image))
out = F.relu(self.conv1_2(out))
out = self.pool1(out)
out = F.relu(self.conv2_1(out))
out = F.relu(self.conv2_2(out))
out = self.pool2(out)
out = F.relu(self.conv3_1(out))
out = F.relu(self.conv3_2(out))
out = F.relu(self.conv3_3(out))
out = self.pool3(out)
out = F.relu(self.conv4_1(out))
out = F.relu(self.conv4_2(out))
out = F.relu(self.conv4_3(out))
conv4_3_feats = out
out = self.pool4(out)
out = F.relu(self.conv5_1(out))
out = F.relu(self.conv5_2(out))
out = F.relu(self.conv5_3(out))
out = self.pool5(out)
out = F.relu(self.conv6(out))
conv7_feats = F.relu(self.conv7(out))
return conv4_3_feats, conv7_feats
def load_pretrained_layers(self):
"""
As in the paper, we use a VGG-16 pretrained on the ImageNet task as the base network.
There's one available in PyTorch, see https://pytorch.org/docs/stable/torchvision/models.html#torchvision.models.vgg16
We copy these parameters into our network. It's straightforward for conv1 to conv5.
However, the original VGG-16 does not contain the conv6 and con7 layers.
Therefore, we convert fc6 and fc7 into convolutional layers, and subsample by decimation. See 'decimate' in utils.py.
"""
state_dict = self.state_dict()
param_names = list(state_dict.keys())
pretrained_state_dict = torchvision.models.vgg16(pretrained=True
).state_dict()
pretrained_param_names = list(pretrained_state_dict.keys())
for i, param in enumerate(param_names[:-4]):
state_dict[param] = pretrained_state_dict[pretrained_param_names[i]
]
conv_fc6_weight = pretrained_state_dict['classifier.0.weight'].view(
4096, 512, 7, 7)
conv_fc6_bias = pretrained_state_dict['classifier.0.bias']
state_dict['conv6.weight'] = decimate(conv_fc6_weight, m=[4, None,
3, 3])
state_dict['conv6.bias'] = decimate(conv_fc6_bias, m=[4])
conv_fc7_weight = pretrained_state_dict['classifier.3.weight'].view(
4096, 4096, 1, 1)
conv_fc7_bias = pretrained_state_dict['classifier.3.bias']
state_dict['conv7.weight'] = decimate(conv_fc7_weight, m=[4, 4,
None, None])
state_dict['conv7.bias'] = decimate(conv_fc7_bias, m=[4])
self.load_state_dict(state_dict)
None
class AuxiliaryConvolutions(nn.Module):
"""
Additional convolutions to produce higher-level feature maps.
"""
def __init__(self):
super(AuxiliaryConvolutions, self).__init__()
self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0)
self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1)
self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0)
self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)
self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0)
self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0)
self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0)
self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0)
self.init_conv2d()
def init_conv2d(self):
"""
Initialize convolution parameters.
"""
for c in self.children():
if isinstance(c, nn.Conv2d):
nn.init.xavier_uniform_(c.weight)
nn.init.constant_(c.bias, 0.0)
def forward(self, conv7_feats):
"""
Forward propagation.
:param conv7_feats: lower-level conv7 feature map, a tensor of dimensions (N, 1024, 19, 19)
:return: higher-level feature maps conv8_2, conv9_2, conv10_2, and conv11_2
"""
out = F.relu(self.conv8_1(conv7_feats))
out = F.relu(self.conv8_2(out))
conv8_2_feats = out
out = F.relu(self.conv9_1(out))
out = F.relu(self.conv9_2(out))
conv9_2_feats = out
out = F.relu(self.conv10_1(out))
out = F.relu(self.conv10_2(out))
conv10_2_feats = out
out = F.relu(self.conv11_1(out))
conv11_2_feats = F.relu(self.conv11_2(out))
return conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats
class PredictionConvolutions(nn.Module):
"""
Convolutions to predict class scores and bounding boxes using lower and higher-level feature maps.
The bounding boxes (locations) are predicted as encoded offsets w.r.t each of the 8732 prior (default) boxes.
See 'cxcy_to_gcxgcy' in utils.py for the encoding definition.
The class scores represent the scores of each object class in each of the 8732 bounding boxes located.
A high score for 'background' = no object.
"""
def __init__(self, n_classes):
"""
:param n_classes: number of different types of objects
"""
super(PredictionConvolutions, self).__init__()
self.n_classes = n_classes
n_boxes = {'conv4_3': 4, 'conv7': 6, 'conv8_2': 6, 'conv9_2': 6,
'conv10_2': 4, 'conv11_2': 4}
self.loc_conv4_3 = nn.Conv2d(512, n_boxes['conv4_3'] * 4,
kernel_size=3, padding=1)
self.loc_conv7 = nn.Conv2d(1024, n_boxes['conv7'] * 4, kernel_size=
3, padding=1)
self.loc_conv8_2 = nn.Conv2d(512, n_boxes['conv8_2'] * 4,
kernel_size=3, padding=1)
self.loc_conv9_2 = nn.Conv2d(256, n_boxes['conv9_2'] * 4,
kernel_size=3, padding=1)
self.loc_conv10_2 = nn.Conv2d(256, n_boxes['conv10_2'] * 4,
kernel_size=3, padding=1)
self.loc_conv11_2 = nn.Conv2d(256, n_boxes['conv11_2'] * 4,
kernel_size=3, padding=1)
self.cl_conv4_3 = nn.Conv2d(512, n_boxes['conv4_3'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv7 = nn.Conv2d(1024, n_boxes['conv7'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv8_2 = nn.Conv2d(512, n_boxes['conv8_2'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv9_2 = nn.Conv2d(256, n_boxes['conv9_2'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv10_2 = nn.Conv2d(256, n_boxes['conv10_2'] * n_classes,
kernel_size=3, padding=1)
self.cl_conv11_2 = nn.Conv2d(256, n_boxes['conv11_2'] * n_classes,
kernel_size=3, padding=1)
self.init_conv2d()
def init_conv2d(self):
"""
Initialize convolution parameters.
"""
for c in self.children():
if isinstance(c, nn.Conv2d):
nn.init.xavier_uniform_(c.weight)
nn.init.constant_(c.bias, 0.0)
def forward(self, conv4_3_feats, conv7_feats, conv8_2_feats,
conv9_2_feats, conv10_2_feats, conv11_2_feats):
"""
Forward propagation.
:param conv4_3_feats: conv4_3 feature map, a tensor of dimensions (N, 512, 38, 38)
:param conv7_feats: conv7 feature map, a tensor of dimensions (N, 1024, 19, 19)
:param conv8_2_feats: conv8_2 feature map, a tensor of dimensions (N, 512, 10, 10)
:param conv9_2_feats: conv9_2 feature map, a tensor of dimensions (N, 256, 5, 5)
:param conv10_2_feats: conv10_2 feature map, a tensor of dimensions (N, 256, 3, 3)
:param conv11_2_feats: conv11_2 feature map, a tensor of dimensions (N, 256, 1, 1)
:return: 8732 locations and class scores (i.e. w.r.t each prior box) for each image
"""
batch_size = conv4_3_feats.size(0)
l_conv4_3 = self.loc_conv4_3(conv4_3_feats)
l_conv4_3 = l_conv4_3.permute(0, 2, 3, 1).contiguous()
l_conv4_3 = l_conv4_3.view(batch_size, -1, 4)
l_conv7 = self.loc_conv7(conv7_feats)
l_conv7 = l_conv7.permute(0, 2, 3, 1).contiguous()
l_conv7 = l_conv7.view(batch_size, -1, 4)
l_conv8_2 = self.loc_conv8_2(conv8_2_feats)
l_conv8_2 = l_conv8_2.permute(0, 2, 3, 1).contiguous()
l_conv8_2 = l_conv8_2.view(batch_size, -1, 4)
l_conv9_2 = self.loc_conv9_2(conv9_2_feats)
l_conv9_2 = l_conv9_2.permute(0, 2, 3, 1).contiguous()
l_conv9_2 = l_conv9_2.view(batch_size, -1, 4)
l_conv10_2 = self.loc_conv10_2(conv10_2_feats)
l_conv10_2 = l_conv10_2.permute(0, 2, 3, 1).contiguous()
l_conv10_2 = l_conv10_2.view(batch_size, -1, 4)
l_conv11_2 = self.loc_conv11_2(conv11_2_feats)
l_conv11_2 = l_conv11_2.permute(0, 2, 3, 1).contiguous()
l_conv11_2 = l_conv11_2.view(batch_size, -1, 4)
c_conv4_3 = self.cl_conv4_3(conv4_3_feats)
c_conv4_3 = c_conv4_3.permute(0, 2, 3, 1).contiguous()
c_conv4_3 = c_conv4_3.view(batch_size, -1, self.n_classes)
c_conv7 = self.cl_conv7(conv7_feats)
c_conv7 = c_conv7.permute(0, 2, 3, 1).contiguous()
c_conv7 = c_conv7.view(batch_size, -1, self.n_classes)
c_conv8_2 = self.cl_conv8_2(conv8_2_feats)
c_conv8_2 = c_conv8_2.permute(0, 2, 3, 1).contiguous()
c_conv8_2 = c_conv8_2.view(batch_size, -1, self.n_classes)
c_conv9_2 = self.cl_conv9_2(conv9_2_feats)
c_conv9_2 = c_conv9_2.permute(0, 2, 3, 1).contiguous()
c_conv9_2 = c_conv9_2.view(batch_size, -1, self.n_classes)
c_conv10_2 = self.cl_conv10_2(conv10_2_feats)
c_conv10_2 = c_conv10_2.permute(0, 2, 3, 1).contiguous()
c_conv10_2 = c_conv10_2.view(batch_size, -1, self.n_classes)
c_conv11_2 = self.cl_conv11_2(conv11_2_feats)
c_conv11_2 = c_conv11_2.permute(0, 2, 3, 1).contiguous()
c_conv11_2 = c_conv11_2.view(batch_size, -1, self.n_classes)
locs = torch.cat([l_conv4_3, l_conv7, l_conv8_2, l_conv9_2,
l_conv10_2, l_conv11_2], dim=1)
classes_scores = torch.cat([c_conv4_3, c_conv7, c_conv8_2,
c_conv9_2, c_conv10_2, c_conv11_2], dim=1)
return locs, classes_scores
class SSD300New(nn.Module):
"""
The SSD300 network - encapsulates the base VGG network, auxiliary, and prediction convolutions.
"""
def __init__(self, n_classes):
super(SSD300New, self).__init__()
self.n_classes = n_classes
self.base = VGGBase()
self.aux_convs = AuxiliaryConvolutions()
self.pred_convs = PredictionConvolutions(n_classes)
self.rescale_factors = nn.Parameter(torch.FloatTensor(1, 512, 1, 1))
nn.init.constant_(self.rescale_factors, 20)
self.priors_cxcy = self.create_prior_boxes()
def create_prior_boxes(self):
"""
Create the 8732 prior (default) boxes for the SSD300, as defined in the paper.
:return: prior boxes in center-size coordinates, a tensor of dimensions (8732, 4)
"""
fmap_dims = {'conv4_3': 38, 'conv7': 19, 'conv8_2': 10, 'conv9_2':
5, 'conv10_2': 3, 'conv11_2': 1}
obj_scales = {'conv4_3': 0.1, 'conv7': 0.2, 'conv8_2': 0.375,
'conv9_2': 0.55, 'conv10_2': 0.725, 'conv11_2': 0.9}
aspect_ratios = {'conv4_3': [1.0, 2.0, 0.5], 'conv7': [1.0, 2.0,
3.0, 0.5, 0.333], 'conv8_2': [1.0, 2.0, 3.0, 0.5, 0.333],
'conv9_2': [1.0, 2.0, 3.0, 0.5, 0.333], 'conv10_2': [1.0, 2.0,
0.5], 'conv11_2': [1.0, 2.0, 0.5]}
fmaps = list(fmap_dims.keys())
prior_boxes = []
for k, fmap in enumerate(fmaps):
for i in range(fmap_dims[fmap]):
for j in range(fmap_dims[fmap]):
cx = (j + 0.5) / fmap_dims[fmap]
cy = (i + 0.5) / fmap_dims[fmap]
for ratio in aspect_ratios[fmap]:
prior_boxes.append([cx, cy, obj_scales[fmap] * sqrt
(ratio), obj_scales[fmap] / sqrt(ratio)])
if ratio == 1.0:
try:
additional_scale = sqrt(obj_scales[fmap] *
obj_scales[fmaps[k + 1]])
except IndexError:
additional_scale = 1.0
prior_boxes.append([cx, cy, additional_scale,
additional_scale])
prior_boxes = torch.FloatTensor(prior_boxes)
prior_boxes.clamp_(0, 1)
return prior_boxes
def detect_objects(self, predicted_locs, predicted_scores):
"""
Decipher the 8732 locations and class scores (output of ths SSD300) to detect objects.
For each class, perform Non-Maximum Suppression (NMS) on boxes that are above a minimum threshold.
:param predicted_locs: predicted locations/boxes w.r.t the 8732 prior boxes, a tensor of dimensions (N, 8732, 4)
:param predicted_scores: class scores for each of the encoded locations/boxes, a tensor of dimensions (N, 8732, n_classes)
:param min_score: minimum threshold for a box to be considered a match for a certain class
:param max_overlap: maximum overlap two boxes can have so that the one with the lower score is not suppressed via NMS
:param top_k: if there are a lot of resulting detection across all classes, keep only the top 'k'
:return: detections (boxes, labels, and scores), lists of length batch_size
"""
batch_size = predicted_locs.size(0)
n_priors = self.priors_cxcy.size(0)
predicted_scores = F.softmax(predicted_scores, dim=2)
all_images_boxes = list()
scores = list()
assert n_priors == predicted_locs.size(1) == predicted_scores.size(1)
for i in range(batch_size):
decoded_locs = cxcy_to_xywh(gcxgcy_to_cxcy(predicted_locs[i],
self.priors_cxcy))
c = 1
class_scores = predicted_scores[i][:, c]
score_above_min_score = class_scores > 0.0
n_above_min_score = score_above_min_score.sum().item()
if n_above_min_score == 0:
continue
class_scores = class_scores[score_above_min_score]
class_decoded_locs = decoded_locs[score_above_min_score]
class_scores, sort_ind = class_scores.sort(dim=0, descending=True)
class_decoded_locs = class_decoded_locs[sort_ind]
best_loc = class_decoded_locs[0]
all_images_boxes.append(best_loc)
scores.append(class_scores[sort_ind][0])
return all_images_boxes, scores
def forward(self, input_0):
primals_32 = self.rescale_factors
primals_1 = self.base.conv1_1.weight
primals_2 = self.base.conv1_1.bias
primals_4 = self.base.conv1_2.weight
primals_5 = self.base.conv1_2.bias
primals_6 = self.base.conv2_1.weight
primals_7 = self.base.conv2_1.bias
primals_8 = self.base.conv2_2.weight
primals_9 = self.base.conv2_2.bias
primals_10 = self.base.conv3_1.weight
primals_11 = self.base.conv3_1.bias
primals_12 = self.base.conv3_2.weight
primals_13 = self.base.conv3_2.bias
primals_14 = self.base.conv3_3.weight
primals_15 = self.base.conv3_3.bias
primals_16 = self.base.conv4_1.weight
primals_17 = self.base.conv4_1.bias
primals_18 = self.base.conv4_2.weight
primals_19 = self.base.conv4_2.bias
primals_20 = self.base.conv4_3.weight
primals_21 = self.base.conv4_3.bias
primals_22 = self.base.conv5_1.weight
primals_23 = self.base.conv5_1.bias
primals_24 = self.base.conv5_2.weight
primals_25 = self.base.conv5_2.bias
primals_26 = self.base.conv5_3.weight
primals_27 = self.base.conv5_3.bias
primals_28 = self.base.conv6.weight
primals_29 = self.base.conv6.bias
primals_30 = self.base.conv7.weight
primals_31 = self.base.conv7.bias
primals_33 = self.aux_convs.conv8_1.weight
primals_34 = self.aux_convs.conv8_1.bias
primals_35 = self.aux_convs.conv8_2.weight
primals_36 = self.aux_convs.conv8_2.bias
primals_37 = self.aux_convs.conv9_1.weight
primals_38 = self.aux_convs.conv9_1.bias
primals_39 = self.aux_convs.conv9_2.weight
primals_40 = self.aux_convs.conv9_2.bias
primals_41 = self.aux_convs.conv10_1.weight
primals_42 = self.aux_convs.conv10_1.bias
primals_43 = self.aux_convs.conv10_2.weight
primals_44 = self.aux_convs.conv10_2.bias
primals_45 = self.aux_convs.conv11_1.weight
primals_46 = self.aux_convs.conv11_1.bias
primals_47 = self.aux_convs.conv11_2.weight
primals_48 = self.aux_convs.conv11_2.bias
primals_49 = self.pred_convs.loc_conv4_3.weight
primals_50 = self.pred_convs.loc_conv4_3.bias
primals_51 = self.pred_convs.loc_conv7.weight
primals_52 = self.pred_convs.loc_conv7.bias
primals_53 = self.pred_convs.loc_conv8_2.weight
primals_54 = self.pred_convs.loc_conv8_2.bias
primals_55 = self.pred_convs.loc_conv9_2.weight
primals_56 = self.pred_convs.loc_conv9_2.bias
primals_57 = self.pred_convs.loc_conv10_2.weight
primals_58 = self.pred_convs.loc_conv10_2.bias
primals_59 = self.pred_convs.loc_conv11_2.weight
primals_60 = self.pred_convs.loc_conv11_2.bias
primals_61 = self.pred_convs.cl_conv4_3.weight
primals_62 = self.pred_convs.cl_conv4_3.bias
primals_63 = self.pred_convs.cl_conv7.weight
primals_64 = self.pred_convs.cl_conv7.bias
primals_65 = self.pred_convs.cl_conv8_2.weight
primals_66 = self.pred_convs.cl_conv8_2.bias
primals_67 = self.pred_convs.cl_conv9_2.weight
primals_68 = self.pred_convs.cl_conv9_2.bias
primals_69 = self.pred_convs.cl_conv10_2.weight
primals_70 = self.pred_convs.cl_conv10_2.bias
primals_71 = self.pred_convs.cl_conv11_2.weight
primals_72 = self.pred_convs.cl_conv11_2.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9,
primals_10, primals_11, primals_12, primals_13, 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, primals_62, primals_63, primals_64,
primals_65, primals_66, primals_67, primals_68, primals_69,
primals_70, primals_71, primals_72])
return output[0], output[1]
|
ildoonet/ai-starthon-2019
|
SSD300
| false
| 15,742
|
[
"MIT"
] | 69
|
148855adcb731741938a86545a2d3282287f0a50
|
https://github.com/ildoonet/ai-starthon-2019/tree/148855adcb731741938a86545a2d3282287f0a50
|
SoftExp
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class SoftExp(nn.Module):
def __init__(self, input_size):
super(SoftExp, self).__init__()
self.alpha = nn.Parameter(torch.Tensor(input_size))
def forward(self, data):
self.alpha.data.clamp_(-1, 1)
positives = torch.gt(F.threshold(self.alpha, 0, 0), 0)
negatives = torch.gt(F.threshold(-self.alpha, 0, 0), 0)
output = data.clone()
pos_out = (torch.exp(self.alpha * data) - 1) / self.alpha + self.alpha
neg_out = -torch.log(1 - self.alpha * (data + self.alpha)) / self.alpha
output.masked_scatter_(positives, pos_out.masked_select(positives))
output.masked_scatter_(negatives, neg_out.masked_select(negatives))
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_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._inductor.runtime.triton_helpers import math as tl_math
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_clamp_gt_neg_threshold_0(in_ptr0, out_ptr0, out_ptr1,
out_ptr2, 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 = triton_helpers.maximum(tmp0, tmp1)
tmp3 = 1.0
tmp4 = triton_helpers.minimum(tmp2, tmp3)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tmp7 = tl.where(tmp6, tmp5, tmp4)
tmp8 = tmp7 > tmp5
tmp9 = -tmp4
tmp10 = tmp9 <= tmp5
tmp11 = tl.where(tmp10, tmp5, tmp9)
tmp12 = tmp11 > tmp5
tl.store(out_ptr0 + x0, tmp4, xmask)
tl.store(out_ptr1 + x0, tmp8, xmask)
tl.store(out_ptr2 + x0, tmp12, xmask)
@triton.jit
def triton_poi_fused_add_clone_div_exp_log_mul_neg_rsub_sub_1(in_ptr0,
in_ptr1, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
x1 = xindex % 4
tmp0 = tl.load(in_ptr0 + x0, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp0
tmp3 = tl_math.exp(tmp2)
tmp4 = 1.0
tmp5 = tmp3 - tmp4
tmp6 = tmp5 / tmp1
tmp7 = tmp6 + tmp1
tmp8 = tmp0 + tmp1
tmp9 = tmp1 * tmp8
tmp10 = tmp4 - tmp9
tmp11 = tl_math.log(tmp10)
tmp12 = -tmp11
tmp13 = tmp12 / tmp1
tl.store(out_ptr0 + x0, tmp0, xmask)
tl.store(out_ptr1 + x0, tmp7, xmask)
tl.store(out_ptr2 + x0, tmp13, xmask)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4,), (1,))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
buf1 = empty_strided_cuda((4,), (1,), torch.bool)
buf2 = empty_strided_cuda((4,), (1,), torch.bool)
get_raw_stream(0)
triton_poi_fused_clamp_gt_neg_threshold_0[grid(4)](primals_1, buf0,
buf1, buf2, 4, XBLOCK=4, num_warps=1, num_stages=1)
del primals_1
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.float32)
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_clone_div_exp_log_mul_neg_rsub_sub_1[grid(256)](
primals_2, buf0, buf3, buf4, buf5, 256, XBLOCK=128, num_warps=4,
num_stages=1)
return buf0, buf3, buf1, buf4, buf2, buf5, primals_2, buf0
class SoftExpNew(nn.Module):
def __init__(self, input_size):
super(SoftExpNew, self).__init__()
self.alpha = nn.Parameter(torch.Tensor(input_size))
def forward(self, input_0):
primals_1 = self.alpha
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
jpeg729/pytorch-bits
|
SoftExp
| false
| 15,743
|
[
"MIT"
] | 73
|
5d107094042c27472dfb7dee77506b603f5d3e45
|
https://github.com/jpeg729/pytorch-bits/tree/5d107094042c27472dfb7dee77506b603f5d3e45
|
OcrPtrNet
|
import math
import torch
from torch import nn
class OcrPtrNet(nn.Module):
def __init__(self, hidden_size, query_key_size=None):
super().__init__()
if query_key_size is None:
query_key_size = hidden_size
self.hidden_size = hidden_size
self.query_key_size = query_key_size
self.query = nn.Linear(hidden_size, query_key_size)
self.key = nn.Linear(hidden_size, query_key_size)
def forward(self, query_inputs, key_inputs, attention_mask):
extended_attention_mask = (1.0 - attention_mask) * -10000.0
assert extended_attention_mask.dim() == 2
extended_attention_mask = extended_attention_mask.unsqueeze(1)
query_layer = self.query(query_inputs)
if query_layer.dim() == 2:
query_layer = query_layer.unsqueeze(1)
squeeze_result = True
else:
squeeze_result = False
key_layer = self.key(key_inputs)
scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
scores = scores / math.sqrt(self.query_key_size)
scores = scores + extended_attention_mask
if squeeze_result:
scores = scores.squeeze(1)
return scores
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_add_div_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_out_ptr0 + x0, xmask)
tmp3 = tl.load(in_ptr0 + x0, xmask)
tmp1 = 0.5
tmp2 = tmp0 * tmp1
tmp4 = 1.0
tmp5 = tmp4 - tmp3
tmp6 = -10000.0
tmp7 = tmp5 * tmp6
tmp8 = tmp2 + tmp7
tl.store(in_out_ptr0 + x0, tmp8, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 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, 4), (4, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_3, primals_4, 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, 1), torch.float32)
extern_kernels.addmm(primals_6, primals_7, reinterpret_tensor(
primals_5, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
del primals_5
del primals_6
buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(buf1, (4, 4), (1, 4), 0),
out=buf2)
buf3 = reinterpret_tensor(buf2, (4, 1, 4), (4, 4, 1), 0)
del buf2
get_raw_stream(0)
triton_poi_fused_add_div_0[grid(16)](buf3, primals_1, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_1
return reinterpret_tensor(buf3, (4, 4), (4, 1), 0
), primals_4, primals_7, buf0, buf1
class OcrPtrNetNew(nn.Module):
def __init__(self, hidden_size, query_key_size=None):
super().__init__()
if query_key_size is None:
query_key_size = hidden_size
self.hidden_size = hidden_size
self.query_key_size = query_key_size
self.query = nn.Linear(hidden_size, query_key_size)
self.key = nn.Linear(hidden_size, query_key_size)
def forward(self, input_0, input_1, input_2):
primals_1 = self.query.weight
primals_3 = self.query.bias
primals_2 = self.key.weight
primals_6 = self.key.bias
primals_4 = input_0
primals_5 = input_1
primals_7 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
junj2ejj/sam-textvqa
|
OcrPtrNet
| false
| 15,744
|
[
"W3C"
] | 48
|
6bf646d741fb2536e3a8f331c78b594f6199df15
|
https://github.com/junj2ejj/sam-textvqa/tree/6bf646d741fb2536e3a8f331c78b594f6199df15
|
Cblock
|
import torch
import torch.nn as nn
import torch.nn.functional
class Cblock(nn.Module):
def __init__(self, in_ch, out_ch, stride=1):
super(Cblock, self).__init__()
self.block = nn.Conv3d(in_ch, out_ch, kernel_size=3, stride=stride,
padding=1, bias=True)
def forward(self, x):
return self.block(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'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
import torch.nn.functional
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 = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
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, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(1, 1,
1), padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf1 = buf0
del buf0
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 reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_1, reinterpret_tensor(primals_3, (1, 4, 4, 4, 4), (256,
64, 16, 4, 1), 0)
class CblockNew(nn.Module):
def __init__(self, in_ch, out_ch, stride=1):
super(CblockNew, self).__init__()
self.block = nn.Conv3d(in_ch, out_ch, kernel_size=3, stride=stride,
padding=1, bias=True)
def forward(self, input_0):
primals_1 = self.block.weight
primals_2 = self.block.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
Cblock
| false
| 15,745
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
Wave
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalConv1d(nn.Conv1d):
def __init__(self, input_size, hidden_size, kernel_size, stride=1,
dilation=1, groups=1, bias=True, sigmoid=None, tanh=None):
self.left_padding = (kernel_size - 1) * dilation
super(CausalConv1d, self).__init__(input_size, hidden_size,
kernel_size, stride=stride, padding=0, dilation=dilation,
groups=groups, bias=bias)
def forward(self, input):
x = F.pad(input.permute(1, 2, 0), (self.left_padding, 0))
conv_out = super(CausalConv1d, self).forward(x)
return conv_out.permute(2, 0, 1)
class Wave(nn.Module):
def __init__(self, input_size, hidden_size, layers=3, activation='tanh'):
super(Wave, self).__init__()
self.layers = []
prev_size = input_size
for layer in range(layers):
conv = CausalConv1d(prev_size, hidden_size, kernel_size=2,
dilation=2 ** layer)
self.layers.append(conv)
self.add_module('layer' + str(layer), conv)
prev_size = hidden_size
def forward(self, data):
for layer in self.layers:
data = layer(data)
return data
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'hidden_size': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_constant_pad_nd_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 5
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 = -1 + x1
tmp1 = tl.full([1, 1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.load(in_ptr0 + (-16 + y0 + 16 * x1), tmp2 & xmask & ymask,
eviction_policy='evict_last', other=0.0)
tl.store(out_ptr0 + (x1 + 5 * y0), tmp3, xmask & ymask)
@triton.jit
def triton_poi_fused_constant_pad_nd_1(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 96
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 6
x3 = xindex // 6
x1 = xindex // 6 % 4
x4 = xindex
tmp0 = -2 + x0
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.load(in_ptr0 + (-2 + x0 + 4 * x3), tmp2 & xmask, other=0.0)
tmp4 = tl.load(in_ptr1 + x1, tmp2 & xmask, eviction_policy='evict_last',
other=0.0)
tmp5 = tmp3 + tmp4
tmp6 = tl.full(tmp5.shape, 0.0, tmp5.dtype)
tmp7 = tl.where(tmp2, tmp5, tmp6)
tl.store(out_ptr0 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_constant_pad_nd_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x3 = xindex // 8
x1 = xindex // 8 % 4
x4 = xindex
tmp0 = -4 + x0
tmp1 = tl.full([1], 0, tl.int64)
tmp2 = tmp0 >= tmp1
tmp3 = tl.load(in_ptr0 + (-4 + x0 + 4 * x3), tmp2 & xmask, other=0.0)
tmp4 = tl.load(in_ptr1 + x1, tmp2 & xmask, eviction_policy='evict_last',
other=0.0)
tmp5 = tmp3 + tmp4
tmp6 = tl.full(tmp5.shape, 0.0, tmp5.dtype)
tmp7 = tl.where(tmp2, tmp5, tmp6)
tl.store(out_ptr0 + x4, tmp7, xmask)
@triton.jit
def triton_poi_fused_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4, 4, 2), (8, 2, 1))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 5), (20, 5, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_0[grid(16, 5)](primals_1, buf0, 16,
5, XBLOCK=8, YBLOCK=16, num_warps=4, num_stages=1)
del primals_1
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf2 = empty_strided_cuda((4, 4, 6), (24, 6, 1), torch.float32)
triton_poi_fused_constant_pad_nd_1[grid(96)](buf1, primals_3, buf2,
96, XBLOCK=128, num_warps=4, num_stages=1)
del buf1
del primals_3
buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1,),
padding=(0,), dilation=(2,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4), (16, 4, 1))
buf4 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_constant_pad_nd_2[grid(128)](buf3, primals_5, buf4,
128, XBLOCK=128, num_warps=4, num_stages=1)
del buf3
del primals_5
buf5 = extern_kernels.convolution(buf4, primals_6, stride=(1,),
padding=(0,), dilation=(4,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf5, (4, 4, 4), (16, 4, 1))
buf6 = buf5
del buf5
triton_poi_fused_convolution_3[grid(64)](buf6, primals_7, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_7
return reinterpret_tensor(buf6, (4, 4, 4), (1, 16, 4), 0
), primals_2, primals_4, primals_6, buf0, buf2, buf4
class CausalConv1d(nn.Conv1d):
def __init__(self, input_size, hidden_size, kernel_size, stride=1,
dilation=1, groups=1, bias=True, sigmoid=None, tanh=None):
self.left_padding = (kernel_size - 1) * dilation
super(CausalConv1d, self).__init__(input_size, hidden_size,
kernel_size, stride=stride, padding=0, dilation=dilation,
groups=groups, bias=bias)
def forward(self, input):
x = F.pad(input.permute(1, 2, 0), (self.left_padding, 0))
conv_out = super(CausalConv1d, self).forward(x)
return conv_out.permute(2, 0, 1)
class WaveNew(nn.Module):
def __init__(self, input_size, hidden_size, layers=3, activation='tanh'):
super(WaveNew, self).__init__()
self.layers = []
prev_size = input_size
for layer in range(layers):
conv = CausalConv1d(prev_size, hidden_size, kernel_size=2,
dilation=2 ** layer)
self.layers.append(conv)
self.add_module('layer' + str(layer), conv)
prev_size = hidden_size
def forward(self, input_0):
primals_2 = self.layer0.weight
primals_3 = self.layer0.bias
primals_4 = self.layer1.weight
primals_5 = self.layer1.bias
primals_6 = self.layer2.weight
primals_7 = self.layer2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
jpeg729/pytorch-bits
|
Wave
| false
| 15,746
|
[
"MIT"
] | 73
|
5d107094042c27472dfb7dee77506b603f5d3e45
|
https://github.com/jpeg729/pytorch-bits/tree/5d107094042c27472dfb7dee77506b603f5d3e45
|
DoubleConv
|
import torch
import torch.nn as nn
import torch.nn.functional
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
self.conv1_ = nn.Conv3d(in_channels, mid_channels, kernel_size=3,
padding=1)
self.relu1_ = nn.ReLU(inplace=True)
self.conv2_ = nn.Conv3d(mid_channels, out_channels, kernel_size=3,
padding=1)
self.relu2_ = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv1_(x)
x = self.relu1_(x)
x = self.conv2_(x)
x = self.relu2_(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_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
x1 = xindex // 64
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(1, 1,
1), padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf1 = 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 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 4,
4, 4), (0, 64, 16, 4, 1), 0), primals_4, stride=(1, 1, 1),
padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf2, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf2
buf4 = 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, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_4, reinterpret_tensor(primals_3, (1, 4,
4, 4, 4), (256, 64, 16, 4, 1), 0), reinterpret_tensor(buf1, (1, 4,
4, 4, 4), (256, 64, 16, 4, 1), 0), buf4, buf5
class DoubleConvNew(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
self.conv1_ = nn.Conv3d(in_channels, mid_channels, kernel_size=3,
padding=1)
self.relu1_ = nn.ReLU(inplace=True)
self.conv2_ = nn.Conv3d(mid_channels, out_channels, kernel_size=3,
padding=1)
self.relu2_ = nn.ReLU(inplace=True)
def forward(self, input_0):
primals_1 = self.conv1_.weight
primals_2 = self.conv1_.bias
primals_4 = self.conv2_.weight
primals_5 = self.conv2_.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
DoubleConv
| false
| 15,747
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
SelfAttentionGPT2
|
import torch
from torch import nn
def mask_(matrices, maskval=0.0, mask_diagonal=True):
"""
Masks out all values in the given batch of matrices where i <= j holds,
i < j if mask_diagonal is false
In place operation
:param tns:
:return:
"""
h, w = matrices.size(-2), matrices.size(-1)
indices = torch.triu_indices(h, w, offset=0 if mask_diagonal else 1)
matrices[..., indices[0], indices[1]] = maskval
class SelfAttentionGPT2(nn.Module):
"""
This is the self-attention operation as implemented in the Huggingface port of GPT2. The code has been
simplified to remove several features not used here but otherwise it should do exactly the same as GPT2 when run with
normal parameters.
It is very similar to the default SelfAttention below, with the exception of the way it's initialized and some
small speed improvements in the custom implementation of the linear layer (the Conv1D defined above).
We include this primarily for comparison with our own canonical implementation to check for performance differences.
"""
def __init__(self, emb, heads, mask=False):
super().__init__()
self.nheads = heads
self.emb = emb
self.mask = mask
self.c_attn = nn.Linear(emb, 3 * emb)
self.c_proj = nn.Linear(emb, emb)
def _attn(self, q, k, v):
dot = torch.matmul(q, k)
dot = dot / float(v.size(-1)) ** 0.5
if self.mask:
mask_(dot, maskval=float('-inf'), mask_diagonal=False)
dot = nn.Softmax(dim=-1)(dot)
return torch.matmul(dot, v)
def merge_heads(self, x):
x = x.permute(0, 2, 1, 3).contiguous()
new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)
return x.view(*new_x_shape)
def split_heads(self, x, is_key=False):
new_x_shape = x.size()[:-1] + (self.nheads, x.size(-1) // self.nheads)
x = x.view(*new_x_shape)
if is_key:
return x.permute(0, 2, 3, 1)
else:
return x.permute(0, 2, 1, 3)
def forward(self, input_sequence):
_b, _t, e = input_sequence.size()
query, key, value = self.c_attn(input_sequence).split(e, dim=2)
query = self.split_heads(query)
key = self.split_heads(key, is_key=True)
value = self.split_heads(value)
a = self._attn(query, key, value)
a = self.merge_heads(a)
a = self.c_proj(a)
return a
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'emb': 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
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_1(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (4 + y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (4 + 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_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)
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_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_clone_4(in_ptr0, 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 + (8 + y0 + 12 * x2 + 48 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + (8 + y0), ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_5(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_2, (12, 4), (4, 1))
assert_size_stride(primals_3, (12,), (1,))
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_1, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_2, (4, 12), (1, 4), 0), out=buf0)
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(16, 4)](buf0, primals_3, buf1, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 1, 4), (16, 4, 4, 1), torch.float32)
triton_poi_fused_clone_1[grid(16, 4)](buf0, primals_3, buf2, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf2, (16, 1, 4), (4, 0, 1), 0), out=buf3)
buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf5 = reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf3
triton_poi_fused__softmax_3[grid(256)](buf4, buf5, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf4
buf6 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf0, primals_3, buf6, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
del buf0
del primals_3
buf7 = empty_strided_cuda((16, 4, 1), (4, 1, 1), torch.float32)
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, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_5[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.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), (16, 4, 1), 0
), reinterpret_tensor(primals_1, (16, 4), (4, 1), 0
), buf5, reinterpret_tensor(buf8, (16, 4), (4, 1), 0
), primals_4, reinterpret_tensor(buf6, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf1, (16, 1, 4), (4, 1, 1), 0
), reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 4), 0)
def mask_(matrices, maskval=0.0, mask_diagonal=True):
"""
Masks out all values in the given batch of matrices where i <= j holds,
i < j if mask_diagonal is false
In place operation
:param tns:
:return:
"""
h, w = matrices.size(-2), matrices.size(-1)
indices = torch.triu_indices(h, w, offset=0 if mask_diagonal else 1)
matrices[..., indices[0], indices[1]] = maskval
class SelfAttentionGPT2New(nn.Module):
"""
This is the self-attention operation as implemented in the Huggingface port of GPT2. The code has been
simplified to remove several features not used here but otherwise it should do exactly the same as GPT2 when run with
normal parameters.
It is very similar to the default SelfAttention below, with the exception of the way it's initialized and some
small speed improvements in the custom implementation of the linear layer (the Conv1D defined above).
We include this primarily for comparison with our own canonical implementation to check for performance differences.
"""
def __init__(self, emb, heads, mask=False):
super().__init__()
self.nheads = heads
self.emb = emb
self.mask = mask
self.c_attn = nn.Linear(emb, 3 * emb)
self.c_proj = nn.Linear(emb, emb)
def _attn(self, q, k, v):
dot = torch.matmul(q, k)
dot = dot / float(v.size(-1)) ** 0.5
if self.mask:
mask_(dot, maskval=float('-inf'), mask_diagonal=False)
dot = nn.Softmax(dim=-1)(dot)
return torch.matmul(dot, v)
def merge_heads(self, x):
x = x.permute(0, 2, 1, 3).contiguous()
new_x_shape = x.size()[:-2] + (x.size(-2) * x.size(-1),)
return x.view(*new_x_shape)
def split_heads(self, x, is_key=False):
new_x_shape = x.size()[:-1] + (self.nheads, x.size(-1) // self.nheads)
x = x.view(*new_x_shape)
if is_key:
return x.permute(0, 2, 3, 1)
else:
return x.permute(0, 2, 1, 3)
def forward(self, input_0):
primals_2 = self.c_attn.weight
primals_3 = self.c_attn.bias
primals_4 = self.c_proj.weight
primals_5 = self.c_proj.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jplasser/former
|
SelfAttentionGPT2
| false
| 15,749
|
[
"MIT"
] | 674
|
7dabf7b355e94f2f0af966bd0daead539a30675a
|
https://github.com/jplasser/former/tree/7dabf7b355e94f2f0af966bd0daead539a30675a
|
Hflip
|
import torch
import torch.nn as nn
def hflip(input: 'torch.Tensor') ->torch.Tensor:
return torch.flip(input, [-1])
class Hflip(nn.Module):
"""Horizontally flip a tensor image or a batch of tensor images.
Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
input: input tensor.
Returns:
The horizontally flipped image tensor.
Examples:
>>> hflip = Hflip()
>>> input = torch.tensor([[[
... [0., 0., 0.],
... [0., 0., 0.],
... [0., 1., 1.]
... ]]])
>>> hflip(input)
tensor([[[[0., 0., 0.],
[0., 0., 0.],
[1., 1., 0.]]]])
"""
def forward(self, input: 'torch.Tensor') ->torch.Tensor:
return hflip(input)
def __repr__(self):
return self.__class__.__name__
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn 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_flip_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 4
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + (3 + -1 * x0 + 4 * x1), xmask, eviction_policy
='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_flip_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
def hflip(input: 'torch.Tensor') ->torch.Tensor:
return torch.flip(input, [-1])
class HflipNew(nn.Module):
"""Horizontally flip a tensor image or a batch of tensor images.
Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
Args:
input: input tensor.
Returns:
The horizontally flipped image tensor.
Examples:
>>> hflip = Hflip()
>>> input = torch.tensor([[[
... [0., 0., 0.],
... [0., 0., 0.],
... [0., 1., 1.]
... ]]])
>>> hflip(input)
tensor([[[[0., 0., 0.],
[0., 0., 0.],
[1., 1., 0.]]]])
"""
def __repr__(self):
return self.__class__.__name__
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
justanhduc/kornia
|
Hflip
| false
| 15,750
|
[
"ECL-2.0",
"Apache-2.0"
] | 51
|
c14081292dfb2491fad50ba10e27491cad8cb3e3
|
https://github.com/justanhduc/kornia/tree/c14081292dfb2491fad50ba10e27491cad8cb3e3
|
convBlock
|
import torch
import torch.nn as nn
import torch.nn.functional
class convBlock(nn.Module):
"""
A convolutional block including conv, BN, nonliear activiation, residual connection
"""
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, bias=True, batchnorm=False, residual=False, nonlinear=nn
.LeakyReLU(0.2)):
"""
:param in_channels:
:param out_channels:
:param kernel_size:
:param stride:
:param padding:
:param bias:
:param batchnorm:
:param residual:
:param nonlinear:
"""
super(convBlock, self).__init__()
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size,
stride=stride, padding=padding, bias=bias)
self.bn = nn.BatchNorm3d(out_channels) if batchnorm else None
self.nonlinear = nonlinear
self.residual = residual
def forward(self, x):
x = self.conv(x)
if self.bn:
x = self.bn(x)
if self.nonlinear:
x = self.nonlinear(x)
if self.residual:
x += x
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_leaky_relu_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 64
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp5 = 0.2
tmp6 = tmp2 * tmp5
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr1 + x2, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(1, 1,
1), padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_leaky_relu_0[grid(256)](buf0, primals_2, buf1,
buf2, 256, XBLOCK=256, num_warps=4, num_stages=1)
del buf0
del primals_2
return buf2, primals_1, reinterpret_tensor(primals_3, (1, 4, 4, 4, 4),
(256, 64, 16, 4, 1), 0), buf1
class convBlockNew(nn.Module):
"""
A convolutional block including conv, BN, nonliear activiation, residual connection
"""
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1, bias=True, batchnorm=False, residual=False, nonlinear=nn
.LeakyReLU(0.2)):
"""
:param in_channels:
:param out_channels:
:param kernel_size:
:param stride:
:param padding:
:param bias:
:param batchnorm:
:param residual:
:param nonlinear:
"""
super(convBlockNew, self).__init__()
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size,
stride=stride, padding=padding, bias=bias)
self.bn = nn.BatchNorm3d(out_channels) if batchnorm else None
self.nonlinear = nonlinear
self.residual = residual
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]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
convBlock
| false
| 15,751
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
BinaryFocalLossWithLogits
|
import torch
import torch.nn as nn
def binary_focal_loss_with_logits(input: 'torch.Tensor', target:
'torch.Tensor', alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='none', eps: 'float'=1e-08) ->torch.Tensor:
"""Function that computes Binary Focal loss.
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
input: input data tensor with shape :math:`(N, 1, *)`.
target: the target tensor with shape :math:`(N, 1, *)`.
alpha: Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
eps: for numerically stability when dividing.
Returns:
the computed loss.
Examples:
>>> num_classes = 1
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> logits = torch.tensor([[[[6.325]]],[[[5.26]]],[[[87.49]]]])
>>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
>>> binary_focal_loss_with_logits(logits, labels, **kwargs)
tensor(4.6052)
"""
if not isinstance(input, torch.Tensor):
raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
type(input)))
if not len(input.shape) >= 2:
raise ValueError('Invalid input shape, we expect BxCx*. Got: {}'.
format(input.shape))
if input.size(0) != target.size(0):
raise ValueError(
'Expected input batch_size ({}) to match target batch_size ({}).'
.format(input.size(0), target.size(0)))
probs = torch.sigmoid(input)
target = target.unsqueeze(dim=1)
loss_tmp = -alpha * torch.pow(1.0 - probs + eps, gamma
) * target * torch.log(probs + eps) - (1 - alpha) * torch.pow(probs +
eps, gamma) * (1.0 - target) * torch.log(1.0 - probs + eps)
loss_tmp = loss_tmp.squeeze(dim=1)
if reduction == 'none':
loss = loss_tmp
elif reduction == 'mean':
loss = torch.mean(loss_tmp)
elif reduction == 'sum':
loss = torch.sum(loss_tmp)
else:
raise NotImplementedError('Invalid reduction mode: {}'.format(
reduction))
return loss
class BinaryFocalLossWithLogits(nn.Module):
"""Criterion that computes Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
alpha): Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
Shape:
- Input: :math:`(N, 1, *)`.
- Target: :math:`(N, 1, *)`.
Examples:
>>> N = 1 # num_classes
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> loss = BinaryFocalLossWithLogits(**kwargs)
>>> input = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = loss(input, target)
>>> output.backward()
"""
def __init__(self, alpha: 'float', gamma: 'float'=2.0, reduction: 'str'
='none') ->None:
super(BinaryFocalLossWithLogits, self).__init__()
self.alpha: 'float' = alpha
self.gamma: 'float' = gamma
self.reduction: 'str' = reduction
self.eps: 'float' = 1e-08
def forward(self, input: 'torch.Tensor', target: 'torch.Tensor'
) ->torch.Tensor:
return binary_focal_loss_with_logits(input, target, self.alpha,
self.gamma, self.reduction, self.eps)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'alpha': 4}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import math as tl_math
import 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_log_mul_pow_rsub_sigmoid_squeeze_sub_0(in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex % 256
x0 = xindex % 64
x2 = xindex // 256
x4 = xindex
tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp1 = tl.sigmoid(tmp0)
tmp2 = 1.0
tmp3 = tmp2 - tmp1
tmp4 = 1e-08
tmp5 = tmp3 + tmp4
tmp6 = tmp5 * tmp5
tmp7 = -4.0
tmp8 = tmp6 * tmp7
tmp10 = tmp8 * tmp9
tmp11 = tmp1 + tmp4
tmp12 = tl_math.log(tmp11)
tmp13 = tmp10 * tmp12
tmp14 = tmp11 * tmp11
tmp15 = -3.0
tmp16 = tmp14 * tmp15
tmp17 = tmp2 - tmp9
tmp18 = tmp16 * tmp17
tmp19 = tl_math.log(tmp5)
tmp20 = tmp18 * tmp19
tmp21 = tmp13 - tmp20
tl.store(out_ptr0 + x4, tmp21, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_add_log_mul_pow_rsub_sigmoid_squeeze_sub_0[grid(1024)
](arg0_1, arg1_1, buf0, 1024, XBLOCK=128, num_warps=4, num_stages=1
)
del arg0_1
del arg1_1
return buf0,
def binary_focal_loss_with_logits(input: 'torch.Tensor', target:
'torch.Tensor', alpha: 'float'=0.25, gamma: 'float'=2.0, reduction:
'str'='none', eps: 'float'=1e-08) ->torch.Tensor:
"""Function that computes Binary Focal loss.
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
input: input data tensor with shape :math:`(N, 1, *)`.
target: the target tensor with shape :math:`(N, 1, *)`.
alpha: Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
eps: for numerically stability when dividing.
Returns:
the computed loss.
Examples:
>>> num_classes = 1
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> logits = torch.tensor([[[[6.325]]],[[[5.26]]],[[[87.49]]]])
>>> labels = torch.tensor([[[1.]],[[1.]],[[0.]]])
>>> binary_focal_loss_with_logits(logits, labels, **kwargs)
tensor(4.6052)
"""
if not isinstance(input, torch.Tensor):
raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
type(input)))
if not len(input.shape) >= 2:
raise ValueError('Invalid input shape, we expect BxCx*. Got: {}'.
format(input.shape))
if input.size(0) != target.size(0):
raise ValueError(
'Expected input batch_size ({}) to match target batch_size ({}).'
.format(input.size(0), target.size(0)))
probs = torch.sigmoid(input)
target = target.unsqueeze(dim=1)
loss_tmp = -alpha * torch.pow(1.0 - probs + eps, gamma
) * target * torch.log(probs + eps) - (1 - alpha) * torch.pow(probs +
eps, gamma) * (1.0 - target) * torch.log(1.0 - probs + eps)
loss_tmp = loss_tmp.squeeze(dim=1)
if reduction == 'none':
loss = loss_tmp
elif reduction == 'mean':
loss = torch.mean(loss_tmp)
elif reduction == 'sum':
loss = torch.sum(loss_tmp)
else:
raise NotImplementedError('Invalid reduction mode: {}'.format(
reduction))
return loss
class BinaryFocalLossWithLogitsNew(nn.Module):
"""Criterion that computes Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
.. math::
\\text{FL}(p_t) = -\\alpha_t (1 - p_t)^{\\gamma} \\, \\text{log}(p_t)
where:
- :math:`p_t` is the model's estimated probability for each class.
Args:
alpha): Weighting factor for the rare class :math:`\\alpha \\in [0, 1]`.
gamma: Focusing parameter :math:`\\gamma >= 0`.
reduction: Specifies the reduction to apply to the
output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
will be applied, ``'mean'``: the sum of the output will be divided by
the number of elements in the output, ``'sum'``: the output will be
summed.
Shape:
- Input: :math:`(N, 1, *)`.
- Target: :math:`(N, 1, *)`.
Examples:
>>> N = 1 # num_classes
>>> kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
>>> loss = BinaryFocalLossWithLogits(**kwargs)
>>> input = torch.randn(1, N, 3, 5, requires_grad=True)
>>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
>>> output = loss(input, target)
>>> output.backward()
"""
def __init__(self, alpha: 'float', gamma: 'float'=2.0, reduction: 'str'
='none') ->None:
super(BinaryFocalLossWithLogitsNew, self).__init__()
self.alpha: 'float' = alpha
self.gamma: 'float' = gamma
self.reduction: 'str' = reduction
self.eps: 'float' = 1e-08
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
justanhduc/kornia
|
BinaryFocalLossWithLogits
| false
| 15,752
|
[
"ECL-2.0",
"Apache-2.0"
] | 51
|
c14081292dfb2491fad50ba10e27491cad8cb3e3
|
https://github.com/justanhduc/kornia/tree/c14081292dfb2491fad50ba10e27491cad8cb3e3
|
Critic
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self, dim, dim_embed):
super(Encoder, self).__init__()
self.embed = nn.Conv1d(dim, dim_embed, 1)
return
def forward(self, input):
input_2 = input.permute(0, 2, 1)
out = self.embed(input_2)
return out.permute(0, 2, 1)
class Critic(nn.Module):
def __init__(self, batch_size, n_nodes, dim_s, dim_embed, embeding_type
='conv1d'):
super(Critic, self).__init__()
self.dim_embed = dim_embed
if embeding_type == 'conv1d':
self.project_s = Encoder(dim_s, dim_embed)
self.w_a = Encoder(dim_embed, dim_embed)
self.w_c = Encoder(dim_embed * 2, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
self.v_c = nn.Parameter(torch.randn(dim_embed))
else:
self.project_s = nn.Linear(dim_s, dim_embed)
self.w_a = nn.Linear(dim_embed, dim_embed)
self.w_c = nn.Linear(dim_embed * 2, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
self.v_c = nn.Parameter(torch.randn(dim_embed))
self.linear_1 = nn.Linear(dim_embed, dim_embed)
self.linear_2 = nn.Linear(dim_embed, 1)
for p in self.parameters():
if len(p.shape) > 1:
nn.init.xavier_uniform_(p)
return
def forward(self, o):
instance = o[1]
projected_instance = self.project_s(instance)
u_t = torch.matmul(self.v_a, torch.tanh(self.w_a(projected_instance
)).permute(0, 2, 1))
a_t = F.softmax(u_t, dim=1).unsqueeze(2).repeat(1, 1, self.dim_embed)
c_t = a_t * projected_instance
hidden_2 = torch.cat((projected_instance, c_t), dim=2)
u_t_2 = torch.matmul(self.v_c, torch.tanh(self.w_c(hidden_2)).
permute(0, 2, 1))
prob = torch.softmax(u_t_2, dim=1)
h_i = torch.bmm(prob.unsqueeze(1), projected_instance).squeeze(1)
output_1 = F.relu(self.linear_1(h_i))
v = self.linear_2(output_1).squeeze(1)
return v
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'batch_size': 4, 'n_nodes': 4, 'dim_s': 4, 'dim_embed': 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_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (64 + y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 4 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_mv_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + (16 * (x0 // 4) + x0 % 4), xmask)
tmp2 = tl.load(in_ptr1 + 0)
tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
tmp5 = tl.load(in_ptr0 + (4 + 16 * (x0 // 4) + x0 % 4), xmask)
tmp7 = tl.load(in_ptr1 + 1)
tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
tmp11 = tl.load(in_ptr0 + (8 + 16 * (x0 // 4) + x0 % 4), xmask)
tmp13 = tl.load(in_ptr1 + 2)
tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
tmp17 = tl.load(in_ptr0 + (12 + 16 * (x0 // 4) + x0 % 4), xmask)
tmp19 = tl.load(in_ptr1 + 3)
tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
tmp1 = libdevice.tanh(tmp0)
tmp4 = tmp1 * tmp3
tmp6 = libdevice.tanh(tmp5)
tmp9 = tmp6 * tmp8
tmp10 = tmp4 + tmp9
tmp12 = libdevice.tanh(tmp11)
tmp15 = tmp12 * tmp14
tmp16 = tmp10 + tmp15
tmp18 = libdevice.tanh(tmp17)
tmp21 = tmp18 * tmp20
tmp22 = tmp16 + tmp21
tl.store(out_ptr0 + x0, tmp22, xmask)
@triton.jit
def triton_poi_fused__softmax_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused__softmax_4(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = tmp1 + tmp2
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp8 = tmp0 / tmp7
tl.store(out_ptr0 + x2, tmp8, xmask)
@triton.jit
def triton_poi_fused_repeat_5(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
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tl.store(out_ptr0 + x2, tmp0, xmask)
@triton.jit
def triton_poi_fused_cat_6(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 8
x1 = xindex // 8 % 4
x2 = xindex // 32
x3 = xindex // 8
x4 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x1 + 4 * x0 + 16 * x2), tmp4 & xmask,
eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (4 * x3 + (-4 + x0)), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp10 = tl.load(in_ptr0 + (x1 + 4 * (-4 + x0) + 16 * x2), tmp6 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp9 * tmp10
tmp12 = tl.full(tmp11.shape, 0.0, tmp11.dtype)
tmp13 = tl.where(tmp6, tmp11, tmp12)
tmp14 = tl.where(tmp4, tmp5, tmp13)
tl.store(out_ptr0 + x4, tmp14, xmask)
@triton.jit
def triton_poi_fused_convolution_7(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 32
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 % 8
y1 = yindex // 8
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 8 * x2 + 32 * y1), xmask & ymask,
eviction_policy='evict_last')
tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_relu_8(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)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 1), (4, 1, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 8, 1), (8, 1, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4, 4), (4, 1))
assert_size_stride(primals_11, (4,), (1,))
assert_size_stride(primals_12, (1, 4), (4, 1))
assert_size_stride(primals_13, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(16, 4)](primals_1, buf0, 16, 4,
XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1)
buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4), (16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_1[grid(64)](buf2, primals_3, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_3
buf3 = extern_kernels.convolution(buf2, primals_5, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4), (16, 4, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_1[grid(64)](buf4, primals_6, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_6
buf5 = empty_strided_cuda((16,), (1,), torch.float32)
triton_poi_fused_mv_2[grid(16)](buf4, primals_4, buf5, 16, XBLOCK=
16, num_warps=1, num_stages=1)
buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
triton_poi_fused__softmax_3[grid(16)](buf5, buf6, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf7 = reinterpret_tensor(buf5, (4, 4), (4, 1), 0)
del buf5
triton_poi_fused__softmax_4[grid(16)](buf6, buf7, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf8 = buf0
del buf0
triton_poi_fused_repeat_5[grid(64)](buf7, buf8, 64, XBLOCK=64,
num_warps=1, num_stages=1)
buf9 = empty_strided_cuda((4, 4, 8), (32, 8, 1), torch.float32)
triton_poi_fused_cat_6[grid(128)](buf2, buf8, buf9, 128, XBLOCK=128,
num_warps=4, num_stages=1)
buf10 = empty_strided_cuda((4, 8, 4), (32, 4, 1), torch.float32)
triton_poi_fused_convolution_7[grid(32, 4)](buf9, buf10, 32, 4,
XBLOCK=4, YBLOCK=32, num_warps=4, num_stages=1)
buf11 = extern_kernels.convolution(buf10, primals_8, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf11, (4, 4, 4), (16, 4, 1))
del buf10
buf12 = buf11
del buf11
triton_poi_fused_convolution_1[grid(64)](buf12, primals_9, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del primals_9
buf13 = reinterpret_tensor(buf7, (16,), (1,), 0)
del buf7
triton_poi_fused_mv_2[grid(16)](buf12, primals_7, buf13, 16, XBLOCK
=16, num_warps=1, num_stages=1)
buf14 = buf6
del buf6
triton_poi_fused__softmax_3[grid(16)](buf13, buf14, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf15 = reinterpret_tensor(buf13, (4, 4), (4, 1), 0)
del buf13
triton_poi_fused__softmax_4[grid(16)](buf14, buf15, 16, XBLOCK=16,
num_warps=1, num_stages=1)
buf16 = reinterpret_tensor(buf14, (4, 1, 4), (4, 4, 1), 0)
del buf14
extern_kernels.bmm(reinterpret_tensor(buf15, (4, 1, 4), (4, 4, 1),
0), reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0), out=buf16)
buf17 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(reinterpret_tensor(buf16, (4, 4), (4, 1), 0),
reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf17)
buf18 = buf17
del buf17
triton_poi_fused_relu_8[grid(16)](buf18, primals_11, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del primals_11
buf20 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_13, buf18, reinterpret_tensor(
primals_12, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf20)
del primals_13
return (reinterpret_tensor(buf20, (4,), (1,), 0), primals_2, primals_4,
primals_5, primals_7, primals_8, reinterpret_tensor(primals_1, (4,
4, 4), (16, 1, 4), 64), reinterpret_tensor(buf2, (4, 4, 4), (16, 1,
4), 0), buf4, buf8, reinterpret_tensor(buf9, (4, 8, 4), (32, 1, 8),
0), buf12, buf15, reinterpret_tensor(buf16, (4, 4), (4, 1), 0),
buf18, primals_12, primals_10)
class Encoder(nn.Module):
def __init__(self, dim, dim_embed):
super(Encoder, self).__init__()
self.embed = nn.Conv1d(dim, dim_embed, 1)
return
def forward(self, input):
input_2 = input.permute(0, 2, 1)
out = self.embed(input_2)
return out.permute(0, 2, 1)
class CriticNew(nn.Module):
def __init__(self, batch_size, n_nodes, dim_s, dim_embed, embeding_type
='conv1d'):
super(CriticNew, self).__init__()
self.dim_embed = dim_embed
if embeding_type == 'conv1d':
self.project_s = Encoder(dim_s, dim_embed)
self.w_a = Encoder(dim_embed, dim_embed)
self.w_c = Encoder(dim_embed * 2, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
self.v_c = nn.Parameter(torch.randn(dim_embed))
else:
self.project_s = nn.Linear(dim_s, dim_embed)
self.w_a = nn.Linear(dim_embed, dim_embed)
self.w_c = nn.Linear(dim_embed * 2, dim_embed)
self.v_a = nn.Parameter(torch.randn(dim_embed))
self.v_c = nn.Parameter(torch.randn(dim_embed))
self.linear_1 = nn.Linear(dim_embed, dim_embed)
self.linear_2 = nn.Linear(dim_embed, 1)
for p in self.parameters():
if len(p.shape) > 1:
nn.init.xavier_uniform_(p)
return
def forward(self, input_0):
primals_3 = self.v_a
primals_4 = self.v_c
primals_2 = self.project_s.embed.weight
primals_6 = self.project_s.embed.bias
primals_5 = self.w_a.embed.weight
primals_7 = self.w_a.embed.bias
primals_8 = self.w_c.embed.weight
primals_9 = self.w_c.embed.bias
primals_10 = self.linear_1.weight
primals_11 = self.linear_1.bias
primals_12 = self.linear_2.weight
primals_13 = self.linear_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]
|
jomavera/DRL_HFV
|
Critic
| false
| 15,753
|
[
"MIT"
] | 114
|
043e32805ec79fd35281b864659c194d7b89f5bc
|
https://github.com/jomavera/DRL_HFV/tree/043e32805ec79fd35281b864659c194d7b89f5bc
|
ConvMeanPool
|
import torch
from torch import nn
class MyConvo2d(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True,
stride=1, bias=True):
super(MyConvo2d, self).__init__()
self.he_init = he_init
self.padding = int((kernel_size - 1) / 2)
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride=1,
padding=self.padding, bias=bias)
def forward(self, input):
output = self.conv(input)
return output
class ConvMeanPool(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True):
super(ConvMeanPool, self).__init__()
self.he_init = he_init
self.conv = MyConvo2d(input_dim, output_dim, kernel_size, he_init=
self.he_init)
def forward(self, input):
output = self.conv(input)
output = (output[:, :, ::2, ::2] + output[:, :, 1::2, ::2] + output
[:, :, ::2, 1::2] + output[:, :, 1::2, 1::2]) / 4
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 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 import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_div_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK:
tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 2
x1 = xindex // 2 % 2
x4 = xindex // 4
x2 = xindex // 4 % 4
x6 = xindex
tmp0 = tl.load(in_ptr0 + (2 * x0 + 6 * x1 + 9 * x4), xmask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + x2, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (3 + 2 * x0 + 9 * x4), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 6 * x1 + 9 * x4), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (4 + 9 * x4), xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp3 + tmp1
tmp5 = tmp2 + tmp4
tmp7 = tmp6 + tmp1
tmp8 = tmp5 + tmp7
tmp10 = tmp9 + tmp1
tmp11 = tmp8 + tmp10
tmp12 = 0.25
tmp13 = tmp11 * tmp12
tl.store(out_ptr0 + x6, tmp13, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 3, 3), (36, 9, 3, 1))
buf1 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_div_0[grid(64)](buf0, primals_2, buf1, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf0
del primals_2
return buf1, primals_1, primals_3
class MyConvo2d(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True,
stride=1, bias=True):
super(MyConvo2d, self).__init__()
self.he_init = he_init
self.padding = int((kernel_size - 1) / 2)
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride=1,
padding=self.padding, bias=bias)
def forward(self, input):
output = self.conv(input)
return output
class ConvMeanPoolNew(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True):
super(ConvMeanPoolNew, self).__init__()
self.he_init = he_init
self.conv = MyConvo2d(input_dim, output_dim, kernel_size, he_init=
self.he_init)
def forward(self, input_0):
primals_1 = self.conv.conv.weight
primals_2 = self.conv.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
justaboutlola/improved-wgan-pytorch
|
ConvMeanPool
| false
| 15,754
|
[
"MIT"
] | 412
|
5bb0b729809152d9129ef72a9dd28b3ff83021a2
|
https://github.com/justaboutlola/improved-wgan-pytorch/tree/5bb0b729809152d9129ef72a9dd28b3ff83021a2
|
SelfAttention
|
import torch
from torch import nn
class SelfAttention(nn.Module):
"""Self attention layer, cited from https://github.com/heykeetae/Self-Attention-GAN/blob/master/sagan_models.py"""
def __init__(self, in_dim, activation='relu', k=2):
super().__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=max(
in_dim // k, 1), kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=max(
in_dim // k, 1), kernel_size=1)
self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim,
kernel_size=1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
"""
inputs :
x : input feature maps( B X C X W X H)
returns :
out : self attention value + input feature
attention: B X N X N (N is Width*Height)
"""
m_batchsize, C, width, height = x.size()
proj_query = self.query_conv(x).view(m_batchsize, -1, width * height
).permute(0, 2, 1)
proj_key = self.key_conv(x).view(m_batchsize, -1, width * height)
energy = torch.bmm(proj_query, proj_key)
attention = self.softmax(energy)
proj_value = self.value_conv(x).view(m_batchsize, -1, width * height)
out = torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(m_batchsize, C, width, height)
out = self.gamma * out + x
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
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_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 128
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 2
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_per_fused__softmax_1(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK:
tl.constexpr):
xnumel = 64
RBLOCK: tl.constexpr = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp3 = tl.where(xmask, tmp1, float('-inf'))
tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
tmp5 = tmp0 - tmp4
tmp6 = tl_math.exp(tmp5)
tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
tmp9 = tl.where(xmask, tmp7, 0)
tmp10 = tl.sum(tmp9, 1)[:, None]
tmp11 = tmp6 / tmp10
tl.store(out_ptr2 + (r1 + 16 * x0), tmp11, xmask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_add_mul_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK])
tmp2 = tl.load(in_ptr1 + x0, xmask)
tmp4 = tl.load(in_ptr2 + x0, xmask)
tmp3 = tmp1 * tmp2
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, primals_8) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_3, (2,), (1,))
assert_size_stride(primals_4, (2, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (2,), (1,))
assert_size_stride(primals_6, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (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, 2, 4, 4), (32, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(128)](buf1, primals_3, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(primals_1, primals_4, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 2, 4, 4), (32, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(128)](buf3, primals_5, 128,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
buf4 = empty_strided_cuda((4, 16, 16), (256, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf1, (4, 16, 2), (32, 1, 16),
0), reinterpret_tensor(buf3, (4, 2, 16), (32, 16, 1), 0), out=buf4)
buf7 = empty_strided_cuda((4, 16, 16), (256, 16, 1), torch.float32)
triton_per_fused__softmax_1[grid(64)](buf4, buf7, 64, 16, XBLOCK=1,
num_warps=2, num_stages=1)
del buf4
buf8 = extern_kernels.convolution(primals_1, primals_6, stride=(1,
1), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 4, 4, 4), (64, 16, 4, 1))
buf9 = buf8
del buf8
triton_poi_fused_convolution_2[grid(256)](buf9, primals_7, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_7
buf10 = empty_strided_cuda((4, 4, 16), (64, 16, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf9, (4, 4, 16), (64, 16, 1),
0), reinterpret_tensor(buf7, (4, 16, 16), (256, 1, 16), 0), out
=buf10)
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_3[grid(256)](primals_8, buf10, primals_1,
buf11, 256, XBLOCK=128, num_warps=4, num_stages=1)
return (buf11, primals_1, primals_2, primals_4, primals_6, primals_8,
buf7, buf10, reinterpret_tensor(buf9, (4, 16, 4), (64, 1, 16), 0),
reinterpret_tensor(buf1, (4, 2, 16), (32, 16, 1), 0),
reinterpret_tensor(buf3, (4, 16, 2), (32, 1, 16), 0))
class SelfAttentionNew(nn.Module):
"""Self attention layer, cited from https://github.com/heykeetae/Self-Attention-GAN/blob/master/sagan_models.py"""
def __init__(self, in_dim, activation='relu', k=2):
super().__init__()
self.chanel_in = in_dim
self.activation = activation
self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=max(
in_dim // k, 1), kernel_size=1)
self.key_conv = nn.Conv2d(in_channels=in_dim, out_channels=max(
in_dim // k, 1), kernel_size=1)
self.value_conv = nn.Conv2d(in_channels=in_dim, out_channels=in_dim,
kernel_size=1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, input_0):
primals_8 = self.gamma
primals_2 = self.query_conv.weight
primals_3 = self.query_conv.bias
primals_4 = self.key_conv.weight
primals_5 = self.key_conv.bias
primals_6 = self.value_conv.weight
primals_7 = self.value_conv.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
jscarlson/zi2zi-pytorch
|
SelfAttention
| false
| 15,755
|
[
"Apache-2.0"
] | 81
|
3409165b304ccf1d5a5c2329a9f0f0897b3495dc
|
https://github.com/jscarlson/zi2zi-pytorch/tree/3409165b304ccf1d5a5c2329a9f0f0897b3495dc
|
UpSampleConv
|
import torch
from torch import nn
class MyConvo2d(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True,
stride=1, bias=True):
super(MyConvo2d, self).__init__()
self.he_init = he_init
self.padding = int((kernel_size - 1) / 2)
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride=1,
padding=self.padding, bias=bias)
def forward(self, input):
output = self.conv(input)
return output
class DepthToSpace(nn.Module):
def __init__(self, block_size):
super(DepthToSpace, self).__init__()
self.block_size = block_size
self.block_size_sq = block_size * block_size
def forward(self, input):
output = input.permute(0, 2, 3, 1)
batch_size, input_height, input_width, input_depth = output.size()
output_depth = int(input_depth / self.block_size_sq)
output_width = int(input_width * self.block_size)
output_height = int(input_height * self.block_size)
t_1 = output.reshape(batch_size, input_height, input_width, self.
block_size_sq, output_depth)
spl = t_1.split(self.block_size, 3)
stacks = [t_t.reshape(batch_size, input_height, output_width,
output_depth) for t_t in spl]
output = torch.stack(stacks, 0).transpose(0, 1).permute(0, 2, 1, 3, 4
).reshape(batch_size, output_height, output_width, output_depth)
output = output.permute(0, 3, 1, 2)
return output
class UpSampleConv(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True,
bias=True):
super(UpSampleConv, self).__init__()
self.he_init = he_init
self.conv = MyConvo2d(input_dim, output_dim, kernel_size, he_init=
self.he_init, bias=bias)
self.depth_to_space = DepthToSpace(2)
def forward(self, input):
output = input
output = torch.cat((output, output, output, output), 1)
output = self.depth_to_space(output)
output = self.conv(output)
return output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_dim': 4, 'output_dim': 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 import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 1024
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex // 32 % 2
x4 = xindex // 256
x0 = xindex % 4
x1 = xindex // 4 % 8
x3 = xindex // 64 % 4
x6 = xindex
tmp0 = x4 + 4 * x2
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x3 + 16 * x0 + 64 * (x4 + 4 * x2) + x1 //
2), tmp4 & xmask, eviction_policy='evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr0 + (4 * x3 + 16 * x0 + 64 * (-4 + x4 + 4 * x2) +
x1 // 2), tmp6 & xmask, eviction_policy='evict_last', other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x6, tmp10, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 16
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 784
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 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, 4, 2, 8, 4), (256, 64, 32, 4, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_clone_0[grid(1024)](primals_1, buf0, 1024, XBLOCK=
128, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
triton_poi_fused_convolution_1[grid(16, 16)](primals_2, buf1, 16,
16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
buf2 = extern_kernels.convolution(reinterpret_tensor(buf0, (4, 4, 8,
8), (256, 1, 32, 4), 0), buf1, stride=(1, 1), padding=(1, 1),
dilation=(1, 1), transposed=False, output_padding=(0, 0),
groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 7, 7), (196, 1, 28, 4))
del buf1
buf3 = buf2
del buf2
triton_poi_fused_convolution_2[grid(784)](buf3, primals_3, 784,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_3
return buf3, primals_2, reinterpret_tensor(buf0, (4, 4, 8, 8), (256, 1,
32, 4), 0)
class MyConvo2d(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True,
stride=1, bias=True):
super(MyConvo2d, self).__init__()
self.he_init = he_init
self.padding = int((kernel_size - 1) / 2)
self.conv = nn.Conv2d(input_dim, output_dim, kernel_size, stride=1,
padding=self.padding, bias=bias)
def forward(self, input):
output = self.conv(input)
return output
class DepthToSpace(nn.Module):
def __init__(self, block_size):
super(DepthToSpace, self).__init__()
self.block_size = block_size
self.block_size_sq = block_size * block_size
def forward(self, input):
output = input.permute(0, 2, 3, 1)
batch_size, input_height, input_width, input_depth = output.size()
output_depth = int(input_depth / self.block_size_sq)
output_width = int(input_width * self.block_size)
output_height = int(input_height * self.block_size)
t_1 = output.reshape(batch_size, input_height, input_width, self.
block_size_sq, output_depth)
spl = t_1.split(self.block_size, 3)
stacks = [t_t.reshape(batch_size, input_height, output_width,
output_depth) for t_t in spl]
output = torch.stack(stacks, 0).transpose(0, 1).permute(0, 2, 1, 3, 4
).reshape(batch_size, output_height, output_width, output_depth)
output = output.permute(0, 3, 1, 2)
return output
class UpSampleConvNew(nn.Module):
def __init__(self, input_dim, output_dim, kernel_size, he_init=True,
bias=True):
super(UpSampleConvNew, self).__init__()
self.he_init = he_init
self.conv = MyConvo2d(input_dim, output_dim, kernel_size, he_init=
self.he_init, bias=bias)
self.depth_to_space = DepthToSpace(2)
def forward(self, input_0):
primals_1 = self.conv.conv.weight
primals_3 = self.conv.conv.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
justaboutlola/improved-wgan-pytorch
|
UpSampleConv
| false
| 15,756
|
[
"MIT"
] | 412
|
5bb0b729809152d9129ef72a9dd28b3ff83021a2
|
https://github.com/justaboutlola/improved-wgan-pytorch/tree/5bb0b729809152d9129ef72a9dd28b3ff83021a2
|
ExtractTensorPatches
|
import torch
from typing import Optional
from typing import Tuple
import torch.nn as nn
import torch.nn.functional as F
from typing import Union
from torch.nn.modules.utils import _pair
def _extract_tensor_patchesnd(input: 'torch.Tensor', window_sizes:
'Tuple[int, ...]', strides: 'Tuple[int, ...]') ->torch.Tensor:
batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
input = input.unfold(dim, patch_size, stride)
input = input.permute(0, *dims, 1, *[(dim + len(dims)) for dim in dims]
).contiguous()
return input.view(batch_size, -1, num_channels, *window_sizes)
def extract_tensor_patches(input: 'torch.Tensor', window_size:
'Union[int, Tuple[int, int]]', stride: 'Union[int, Tuple[int, int]]'=1,
padding: 'Union[int, Tuple[int, int]]'=0) ->torch.Tensor:
"""Function that extract patches from tensors and stack them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
"""
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))
if padding:
pad_vert, pad_horz = _pair(padding)
input = F.pad(input, [pad_horz, pad_horz, pad_vert, pad_vert])
return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
class ExtractTensorPatches(nn.Module):
"""Module that extract patches from tensors and stack them.
In the simplest case, the output value of the operator with input size
:math:`(B, C, H, W)` is :math:`(B, N, C, H_{out}, W_{out})`.
where
- :math:`B` is the batch size.
- :math:`N` denotes the total number of extracted patches stacked in
- :math:`C` denotes the number of input channels.
- :math:`H`, :math:`W` the input height and width of the input in pixels.
- :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size
defined in the function signature.
left-right and top-bottom order.
* :attr:`window_size` is the size of the sliding window and controls the
shape of the output tensor and defines the shape of the output patch.
* :attr:`stride` controls the stride to apply to the sliding window and
regulates the overlapping between the extracted patches.
* :attr:`padding` controls the amount of implicit zeros-paddings on both
sizes at each dimension.
The parameters :attr:`window_size`, :attr:`stride` and :attr:`padding` can
be either:
- a single ``int`` -- in which case the same value is used for the
height and width dimension.
- a ``tuple`` of two ints -- in which case, the first `int` is used for
the height dimension, and the second `int` for the width dimension.
Args:
window_size: the size of the sliding window and the output patch size.
stride: stride of the sliding window.
padding: Zero-padding added to both side of the input.
Shape:
- Input: :math:`(B, C, H, W)`
- Output: :math:`(B, N, C, H_{out}, W_{out})`
Returns:
the tensor with the extracted patches.
Examples:
>>> input = torch.arange(9.).view(1, 1, 3, 3)
>>> patches = extract_tensor_patches(input, (2, 3))
>>> input
tensor([[[[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]]]])
>>> patches[:, -1]
tensor([[[[3., 4., 5.],
[6., 7., 8.]]]])
"""
def __init__(self, window_size: 'Union[int, Tuple[int, int]]', stride:
'Optional[Union[int, Tuple[int, int]]]'=1, padding:
'Optional[Union[int, Tuple[int, int]]]'=0) ->None:
super(ExtractTensorPatches, self).__init__()
self.window_size: 'Tuple[int, int]' = _pair(window_size)
self.stride: 'Tuple[int, int]' = _pair(stride)
self.padding: 'Tuple[int, int]' = _pair(padding)
def forward(self, input: 'torch.Tensor') ->torch.Tensor:
return extract_tensor_patches(input, self.window_size, stride=self.
stride, padding=self.padding)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'window_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 typing import Optional
from typing import Tuple
import torch.nn as nn
import torch.nn.functional as F
from typing import Union
from torch.nn.modules.utils import _pair
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_constant_pad_nd_view_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
x0 = xindex
tmp0 = tl.load(in_ptr0 + x0, xmask)
tl.store(in_out_ptr0 + x0, tmp0, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
buf1 = reinterpret_tensor(buf0, (4, 1, 4, 4, 4), (64, 16, 16, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_constant_pad_nd_view_0[grid(256)](buf1, arg0_1,
256, XBLOCK=128, num_warps=4, num_stages=1)
del arg0_1
return buf1,
def _extract_tensor_patchesnd(input: 'torch.Tensor', window_sizes:
'Tuple[int, ...]', strides: 'Tuple[int, ...]') ->torch.Tensor:
batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
input = input.unfold(dim, patch_size, stride)
input = input.permute(0, *dims, 1, *[(dim + len(dims)) for dim in dims]
).contiguous()
return input.view(batch_size, -1, num_channels, *window_sizes)
def extract_tensor_patches(input: 'torch.Tensor', window_size:
'Union[int, Tuple[int, int]]', stride: 'Union[int, Tuple[int, int]]'=1,
padding: 'Union[int, Tuple[int, int]]'=0) ->torch.Tensor:
"""Function that extract patches from tensors and stack them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
"""
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))
if padding:
pad_vert, pad_horz = _pair(padding)
input = F.pad(input, [pad_horz, pad_horz, pad_vert, pad_vert])
return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
class ExtractTensorPatchesNew(nn.Module):
"""Module that extract patches from tensors and stack them.
In the simplest case, the output value of the operator with input size
:math:`(B, C, H, W)` is :math:`(B, N, C, H_{out}, W_{out})`.
where
- :math:`B` is the batch size.
- :math:`N` denotes the total number of extracted patches stacked in
- :math:`C` denotes the number of input channels.
- :math:`H`, :math:`W` the input height and width of the input in pixels.
- :math:`H_{out}`, :math:`W_{out}` denote to denote to the patch size
defined in the function signature.
left-right and top-bottom order.
* :attr:`window_size` is the size of the sliding window and controls the
shape of the output tensor and defines the shape of the output patch.
* :attr:`stride` controls the stride to apply to the sliding window and
regulates the overlapping between the extracted patches.
* :attr:`padding` controls the amount of implicit zeros-paddings on both
sizes at each dimension.
The parameters :attr:`window_size`, :attr:`stride` and :attr:`padding` can
be either:
- a single ``int`` -- in which case the same value is used for the
height and width dimension.
- a ``tuple`` of two ints -- in which case, the first `int` is used for
the height dimension, and the second `int` for the width dimension.
Args:
window_size: the size of the sliding window and the output patch size.
stride: stride of the sliding window.
padding: Zero-padding added to both side of the input.
Shape:
- Input: :math:`(B, C, H, W)`
- Output: :math:`(B, N, C, H_{out}, W_{out})`
Returns:
the tensor with the extracted patches.
Examples:
>>> input = torch.arange(9.).view(1, 1, 3, 3)
>>> patches = extract_tensor_patches(input, (2, 3))
>>> input
tensor([[[[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]]]])
>>> patches[:, -1]
tensor([[[[3., 4., 5.],
[6., 7., 8.]]]])
"""
def __init__(self, window_size: 'Union[int, Tuple[int, int]]', stride:
'Optional[Union[int, Tuple[int, int]]]'=1, padding:
'Optional[Union[int, Tuple[int, int]]]'=0) ->None:
super(ExtractTensorPatchesNew, self).__init__()
self.window_size: 'Tuple[int, int]' = _pair(window_size)
self.stride: 'Tuple[int, int]' = _pair(stride)
self.padding: 'Tuple[int, int]' = _pair(padding)
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
justanhduc/kornia
|
ExtractTensorPatches
| false
| 15,757
|
[
"ECL-2.0",
"Apache-2.0"
] | 51
|
c14081292dfb2491fad50ba10e27491cad8cb3e3
|
https://github.com/justanhduc/kornia/tree/c14081292dfb2491fad50ba10e27491cad8cb3e3
|
Grad_hyper
|
import torch
import torch.nn.functional
class Grad_hyper(torch.nn.Module):
"""
N-D gradient loss.
"""
def __init__(self, penalty='l1'):
super(Grad_hyper, self).__init__()
self.penalty = penalty
def forward(self, y_pred, wts):
dy = torch.abs(y_pred[:, :, 1:, :] - y_pred[:, :, :-1, :])
dx = torch.abs(y_pred[:, :, :, 1:] - y_pred[:, :, :, :-1])
if self.penalty == 'l2':
dy = dy * dy
dx = dx * dx
d = torch.mean(dx, dim=[1, 2, 3]) + torch.mean(dy, dim=[1, 2, 3])
grad = d / 2.0 * wts
None
return torch.mean(grad)
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.functional
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_mean_sub_0(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 48
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, :]
rmask = rindex < rnumel
r1 = rindex % 3
r2 = rindex // 3
x0 = xindex
tmp0 = tl.load(in_ptr0 + (1 + r1 + 4 * r2 + 64 * x0), rmask & xmask,
other=0.0)
tmp1 = tl.load(in_ptr0 + (r1 + 4 * r2 + 64 * x0), rmask & xmask, other=0.0)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(rmask & xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_per_fused_abs_mean_sub_1(in_ptr0, out_ptr0, xnumel, rnumel,
XBLOCK: tl.constexpr):
xnumel = 4
rnumel = 48
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, :]
rmask = rindex < rnumel
r1 = rindex % 12
r2 = rindex // 12
x0 = xindex
tmp0 = tl.load(in_ptr0 + (4 + r1 + 16 * r2 + 64 * x0), rmask & xmask,
other=0.0)
tmp1 = tl.load(in_ptr0 + (r1 + 16 * r2 + 64 * x0), rmask & xmask, other=0.0
)
tmp2 = tmp0 - tmp1
tmp3 = tl_math.abs(tmp2)
tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp6 = tl.where(rmask & xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tl.store(out_ptr0 + x0, tmp7, xmask)
@triton.jit
def triton_per_fused_abs_add_div_mean_mul_sub_2(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r0 = rindex % 4
r2 = rindex
tmp0 = tl.load(in_ptr0 + r0, None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last')
tmp8 = tl.load(in_ptr2 + r2, None)
tmp1 = 48.0
tmp2 = tmp0 / tmp1
tmp4 = tmp3 / tmp1
tmp5 = tmp2 + tmp4
tmp6 = 0.5
tmp7 = tmp5 * tmp6
tmp9 = tmp7 * tmp8
tmp10 = tl.broadcast_to(tmp9, [RBLOCK])
tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0))
tmp13 = 256.0
tmp14 = tmp12 / tmp13
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp14, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4,), (1,), torch.float32)
get_raw_stream(0)
triton_per_fused_abs_mean_sub_0[grid(4)](arg0_1, buf0, 4, 48,
XBLOCK=1, num_warps=2, num_stages=1)
buf1 = empty_strided_cuda((4,), (1,), torch.float32)
triton_per_fused_abs_mean_sub_1[grid(4)](arg0_1, buf1, 4, 48,
XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
buf2 = empty_strided_cuda((), (), torch.float32)
buf3 = buf2
del buf2
triton_per_fused_abs_add_div_mean_mul_sub_2[grid(1)](buf3, buf0,
buf1, arg1_1, 1, 256, num_warps=2, num_stages=1)
del arg1_1
del buf0
del buf1
return buf3,
class Grad_hyperNew(torch.nn.Module):
"""
N-D gradient loss.
"""
def __init__(self, penalty='l1'):
super(Grad_hyperNew, self).__init__()
self.penalty = penalty
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
Grad_hyper
| false
| 15,758
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
PCC
|
import torch
import torch.nn.functional
class PCC(torch.nn.Module):
def __init__(self):
super(PCC, self).__init__()
def pcc(self, y_true, y_pred):
A_bar = torch.mean(y_pred, dim=[1, 2, 3, 4], keepdim=True)
B_bar = torch.mean(y_true, dim=[1, 2, 3, 4], keepdim=True)
top = torch.mean((y_pred - A_bar) * (y_true - B_bar), dim=[1, 2, 3,
4], keepdim=True)
bottom = torch.sqrt(torch.mean((y_pred - A_bar) ** 2, dim=[1, 2, 3,
4], keepdim=True) * torch.mean((y_true - B_bar) ** 2, dim=[1, 2,
3, 4], keepdim=True))
return torch.mean(top / bottom)
def forward(self, I, J):
return 1 - self.pcc(I, J)
def get_inputs():
return [torch.rand([4, 4, 4, 4, 4]), torch.rand([4, 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.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mean_mul_pow_sub_0(in_ptr0, in_ptr1, out_ptr2,
out_ptr3, out_ptr4, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 256 * x0), None)
tmp4 = tl.load(in_ptr1 + (r1 + 256 * x0), None)
tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
tmp3 = triton_helpers.promote_to_tensor(tl.sum(tmp1, 0))
tmp5 = tl.broadcast_to(tmp4, [RBLOCK])
tmp7 = triton_helpers.promote_to_tensor(tl.sum(tmp5, 0))
tmp8 = 256.0
tmp9 = tmp3 / tmp8
tmp10 = tmp0 - tmp9
tmp11 = tmp7 / tmp8
tmp12 = tmp4 - tmp11
tmp13 = tmp10 * tmp12
tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
tmp17 = tmp10 * tmp10
tmp18 = tl.broadcast_to(tmp17, [RBLOCK])
tmp20 = triton_helpers.promote_to_tensor(tl.sum(tmp18, 0))
tmp21 = tmp12 * tmp12
tmp22 = tl.broadcast_to(tmp21, [RBLOCK])
tmp24 = triton_helpers.promote_to_tensor(tl.sum(tmp22, 0))
tl.store(out_ptr2 + x0, tmp16, None)
tl.store(out_ptr3 + x0, tmp20, None)
tl.store(out_ptr4 + x0, tmp24, None)
@triton.jit
def triton_per_fused_div_mean_mul_pow_rsub_sqrt_sub_1(in_out_ptr0, in_ptr0,
in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 4
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex
tmp0 = tl.load(in_ptr0 + r0, None)
tmp3 = tl.load(in_ptr1 + r0, None)
tmp5 = tl.load(in_ptr2 + r0, None)
tmp1 = 256.0
tmp2 = tmp0 / tmp1
tmp4 = tmp3 / tmp1
tmp6 = tmp5 / tmp1
tmp7 = tmp4 * tmp6
tmp8 = libdevice.sqrt(tmp7)
tmp9 = tmp2 / tmp8
tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
tmp12 = tl.sum(tmp10, 1)[:, None]
tmp13 = 4.0
tmp14 = tmp12 / tmp13
tmp15 = 1.0
tmp16 = tmp15 - tmp14
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp16, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4, 4), (256, 64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf2 = empty_strided_cuda((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch.
float32)
buf3 = empty_strided_cuda((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch.
float32)
buf4 = empty_strided_cuda((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch.
float32)
get_raw_stream(0)
triton_per_fused_mean_mul_pow_sub_0[grid(4)](arg0_1, arg1_1, buf2,
buf3, buf4, 4, 256, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
buf5 = empty_strided_cuda((), (), torch.float32)
buf6 = buf5
del buf5
triton_per_fused_div_mean_mul_pow_rsub_sqrt_sub_1[grid(1)](buf6,
buf2, buf3, buf4, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
del buf2
del buf3
del buf4
return buf6,
class PCCNew(torch.nn.Module):
def __init__(self):
super(PCCNew, self).__init__()
def pcc(self, y_true, y_pred):
A_bar = torch.mean(y_pred, dim=[1, 2, 3, 4], keepdim=True)
B_bar = torch.mean(y_true, dim=[1, 2, 3, 4], keepdim=True)
top = torch.mean((y_pred - A_bar) * (y_true - B_bar), dim=[1, 2, 3,
4], keepdim=True)
bottom = torch.sqrt(torch.mean((y_pred - A_bar) ** 2, dim=[1, 2, 3,
4], keepdim=True) * torch.mean((y_true - B_bar) ** 2, dim=[1, 2,
3, 4], keepdim=True))
return torch.mean(top / bottom)
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
PCC
| false
| 15,760
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
outblock
|
import torch
import torch.nn as nn
from torch.distributions.normal import Normal
import torch.nn.functional
class outblock(nn.Module):
def __init__(self, in_ch, out_ch, stride=2, output_padding=1):
super(outblock, self).__init__()
self.upconv = nn.Conv3d(in_ch, out_ch, 3, padding=1, stride=stride)
self.upconv.weight = nn.Parameter(Normal(0, 1e-05).sample(self.
upconv.weight.shape))
self.upconv.bias = nn.Parameter(torch.zeros(self.upconv.bias.shape))
def forward(self, x):
x = self.upconv(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'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
from torch.distributions.normal import Normal
import torch.nn.functional
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 = 32
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 8
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, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_3, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_1, stride=(2, 2,
2), padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 2, 2, 2), (32, 8, 4, 2, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(32)](buf1, primals_2, 32,
XBLOCK=32, num_warps=1, num_stages=1)
del primals_2
return reinterpret_tensor(buf1, (4, 2, 2, 2), (8, 4, 2, 1), 0
), primals_1, reinterpret_tensor(primals_3, (1, 4, 4, 4, 4), (256,
64, 16, 4, 1), 0)
class outblockNew(nn.Module):
def __init__(self, in_ch, out_ch, stride=2, output_padding=1):
super(outblockNew, self).__init__()
self.upconv = nn.Conv3d(in_ch, out_ch, 3, padding=1, stride=stride)
self.upconv.weight = nn.Parameter(Normal(0, 1e-05).sample(self.
upconv.weight.shape))
self.upconv.bias = nn.Parameter(torch.zeros(self.upconv.bias.shape))
def forward(self, input_0):
primals_1 = self.upconv.weight
primals_2 = self.upconv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
outblock
| false
| 15,761
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
DeiTEmbeddings
|
from _paritybench_helpers import _mock_config
import collections
import torch
from torch import nn
import torch.utils.checkpoint
import collections.abc
def to_2tuple(x):
if isinstance(x, collections.abc.Iterable):
return x
return x, x
class PatchEmbeddings(nn.Module):
"""
Image to Patch Embedding.
"""
def __init__(self, image_size=224, patch_size=16, num_channels=3,
embed_dim=768):
super().__init__()
image_size = to_2tuple(image_size)
patch_size = to_2tuple(patch_size)
num_patches = image_size[1] // patch_size[1] * (image_size[0] //
patch_size[0])
self.image_size = image_size
self.patch_size = patch_size
self.num_patches = num_patches
self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=
patch_size, stride=patch_size)
def forward(self, pixel_values):
_batch_size, _num_channels, height, width = pixel_values.shape
if height != self.image_size[0] or width != self.image_size[1]:
raise ValueError(
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
)
x = self.projection(pixel_values).flatten(2).transpose(1, 2)
return x
class DeiTEmbeddings(nn.Module):
"""
Construct the CLS token, distillation token, position and patch embeddings.
"""
def __init__(self, config):
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
self.distillation_token = nn.Parameter(torch.zeros(1, 1, config.
hidden_size))
self.patch_embeddings = PatchEmbeddings(image_size=config.
image_size, patch_size=config.patch_size, num_channels=config.
num_channels, embed_dim=config.hidden_size)
num_patches = self.patch_embeddings.num_patches
self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches +
2, config.hidden_size))
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, pixel_values):
batch_size = pixel_values.shape[0]
embeddings = self.patch_embeddings(pixel_values)
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
distillation_tokens = self.distillation_token.expand(batch_size, -1, -1
)
embeddings = torch.cat((cls_tokens, distillation_tokens, embeddings
), dim=1)
embeddings = embeddings + self.position_embeddings
embeddings = self.dropout(embeddings)
return embeddings
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, image_size=4,
patch_size=4, num_channels=4, 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
import collections
from torch import nn
import torch.utils.checkpoint
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_poi_fused_add_cat_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4 % 3
x0 = xindex % 4
x2 = xindex // 12
x3 = xindex % 12
x4 = xindex
tmp21 = tl.load(in_ptr4 + x3, xmask, eviction_policy='evict_last')
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
tl.full([1], 3, tl.int64)
tmp14 = tl.load(in_ptr2 + (x0 + 4 * x2), tmp11 & xmask, eviction_policy
='evict_last', other=0.0)
tmp15 = tl.load(in_ptr3 + x0, tmp11 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp16 = tmp14 + tmp15
tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype)
tmp18 = tl.where(tmp11, tmp16, tmp17)
tmp19 = tl.where(tmp9, tmp10, tmp18)
tmp20 = tl.where(tmp4, tmp5, tmp19)
tmp22 = tmp20 + tmp21
tl.store(out_ptr0 + x4, tmp22, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (1, 1, 4), (4, 4, 1))
assert_size_stride(primals_5, (1, 1, 4), (4, 4, 1))
assert_size_stride(primals_6, (1, 3, 4), (12, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(4,
4), padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 1, 1), (4, 1, 1, 1))
buf1 = empty_strided_cuda((4, 3, 4), (12, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_cat_0[grid(48)](primals_4, primals_5, buf0,
primals_3, primals_6, buf1, 48, XBLOCK=64, num_warps=1,
num_stages=1)
del buf0
del primals_3
del primals_4
del primals_5
del primals_6
return buf1, primals_1, primals_2
def to_2tuple(x):
if isinstance(x, collections.abc.Iterable):
return x
return x, x
class PatchEmbeddings(nn.Module):
"""
Image to Patch Embedding.
"""
def __init__(self, image_size=224, patch_size=16, num_channels=3,
embed_dim=768):
super().__init__()
image_size = to_2tuple(image_size)
patch_size = to_2tuple(patch_size)
num_patches = image_size[1] // patch_size[1] * (image_size[0] //
patch_size[0])
self.image_size = image_size
self.patch_size = patch_size
self.num_patches = num_patches
self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=
patch_size, stride=patch_size)
def forward(self, pixel_values):
_batch_size, _num_channels, height, width = pixel_values.shape
if height != self.image_size[0] or width != self.image_size[1]:
raise ValueError(
f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
)
x = self.projection(pixel_values).flatten(2).transpose(1, 2)
return x
class DeiTEmbeddingsNew(nn.Module):
"""
Construct the CLS token, distillation token, position and patch embeddings.
"""
def __init__(self, config):
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
self.distillation_token = nn.Parameter(torch.zeros(1, 1, config.
hidden_size))
self.patch_embeddings = PatchEmbeddings(image_size=config.
image_size, patch_size=config.patch_size, num_channels=config.
num_channels, embed_dim=config.hidden_size)
num_patches = self.patch_embeddings.num_patches
self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches +
2, config.hidden_size))
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_0):
primals_4 = self.cls_token
primals_5 = self.distillation_token
primals_6 = self.position_embeddings
primals_1 = self.patch_embeddings.projection.weight
primals_3 = self.patch_embeddings.projection.bias
primals_2 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
DeiTEmbeddings
| false
| 15,762
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
GroupedLinearLayer
|
import torch
from torch import nn
import torch.utils.checkpoint
class GroupedLinearLayer(nn.Module):
def __init__(self, input_size, output_size, num_groups):
super().__init__()
self.input_size = input_size
self.output_size = output_size
self.num_groups = num_groups
self.group_in_dim = self.input_size // self.num_groups
self.group_out_dim = self.output_size // self.num_groups
self.weight = nn.Parameter(torch.empty(self.num_groups, self.
group_in_dim, self.group_out_dim))
self.bias = nn.Parameter(torch.empty(output_size))
def forward(self, hidden_states):
batch_size = list(hidden_states.size())[0]
x = torch.reshape(hidden_states, [-1, self.num_groups, self.
group_in_dim])
x = x.permute(1, 0, 2)
x = torch.matmul(x, self.weight)
x = x.permute(1, 0, 2)
x = torch.reshape(x, [batch_size, -1, self.output_size])
x = x + self.bias
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'input_size': 4, 'output_size': 4, 'num_groups': 1}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import 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, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = xindex % 4
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x2, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (1, 4, 4), (16, 4, 1))
assert_size_stride(primals_3, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((1, 64, 4), (256, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(primals_1, (1, 64, 4), (4, 4,
1), 0), primals_2, out=buf0)
del primals_2
buf1 = reinterpret_tensor(buf0, (4, 16, 4), (64, 4, 1), 0)
del buf0
get_raw_stream(0)
triton_poi_fused_add_0[grid(256)](buf1, primals_3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del primals_3
return buf1, reinterpret_tensor(primals_1, (1, 4, 64), (4, 1, 4), 0)
class GroupedLinearLayerNew(nn.Module):
def __init__(self, input_size, output_size, num_groups):
super().__init__()
self.input_size = input_size
self.output_size = output_size
self.num_groups = num_groups
self.group_in_dim = self.input_size // self.num_groups
self.group_out_dim = self.output_size // self.num_groups
self.weight = nn.Parameter(torch.empty(self.num_groups, self.
group_in_dim, self.group_out_dim))
self.bias = nn.Parameter(torch.empty(output_size))
def forward(self, input_0):
primals_2 = self.weight
primals_3 = self.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
GroupedLinearLayer
| false
| 15,763
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
ConvBlock
|
import torch
import torch.nn as nn
import torch.utils.data
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1):
super(ConvBlock, self).__init__()
self.Mconv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=
padding)
self.MPrelu = nn.PReLU(num_parameters=out_channels)
def forward(self, x):
x = self.Mconv(x)
x = self.MPrelu(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__prelu_kernel_convolution_0(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp6 = tmp5 * tmp2
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf1,
primals_2, primals_4, buf2, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_2
return buf2, primals_1, primals_3, primals_4, buf1
class ConvBlockNew(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1):
super(ConvBlockNew, self).__init__()
self.Mconv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=
padding)
self.MPrelu = nn.PReLU(num_parameters=out_channels)
def forward(self, input_0):
primals_1 = self.Mconv.weight
primals_2 = self.Mconv.bias
primals_4 = self.MPrelu.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
kacel33/ActionAI_PC
|
ConvBlock
| false
| 15,764
|
[
"MIT"
] | 1,311
|
a0528f49ea61cc07d7c1e9a3cd6846e5f50cfae7
|
https://github.com/kacel33/ActionAI_PC/tree/a0528f49ea61cc07d7c1e9a3cd6846e5f50cfae7
|
HubertFeatureProjection
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
import torch.utils.checkpoint
class HubertFeatureProjection(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.
layer_norm_eps)
self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
self.dropout = nn.Dropout(config.feat_proj_dropout)
def forward(self, hidden_states):
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.projection(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(conv_dim=[4, 4], layer_norm_eps=1,
hidden_size=4, feat_proj_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
from torch import 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_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 = 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_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)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = 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,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(64)](primals_3, buf0,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(256)](primals_3, buf0,
buf1, primals_1, primals_2, buf2, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del buf0
del buf1
del primals_1
del primals_2
buf3 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf3)
del primals_5
return reinterpret_tensor(buf3, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_3, reinterpret_tensor(buf2, (64, 4), (4, 1), 0), primals_4
class HubertFeatureProjectionNew(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.
layer_norm_eps)
self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
self.dropout = nn.Dropout(config.feat_proj_dropout)
def forward(self, input_0):
primals_1 = self.layer_norm.weight
primals_2 = self.layer_norm.bias
primals_4 = self.projection.weight
primals_5 = self.projection.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
HubertFeatureProjection
| false
| 15,765
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
MegatronBertOutput
|
from _paritybench_helpers import _mock_config
import torch
from torch import nn
import torch.utils.checkpoint
class MegatronBertOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
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)
return input_tensor + 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,
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 import 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_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 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.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_4, primals_2, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
del primals_4
return buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)
class MegatronBertOutputNew(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
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_3 = input_0
primals_4 = input_1
output = call([primals_1, primals_2, primals_3, primals_4])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
MegatronBertOutput
| false
| 15,766
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
IBertLMHead
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch import nn
import torch.utils.checkpoint
def gelu(x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class IBertLMHead(nn.Module):
"""I-BERT Head for masked language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size,
bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
self.decoder.bias = self.bias
def forward(self, features, **kwargs):
x = self.dense(features)
x = gelu(x)
x = self.layer_norm(x)
x = self.decoder(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, layer_norm_eps=1,
vocab_size=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import math
from torch import 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_mul_native_layer_norm_pow_tanh_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')
tmp14 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp36 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
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
tmp15 = tmp14 * tmp1
tmp16 = tmp14 * tmp14
tmp17 = tmp16 * tmp14
tmp18 = tmp17 * tmp5
tmp19 = tmp14 + tmp18
tmp20 = tmp19 * tmp8
tmp21 = libdevice.tanh(tmp20)
tmp22 = tmp21 + tmp11
tmp23 = tmp15 * tmp22
tmp24 = tmp13 + tmp23
tmp26 = tmp25 * tmp1
tmp27 = tmp25 * tmp25
tmp28 = tmp27 * tmp25
tmp29 = tmp28 * tmp5
tmp30 = tmp25 + tmp29
tmp31 = tmp30 * tmp8
tmp32 = libdevice.tanh(tmp31)
tmp33 = tmp32 + tmp11
tmp34 = tmp26 * tmp33
tmp35 = tmp24 + tmp34
tmp37 = tmp36 * tmp1
tmp38 = tmp36 * tmp36
tmp39 = tmp38 * tmp36
tmp40 = tmp39 * tmp5
tmp41 = tmp36 + tmp40
tmp42 = tmp41 * tmp8
tmp43 = libdevice.tanh(tmp42)
tmp44 = tmp43 + tmp11
tmp45 = tmp37 * tmp44
tmp46 = tmp35 + tmp45
tmp47 = 4.0
tmp48 = tmp46 / tmp47
tmp49 = tmp13 - tmp48
tmp50 = tmp49 * tmp49
tmp51 = tmp23 - tmp48
tmp52 = tmp51 * tmp51
tmp53 = tmp50 + tmp52
tmp54 = tmp34 - tmp48
tmp55 = tmp54 * tmp54
tmp56 = tmp53 + tmp55
tmp57 = tmp45 - tmp48
tmp58 = tmp57 * tmp57
tmp59 = tmp56 + tmp58
tmp60 = tmp59 / tmp47
tl.store(out_ptr0 + x0, tmp48, xmask)
tl.store(out_ptr1 + x0, tmp60, xmask)
@triton.jit
def triton_poi_fused_add_mul_native_layer_norm_pow_tanh_1(in_ptr0, in_ptr1,
in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
x0 = xindex % 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp14 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp16 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
tmp20 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
tmp22 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
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
tmp15 = tmp13 - tmp14
tmp17 = tmp16 + tmp11
tmp18 = libdevice.rsqrt(tmp17)
tmp19 = tmp15 * tmp18
tmp21 = tmp19 * tmp20
tmp23 = tmp21 + tmp22
tl.store(out_ptr0 + x2, tmp23, 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,), (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.addmm(primals_2, reinterpret_tensor(primals_3, (64,
4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0
), alpha=1, beta=1, out=buf0)
del primals_1
del primals_2
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
buf2 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_native_layer_norm_pow_tanh_0[grid(64)](buf0,
buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_add_mul_native_layer_norm_pow_tanh_1[grid(256)](buf0,
buf1, buf2, primals_4, primals_5, buf3, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf1
del buf2
del primals_5
buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), (
4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf4)
del primals_7
return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0
), primals_4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0
), buf0, reinterpret_tensor(buf3, (64, 4), (4, 1), 0), primals_6
def gelu(x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 *
torch.pow(x, 3))))
class IBertLMHeadNew(nn.Module):
"""I-BERT Head for masked language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.decoder = nn.Linear(config.hidden_size, config.vocab_size,
bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
self.decoder.bias = self.bias
def forward(self, input_0):
primals_2 = self.bias
primals_1 = self.dense.weight
primals_4 = self.dense.bias
primals_5 = self.layer_norm.weight
primals_7 = self.layer_norm.bias
primals_6 = self.decoder.weight
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
IBertLMHead
| false
| 15,767
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
Conv3d_wd
|
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.functional
class Conv3d_wd(nn.Conv3d):
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1,
1), padding=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=False):
super(Conv3d_wd, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, dilation, groups, bias)
def forward(self, x):
weight = self.weight
weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True
).mean(dim=3, keepdim=True).mean(dim=4, keepdim=True)
weight = weight - weight_mean
std = torch.sqrt(torch.var(weight.view(weight.size(0), -1), dim=1) +
1e-12).view(-1, 1, 1, 1, 1)
weight = weight / std.expand_as(weight)
return F.conv3d(x, 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._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_mean_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 256 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (64 + x0 + 256 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (128 + x0 + 256 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (192 + x0 + 256 * x1), xmask)
tmp9 = tl.load(in_ptr0 + (16 + x0 + 256 * x1), xmask)
tmp10 = tl.load(in_ptr0 + (80 + x0 + 256 * x1), xmask)
tmp12 = tl.load(in_ptr0 + (144 + x0 + 256 * x1), xmask)
tmp14 = tl.load(in_ptr0 + (208 + x0 + 256 * x1), xmask)
tmp18 = tl.load(in_ptr0 + (32 + x0 + 256 * x1), xmask)
tmp19 = tl.load(in_ptr0 + (96 + x0 + 256 * x1), xmask)
tmp21 = tl.load(in_ptr0 + (160 + x0 + 256 * x1), xmask)
tmp23 = tl.load(in_ptr0 + (224 + x0 + 256 * x1), xmask)
tmp27 = tl.load(in_ptr0 + (48 + x0 + 256 * x1), xmask)
tmp28 = tl.load(in_ptr0 + (112 + x0 + 256 * x1), xmask)
tmp30 = tl.load(in_ptr0 + (176 + x0 + 256 * x1), xmask)
tmp32 = tl.load(in_ptr0 + (240 + x0 + 256 * x1), xmask)
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 + x2, tmp36, xmask)
@triton.jit
def triton_per_fused_add_div_mean_sqrt_sub_var_1(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, out_ptr1, xnumel, rnumel):
XBLOCK: tl.constexpr = 1
RBLOCK: tl.constexpr = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = tl.full([1], xoffset, tl.int32)
tl.full([RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[:]
tl.full([RBLOCK], True, tl.int1)
x0 = xindex
r1 = rindex
tmp0 = tl.load(in_ptr0 + 16 * x0, None, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr0 + (4 + 16 * x0), None, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (8 + 16 * x0), None, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr0 + (12 + 16 * x0), None, eviction_policy='evict_last'
)
tmp9 = tl.load(in_ptr0 + (1 + 16 * x0), None, eviction_policy='evict_last')
tmp10 = tl.load(in_ptr0 + (5 + 16 * x0), None, eviction_policy='evict_last'
)
tmp12 = tl.load(in_ptr0 + (9 + 16 * x0), None, eviction_policy='evict_last'
)
tmp14 = tl.load(in_ptr0 + (13 + 16 * x0), None, eviction_policy=
'evict_last')
tmp18 = tl.load(in_ptr0 + (2 + 16 * x0), None, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr0 + (6 + 16 * x0), None, eviction_policy='evict_last'
)
tmp21 = tl.load(in_ptr0 + (10 + 16 * x0), None, eviction_policy=
'evict_last')
tmp23 = tl.load(in_ptr0 + (14 + 16 * x0), None, eviction_policy=
'evict_last')
tmp27 = tl.load(in_ptr0 + (3 + 16 * x0), None, eviction_policy='evict_last'
)
tmp28 = tl.load(in_ptr0 + (7 + 16 * x0), None, eviction_policy='evict_last'
)
tmp30 = tl.load(in_ptr0 + (11 + 16 * x0), None, eviction_policy=
'evict_last')
tmp32 = tl.load(in_ptr0 + (15 + 16 * x0), None, eviction_policy=
'evict_last')
tmp37 = tl.load(in_ptr1 + (r1 + 256 * x0), None)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp11 = tmp9 + tmp10
tmp13 = tmp11 + tmp12
tmp15 = tmp13 + tmp14
tmp16 = tmp15 / tmp7
tmp17 = tmp8 + tmp16
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
tmp38 = tmp37 - tmp36
tmp39 = tl.broadcast_to(tmp38, [RBLOCK])
tmp41 = tl.broadcast_to(tmp39, [RBLOCK])
tmp43 = triton_helpers.promote_to_tensor(tl.sum(tmp41, 0))
tmp44 = tl.full([1], 256, tl.int32)
tmp45 = tmp44.to(tl.float32)
tmp46 = tmp43 / tmp45
tmp47 = tmp39 - tmp46
tmp48 = tmp47 * tmp47
tmp49 = tl.broadcast_to(tmp48, [RBLOCK])
tmp51 = triton_helpers.promote_to_tensor(tl.sum(tmp49, 0))
tmp52 = 255.0
tmp53 = tmp51 / tmp52
tmp54 = 1e-12
tmp55 = tmp53 + tmp54
tmp56 = libdevice.sqrt(tmp55)
tmp57 = tmp38 / tmp56
tl.store(out_ptr0 + x0, tmp36, None)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp56, None)
tl.store(out_ptr1 + (r1 + 256 * x0), tmp57, None)
def call(args):
primals_1, primals_2 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4, 4), (256, 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 = empty_strided_cuda((4, 1, 1, 4, 4), (16, 64, 64, 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((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch.
float32)
buf3 = empty_strided_cuda((4,), (1,), torch.float32)
buf5 = buf3
del buf3
buf6 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
triton_per_fused_add_div_mean_sqrt_sub_var_1[grid(4)](buf5, buf0,
primals_1, buf1, buf6, 4, 256, num_warps=2, num_stages=1)
del buf0
del buf1
buf7 = extern_kernels.convolution(reinterpret_tensor(primals_2, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), buf6, stride=(1, 1, 1),
padding=(0, 0, 0), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf7, (1, 4, 1, 1, 1), (4, 1, 1, 1, 1))
return reinterpret_tensor(buf7, (4, 1, 1, 1), (1, 1, 1, 1), 0
), primals_1, buf5, buf6, reinterpret_tensor(primals_2, (1, 4, 4, 4,
4), (256, 64, 16, 4, 1), 0)
class Conv3d_wdNew(nn.Conv3d):
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1,
1), padding=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=False):
super(Conv3d_wdNew, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, dilation, groups, bias)
def forward(self, input_0):
primals_1 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
Conv3d_wd
| false
| 15,768
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
MPNetSelfAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch import nn
import torch.utils.checkpoint
class MPNetSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads})'
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.q = nn.Linear(config.hidden_size, self.all_head_size)
self.k = nn.Linear(config.hidden_size, self.all_head_size)
self.v = nn.Linear(config.hidden_size, self.all_head_size)
self.o = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, attention_mask=None, head_mask=None,
position_bias=None, output_attentions=False, **kwargs):
q = self.q(hidden_states)
k = self.k(hidden_states)
v = self.v(hidden_states)
q = self.transpose_for_scores(q)
k = self.transpose_for_scores(k)
v = self.transpose_for_scores(v)
attention_scores = torch.matmul(q, k.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if position_bias is not None:
attention_scores += position_bias
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
c = torch.matmul(attention_probs, v)
c = c.permute(0, 2, 1, 3).contiguous()
new_c_shape = c.size()[:-2] + (self.all_head_size,)
c = c.view(*new_c_shape)
o = self.o(c)
outputs = (o, attention_probs) if output_attentions else (o,)
return outputs
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_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 import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import 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_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
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_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)
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), (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((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_3, (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_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_7, buf8, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_9, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_9
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf7, 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, 4), 0
), reinterpret_tensor(buf10, (16, 4), (4, 1), 0), primals_8
class MPNetSelfAttentionNew(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads})'
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.q = nn.Linear(config.hidden_size, self.all_head_size)
self.k = nn.Linear(config.hidden_size, self.all_head_size)
self.v = nn.Linear(config.hidden_size, self.all_head_size)
self.o = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, input_0):
primals_1 = self.q.weight
primals_2 = self.q.bias
primals_4 = self.k.weight
primals_5 = self.k.bias
primals_6 = self.v.weight
primals_7 = self.v.bias
primals_8 = self.o.weight
primals_9 = self.o.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]
|
jxhe/unify-parameter-efficient-tuning
|
MPNetSelfAttention
| false
| 15,769
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
NoNorm
|
import torch
from torch import nn
import torch.utils.checkpoint
class NoNorm(nn.Module):
def __init__(self, feat_size, eps=None):
super().__init__()
self.bias = nn.Parameter(torch.zeros(feat_size))
self.weight = nn.Parameter(torch.ones(feat_size))
def forward(self, input_tensor):
return input_tensor * self.weight + self.bias
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'feat_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 import nn
import torch.utils.checkpoint
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x0 = 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 + x0, 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 = args
args.clear()
assert_size_stride(primals_1, (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, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_mul_0[grid(256)](primals_2, primals_1,
primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_1
del primals_3
return buf0, primals_2
class NoNormNew(nn.Module):
def __init__(self, feat_size, eps=None):
super().__init__()
self.bias = nn.Parameter(torch.zeros(feat_size))
self.weight = nn.Parameter(torch.ones(feat_size))
def forward(self, input_0):
primals_1 = self.bias
primals_3 = self.weight
primals_2 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
NoNorm
| false
| 15,770
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
ConvDropoutLayerNorm
|
import torch
from torch import nn
import torch.utils.checkpoint
class SqueezeBertLayerNorm(nn.LayerNorm):
"""
This is a nn.LayerNorm subclass that accepts NCW data layout and performs normalization in the C dimension.
N = batch C = channels W = sequence length
"""
def __init__(self, hidden_size, eps=1e-12):
nn.LayerNorm.__init__(self, normalized_shape=hidden_size, eps=eps)
def forward(self, x):
x = x.permute(0, 2, 1)
x = nn.LayerNorm.forward(self, x)
return x.permute(0, 2, 1)
class ConvDropoutLayerNorm(nn.Module):
"""
ConvDropoutLayerNorm: Conv, Dropout, LayerNorm
"""
def __init__(self, cin, cout, groups, dropout_prob):
super().__init__()
self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout,
kernel_size=1, groups=groups)
self.layernorm = SqueezeBertLayerNorm(cout)
self.dropout = nn.Dropout(dropout_prob)
def forward(self, hidden_states, input_tensor):
x = self.conv1d(hidden_states)
x = self.dropout(x)
x = x + input_tensor
x = self.layernorm(x)
return x
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'cin': 4, 'cout': 4, 'groups': 1, '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.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_native_layer_norm_0(in_ptr0, in_ptr1, in_ptr2,
out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 4
y1 = yindex // 4
tmp0 = tl.load(in_ptr0 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + (x2 + 4 * y3), xmask & ymask, eviction_policy=
'evict_last')
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tl.store(out_ptr0 + (y0 + 4 * x2 + 16 * y1), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, out_ptr0, out_ptr1,
xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 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-12
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 = 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)
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, 1), (4, 1, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_4, (4, 4, 4), (16, 4, 1))
assert_size_stride(primals_5, (4,), (1,))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,),
padding=(0,), dilation=(1,), transposed=False, output_padding=(
0,), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4), (16, 4, 1))
buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(16, 4)](buf0, primals_2,
primals_4, buf1, 16, 4, XBLOCK=2, YBLOCK=16, num_warps=1,
num_stages=1)
del primals_2
del primals_4
buf2 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf3 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(16)](buf1, buf2, buf3, 16,
XBLOCK=16, num_warps=1, num_stages=1)
buf4 = buf0
del buf0
triton_poi_fused_native_layer_norm_2[grid(64)](buf1, buf2, buf3,
primals_5, primals_6, buf4, 64, XBLOCK=64, num_warps=1,
num_stages=1)
del buf2
del buf3
del primals_6
return reinterpret_tensor(buf4, (4, 4, 4), (16, 1, 4), 0
), primals_1, primals_3, primals_5, buf1
class SqueezeBertLayerNorm(nn.LayerNorm):
"""
This is a nn.LayerNorm subclass that accepts NCW data layout and performs normalization in the C dimension.
N = batch C = channels W = sequence length
"""
def __init__(self, hidden_size, eps=1e-12):
nn.LayerNorm.__init__(self, normalized_shape=hidden_size, eps=eps)
def forward(self, x):
x = x.permute(0, 2, 1)
x = nn.LayerNorm.forward(self, x)
return x.permute(0, 2, 1)
class ConvDropoutLayerNormNew(nn.Module):
"""
ConvDropoutLayerNorm: Conv, Dropout, LayerNorm
"""
def __init__(self, cin, cout, groups, dropout_prob):
super().__init__()
self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout,
kernel_size=1, groups=groups)
self.layernorm = SqueezeBertLayerNorm(cout)
self.dropout = nn.Dropout(dropout_prob)
def forward(self, input_0, input_1):
primals_1 = self.conv1d.weight
primals_2 = self.conv1d.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]
|
jxhe/unify-parameter-efficient-tuning
|
ConvDropoutLayerNorm
| false
| 15,771
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
DeiTAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
from typing import List
from typing import Tuple
from torch import nn
from typing import Set
import torch.utils.checkpoint
def find_pruneable_heads_and_indices(heads: 'List[int]', n_heads: 'int',
head_size: 'int', already_pruned_heads: 'Set[int]') ->Tuple[Set[int],
torch.LongTensor]:
"""
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
Args:
heads (:obj:`List[int]`): List of the indices of heads to prune.
n_heads (:obj:`int`): The number of heads in the model.
head_size (:obj:`int`): The size of each head.
already_pruned_heads (:obj:`Set[int]`): A set of already pruned heads.
Returns:
:obj:`Tuple[Set[int], torch.LongTensor]`: A tuple with the remaining heads and their corresponding indices.
"""
mask = torch.ones(n_heads, head_size)
heads = set(heads) - already_pruned_heads
for head in heads:
head = head - sum(1 if h < head else 0 for h in already_pruned_heads)
mask[head] = 0
mask = mask.view(-1).contiguous().eq(1)
index: 'torch.LongTensor' = torch.arange(len(mask))[mask].long()
return heads, index
def prune_linear_layer(layer: 'nn.Linear', index: 'torch.LongTensor', dim:
'int'=0) ->nn.Linear:
"""
Prune a linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`torch.nn.Linear`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to keep in the layer.
dim (:obj:`int`, `optional`, defaults to 0): The dimension on which to keep the indices.
Returns:
:obj:`torch.nn.Linear`: The pruned layer as a new layer with :obj:`requires_grad=True`.
"""
index = index
W = layer.weight.index_select(dim, index).clone().detach()
if layer.bias is not None:
if dim == 1:
b = layer.bias.clone().detach()
else:
b = layer.bias[index].clone().detach()
new_size = list(layer.weight.size())
new_size[dim] = len(index)
new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None
)
new_layer.weight.requires_grad = False
new_layer.weight.copy_(W.contiguous())
new_layer.weight.requires_grad = True
if layer.bias is not None:
new_layer.bias.requires_grad = False
new_layer.bias.copy_(b.contiguous())
new_layer.bias.requires_grad = True
return new_layer
class DeiTSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
f'The hidden size {config.hidden_size,} is not a multiple of the number of attention heads {config.num_attention_heads}.'
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, head_mask=None, output_attentions=False):
mixed_query_layer = self.query(hidden_states)
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
query_layer = self.transpose_for_scores(mixed_query_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (
context_layer,)
return outputs
class DeiTSelfOutput(nn.Module):
"""
The residual connection is defined in DeiTLayer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
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)
return hidden_states
class DeiTAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.attention = DeiTSelfAttention(config)
self.output = DeiTSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.
attention.num_attention_heads, self.attention.
attention_head_size, self.pruned_heads)
self.attention.query = prune_linear_layer(self.attention.query, index)
self.attention.key = prune_linear_layer(self.attention.key, index)
self.attention.value = prune_linear_layer(self.attention.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
self.attention.num_attention_heads = (self.attention.
num_attention_heads - len(heads))
self.attention.all_head_size = (self.attention.attention_head_size *
self.attention.num_attention_heads)
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, hidden_states, head_mask=None, output_attentions=False):
self_outputs = self.attention(hidden_states, head_mask,
output_attentions)
attention_output = self.output(self_outputs[0], hidden_states)
outputs = (attention_output,) + self_outputs[1:]
return outputs
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_dropout_prob=0.5, 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 import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import math
from typing import List
from typing import Tuple
from torch import nn
from typing import Set
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_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
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_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)
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), (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((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_3, (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_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_7, buf8, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (16, 4), (4, 1), 0)
del buf9
extern_kernels.addmm(primals_9, reinterpret_tensor(buf10, (16, 4),
(4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0),
alpha=1, beta=1, out=buf11)
del primals_9
return reinterpret_tensor(buf11, (4, 4, 4), (16, 4, 1), 0
), reinterpret_tensor(primals_3, (16, 4), (4, 1), 0
), buf7, 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, 4), 0
), reinterpret_tensor(buf10, (16, 4), (4, 1), 0), primals_8
def find_pruneable_heads_and_indices(heads: 'List[int]', n_heads: 'int',
head_size: 'int', already_pruned_heads: 'Set[int]') ->Tuple[Set[int],
torch.LongTensor]:
"""
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
Args:
heads (:obj:`List[int]`): List of the indices of heads to prune.
n_heads (:obj:`int`): The number of heads in the model.
head_size (:obj:`int`): The size of each head.
already_pruned_heads (:obj:`Set[int]`): A set of already pruned heads.
Returns:
:obj:`Tuple[Set[int], torch.LongTensor]`: A tuple with the remaining heads and their corresponding indices.
"""
mask = torch.ones(n_heads, head_size)
heads = set(heads) - already_pruned_heads
for head in heads:
head = head - sum(1 if h < head else 0 for h in already_pruned_heads)
mask[head] = 0
mask = mask.view(-1).contiguous().eq(1)
index: 'torch.LongTensor' = torch.arange(len(mask))[mask].long()
return heads, index
def prune_linear_layer(layer: 'nn.Linear', index: 'torch.LongTensor', dim:
'int'=0) ->nn.Linear:
"""
Prune a linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`torch.nn.Linear`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to keep in the layer.
dim (:obj:`int`, `optional`, defaults to 0): The dimension on which to keep the indices.
Returns:
:obj:`torch.nn.Linear`: The pruned layer as a new layer with :obj:`requires_grad=True`.
"""
index = index
W = layer.weight.index_select(dim, index).clone().detach()
if layer.bias is not None:
if dim == 1:
b = layer.bias.clone().detach()
else:
b = layer.bias[index].clone().detach()
new_size = list(layer.weight.size())
new_size[dim] = len(index)
new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None
)
new_layer.weight.requires_grad = False
new_layer.weight.copy_(W.contiguous())
new_layer.weight.requires_grad = True
if layer.bias is not None:
new_layer.bias.requires_grad = False
new_layer.bias.copy_(b.contiguous())
new_layer.bias.requires_grad = True
return new_layer
class DeiTSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
f'The hidden size {config.hidden_size,} is not a multiple of the number of attention heads {config.num_attention_heads}.'
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, head_mask=None, output_attentions=False):
mixed_query_layer = self.query(hidden_states)
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
query_layer = self.transpose_for_scores(mixed_query_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (
context_layer,)
return outputs
class DeiTSelfOutput(nn.Module):
"""
The residual connection is defined in DeiTLayer instead of here (as is the case with other models), due to the
layernorm applied before each block.
"""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
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)
return hidden_states
class DeiTAttentionNew(nn.Module):
def __init__(self, config):
super().__init__()
self.attention = DeiTSelfAttention(config)
self.output = DeiTSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.
attention.num_attention_heads, self.attention.
attention_head_size, self.pruned_heads)
self.attention.query = prune_linear_layer(self.attention.query, index)
self.attention.key = prune_linear_layer(self.attention.key, index)
self.attention.value = prune_linear_layer(self.attention.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
self.attention.num_attention_heads = (self.attention.
num_attention_heads - len(heads))
self.attention.all_head_size = (self.attention.attention_head_size *
self.attention.num_attention_heads)
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, input_0):
primals_1 = self.attention.query.weight
primals_2 = self.attention.query.bias
primals_4 = self.attention.key.weight
primals_5 = self.attention.key.bias
primals_6 = self.attention.value.weight
primals_7 = self.attention.value.bias
primals_8 = self.output.dense.weight
primals_9 = self.output.dense.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]
|
jxhe/unify-parameter-efficient-tuning
|
DeiTAttention
| false
| 15,772
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
MobileBertSelfAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
from torch import nn
import torch.utils.checkpoint
class MobileBertSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.true_hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.true_hidden_size, self.all_head_size)
self.key = nn.Linear(config.true_hidden_size, self.all_head_size)
self.value = nn.Linear(config.true_hidden_size if config.
use_bottleneck_attention else config.hidden_size, self.
all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, query_tensor, key_tensor, value_tensor,
attention_mask=None, head_mask=None, output_attentions=None):
mixed_query_layer = self.query(query_tensor)
mixed_key_layer = self.key(key_tensor)
mixed_value_layer = self.value(value_tensor)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.
all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (
context_layer,)
return outputs
def get_inputs():
return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4])
]
def get_init_inputs():
return [[], {'config': _mock_config(num_attention_heads=4,
true_hidden_size=4, use_bottleneck_attention=4,
attention_probs_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 import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
from torch import 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_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
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_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)
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), (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))
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_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_8, buf8, 16, 4,
XBLOCK=2, 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(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
del buf9
return reinterpret_tensor(buf10, (4, 4, 4), (16, 4, 1), 0
), 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(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, 4), 0)
class MobileBertSelfAttentionNew(nn.Module):
def __init__(self, config):
super().__init__()
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.true_hidden_size / config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.true_hidden_size, self.all_head_size)
self.key = nn.Linear(config.true_hidden_size, self.all_head_size)
self.value = nn.Linear(config.true_hidden_size if config.
use_bottleneck_attention else config.hidden_size, self.
all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, input_0, input_1, input_2):
primals_1 = self.query.weight
primals_2 = self.query.bias
primals_4 = self.key.weight
primals_5 = self.key.bias
primals_7 = self.value.weight
primals_8 = self.value.bias
primals_3 = input_0
primals_6 = input_1
primals_9 = input_2
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8, primals_9])
return output[0]
|
jxhe/unify-parameter-efficient-tuning
|
MobileBertSelfAttention
| false
| 15,773
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
Critic
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, action_input_layer=0, init_type='normal',
activation='leaky_relu', init_std=0.01):
super(Critic, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.activation = activation
self.layers = nn.ModuleList()
input_size = self.state_size + action_size + action_parameter_size
last_hidden_layer_size = input_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(input_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.output_layer = nn.Linear(last_hidden_layer_size, 1)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.output_layer.weight, std=init_std)
nn.init.zeros_(self.output_layer.bias)
def forward(self, state, actions, action_parameters):
x = torch.cat((state, actions, action_parameters), dim=1)
negative_slope = 0.01
num_hidden_layers = len(self.layers)
for i in range(0, num_hidden_layers):
if self.activation == 'relu':
x = F.relu(self.layers[i](x))
elif self.activation == 'leaky_relu':
x = F.leaky_relu(self.layers[i](x), negative_slope)
else:
raise ValueError('Unknown activation function ' + str(self.
activation))
Q = self.output_layer(x)
return Q
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {'state_size': 4, 'action_size': 4, 'action_parameter_size': 4}
]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 48
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex % 12
x1 = xindex // 12
x2 = xindex
tmp0 = x0
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask,
eviction_policy='evict_last', other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask,
eviction_policy='evict_last', other=0.0)
tmp15 = tl.where(tmp9, tmp10, tmp14)
tmp16 = tl.where(tmp4, tmp5, tmp15)
tl.store(out_ptr0 + x2, tmp16, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 1))
assert_size_stride(primals_2, (4, 4), (4, 1))
assert_size_stride(primals_3, (4, 4), (4, 1))
assert_size_stride(primals_4, (1, 12), (12, 1))
assert_size_stride(primals_5, (1,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3,
buf0, 48, XBLOCK=64, num_warps=1, num_stages=1)
del primals_1
del primals_2
del primals_3
buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
extern_kernels.addmm(primals_5, buf0, reinterpret_tensor(primals_4,
(12, 1), (1, 12), 0), alpha=1, beta=1, out=buf2)
del primals_4
del primals_5
return buf2, buf0
class CriticNew(nn.Module):
def __init__(self, state_size, action_size, action_parameter_size,
hidden_layers=None, action_input_layer=0, init_type='normal',
activation='leaky_relu', init_std=0.01):
super(CriticNew, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.action_parameter_size = action_parameter_size
self.activation = activation
self.layers = nn.ModuleList()
input_size = self.state_size + action_size + action_parameter_size
last_hidden_layer_size = input_size
if hidden_layers is not None:
nh = len(hidden_layers)
self.layers.append(nn.Linear(input_size, hidden_layers[0]))
for i in range(1, nh):
self.layers.append(nn.Linear(hidden_layers[i - 1],
hidden_layers[i]))
last_hidden_layer_size = hidden_layers[nh - 1]
self.output_layer = nn.Linear(last_hidden_layer_size, 1)
for i in range(0, len(self.layers)):
if init_type == 'kaiming':
nn.init.kaiming_normal_(self.layers[i].weight.data,
nonlinearity=self.activation)
elif init_type == 'normal':
nn.init.normal_(self.layers[i].weight.data, std=init_std)
else:
raise ValueError('Unknown init_type ' + str(init_type))
nn.init.zeros_(self.layers[i].bias.data)
nn.init.normal_(self.output_layer.weight, std=init_std)
nn.init.zeros_(self.output_layer.bias)
def forward(self, input_0, input_1, input_2):
primals_4 = self.output_layer.weight
primals_5 = self.output_layer.bias
primals_1 = input_0
primals_2 = input_1
primals_3 = input_2
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
jordiriu/MP-DQN
|
Critic
| false
| 15,774
|
[
"MIT"
] | 75
|
eec13eb9b4e2c0099649e0639f2a8b93d7d0d5be
|
https://github.com/jordiriu/MP-DQN/tree/eec13eb9b4e2c0099649e0639f2a8b93d7d0d5be
|
DistillationOrthogonalProjectionLoss
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
class DistillationOrthogonalProjectionLoss(nn.Module):
def __init__(self):
super(DistillationOrthogonalProjectionLoss, self).__init__()
@staticmethod
def forward(features, features_teacher):
features = F.normalize(features, p=2, dim=1)
features_teacher = F.normalize(features_teacher, p=2, dim=1)
dot_prod = torch.matmul(features, features.t())
dot_prod_teacher = torch.matmul(features_teacher, features_teacher.t())
tau = 1
loss = F.kl_div(dot_prod / tau, dot_prod_teacher / tau, reduction=
'sum', log_target=True) * (tau * tau) / dot_prod_teacher.numel()
return loss
def get_inputs():
return [torch.rand([4, 4]), torch.rand([4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 16
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp2 = tmp1 * tmp1
tmp4 = tmp3 * tmp3
tmp5 = tmp2 + tmp4
tmp7 = tmp6 * tmp6
tmp8 = tmp5 + tmp7
tmp10 = tmp9 * tmp9
tmp11 = tmp8 + tmp10
tmp12 = libdevice.sqrt(tmp11)
tmp13 = 1e-12
tmp14 = triton_helpers.maximum(tmp12, tmp13)
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x2, tmp15, xmask)
@triton.jit
def triton_per_fused_div_exp_mul_sub_sum_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)
tmp4 = tl.load(in_ptr1 + r0, None)
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp3 = tl_math.exp(tmp2)
tmp5 = tmp4 * tmp1
tmp6 = tmp2 - tmp5
tmp7 = tmp3 * tmp6
tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
tmp10 = tl.sum(tmp8, 1)[:, None]
tmp11 = tmp10 * tmp1
tmp12 = 0.0625
tmp13 = tmp11 * tmp12
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp13, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4), (4, 1))
assert_size_stride(arg1_1, (4, 4), (4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(16)](arg1_1, buf0, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg1_1
buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf0, reinterpret_tensor(buf0, (4, 4), (1, 4), 0),
out=buf1)
buf2 = buf0
del buf0
triton_poi_fused_div_0[grid(16)](arg0_1, buf2, 16, XBLOCK=16,
num_warps=1, num_stages=1)
del arg0_1
buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
extern_kernels.mm(buf2, reinterpret_tensor(buf2, (4, 4), (1, 4), 0),
out=buf3)
del buf2
buf4 = empty_strided_cuda((), (), torch.float32)
buf5 = buf4
del buf4
triton_per_fused_div_exp_mul_sub_sum_1[grid(1)](buf5, buf1, buf3, 1,
16, XBLOCK=1, num_warps=2, num_stages=1)
del buf1
del buf3
return buf5,
class DistillationOrthogonalProjectionLossNew(nn.Module):
def __init__(self):
super(DistillationOrthogonalProjectionLossNew, 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]
|
kahnchana/opl
|
DistillationOrthogonalProjectionLoss
| false
| 15,775
|
[
"MIT"
] | 64
|
1db31de3f95ced16c769f5b18325bdef46f317f4
|
https://github.com/kahnchana/opl/tree/1db31de3f95ced16c769f5b18325bdef46f317f4
|
MSE
|
import torch
import torch.nn as nn
from torch.optim import *
class MSE(nn.Module):
def __init__(self):
super().__init__()
def forward(self, outputs, target, *args):
val_pixels = (target > 0.001).float()
loss = target * val_pixels - outputs * val_pixels
return loss ** 2
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
from torch.optim import *
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_gt_mul_pow_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)
tmp5 = tl.load(in_ptr1 + x0, xmask)
tmp1 = 0.001
tmp2 = tmp0 > tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tmp0 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp4 - tmp6
tmp8 = tmp7 * tmp7
tl.store(out_ptr0 + x0, tmp8, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__to_copy_gt_mul_pow_sub_0[grid(256)](arg0_1,
arg1_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
del arg0_1
del arg1_1
return buf0,
class MSENew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
kakaxi314/GuideNet
|
MSE
| false
| 15,776
|
[
"MIT"
] | 142
|
9f53b4086d707e94d48a47bbac7dd87aaba9fdea
|
https://github.com/kakaxi314/GuideNet/tree/9f53b4086d707e94d48a47bbac7dd87aaba9fdea
|
ResBlock
|
from _paritybench_helpers import _mock_config
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.functional
def Activation_layer(activation_cfg, inplace=True):
out = None
if activation_cfg == 'ReLU':
out = nn.ReLU(inplace=inplace)
else:
out = nn.LeakyReLU(negative_slope=0.01, inplace=inplace)
return out
def Norm_layer(norm_cfg, inplanes):
out = None
if norm_cfg == 'BN':
out = nn.BatchNorm3d(inplanes)
elif norm_cfg == 'SyncBN':
out = nn.SyncBatchNorm(inplanes)
elif norm_cfg == 'GN':
out = nn.GroupNorm(16, inplanes)
else:
out = nn.InstanceNorm3d(inplanes, affine=True)
return out
def conv3x3x3(in_planes, out_planes, kernel_size, stride=(1, 1, 1), padding
=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=False, weight_std=False):
"""3x3x3 convolution with padding"""
if weight_std:
return Conv3d_wd(in_planes, out_planes, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=
groups, bias=bias)
else:
return nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=
groups, bias=bias)
class Conv3d_wd(nn.Conv3d):
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1,
1), padding=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=False):
super(Conv3d_wd, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, dilation, groups, bias)
def forward(self, x):
weight = self.weight
weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True
).mean(dim=3, keepdim=True).mean(dim=4, keepdim=True)
weight = weight - weight_mean
std = torch.sqrt(torch.var(weight.view(weight.size(0), -1), dim=1) +
1e-12).view(-1, 1, 1, 1, 1)
weight = weight / std.expand_as(weight)
return F.conv3d(x, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
class Conv3dBlock(nn.Module):
def __init__(self, in_channels, out_channels, norm_cfg, activation_cfg,
kernel_size, stride=(1, 1, 1), padding=(0, 0, 0), dilation=(1, 1, 1
), bias=False, weight_std=False):
super(Conv3dBlock, self).__init__()
self.conv = conv3x3x3(in_channels, out_channels, kernel_size=
kernel_size, stride=stride, padding=padding, dilation=dilation,
bias=bias, weight_std=weight_std)
self.norm = Norm_layer(norm_cfg, out_channels)
self.nonlin = Activation_layer(activation_cfg, inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.norm(x)
x = self.nonlin(x)
return x
class ResBlock(nn.Module):
def __init__(self, inplanes, planes, norm_cfg, activation_cfg,
weight_std=False):
super(ResBlock, self).__init__()
self.resconv1 = Conv3dBlock(inplanes, planes, norm_cfg,
activation_cfg, kernel_size=3, stride=1, padding=1, bias=False,
weight_std=weight_std)
self.resconv2 = Conv3dBlock(planes, planes, norm_cfg,
activation_cfg, kernel_size=3, stride=1, padding=1, bias=False,
weight_std=weight_std)
def forward(self, x):
residual = x
out = self.resconv1(x)
out = self.resconv2(out)
out = out + residual
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'inplanes': 4, 'planes': 4, 'norm_cfg': _mock_config(),
'activation_cfg': _mock_config()}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language 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.functional as F
import torch.nn as nn
import torch.nn.functional
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused__native_batch_norm_legit_leaky_relu_leaky_relu_backward_0(
in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr2, out_ptr3,
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)
tmp24 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp0 - tmp10
tmp18 = 64.0
tmp19 = tmp16 / tmp18
tmp20 = 1e-05
tmp21 = tmp19 + tmp20
tmp22 = libdevice.rsqrt(tmp21)
tmp23 = tmp17 * tmp22
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tmp28 = 0.0
tmp29 = tmp27 > tmp28
tmp30 = 0.01
tmp31 = tmp27 * tmp30
tmp32 = tl.where(tmp29, tmp27, tmp31)
tmp33 = tmp32 > tmp28
tl.store(in_out_ptr0 + (r1 + 64 * x0), tmp32, xmask)
tl.store(out_ptr2 + (r1 + 64 * x0), tmp33, xmask)
tl.store(out_ptr3 + x0, tmp22, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
@triton.jit
def triton_per_fused__native_batch_norm_legit_add_1(in_out_ptr0,
in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, 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)
tmp24 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
tmp26 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
tmp33 = tl.load(in_ptr3 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tl.where(xmask, tmp1, 0)
tmp4 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
tmp6 = tl.where(xmask, tmp4, 0)
tmp7 = tl.sum(tmp6, 1)[:, None]
tmp8 = tl.full([XBLOCK, 1], 64, tl.int32)
tmp9 = tmp8.to(tl.float32)
tmp10 = tmp7 / tmp9
tmp11 = tmp1 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = 64.0
tmp18 = tmp16 / tmp17
tmp19 = 1e-05
tmp20 = tmp18 + tmp19
tmp21 = libdevice.rsqrt(tmp20)
tmp22 = tmp0 - tmp10
tmp23 = tmp22 * tmp21
tmp25 = tmp23 * tmp24
tmp27 = tmp25 + tmp26
tmp28 = 0.0
tmp29 = tmp27 > tmp28
tmp30 = 0.01
tmp31 = tmp27 * tmp30
tmp32 = tl.where(tmp29, tmp27, tmp31)
tmp34 = tmp32 + tmp33
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp21, xmask)
tl.store(in_out_ptr1 + (r1 + 64 * x0), tmp34, xmask)
tl.store(out_ptr0 + x0, tmp10, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_3, (4,), (1,))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3, 3), (108, 27, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
4, 4, 4, 4), (256, 64, 16, 4, 1), 0), primals_2, stride=(1, 1,
1), padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf0, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf1 = empty_strided_cuda((1, 4, 1, 1, 1), (4, 1, 4, 4, 4), torch.
float32)
buf5 = empty_strided_cuda((1, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
buf6 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf5
buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
buf4 = empty_strided_cuda((1, 4, 1, 1, 1), (4, 1, 4, 4, 4), torch.
float32)
get_raw_stream(0)
triton_per_fused__native_batch_norm_legit_leaky_relu_leaky_relu_backward_0[
grid(4)](buf6, buf0, primals_3, primals_4, buf1, buf14, buf4, 4,
64, XBLOCK=1, num_warps=2, num_stages=1)
del primals_4
buf7 = extern_kernels.convolution(reinterpret_tensor(buf6, (1, 4, 4,
4, 4), (0, 64, 16, 4, 1), 0), primals_5, stride=(1, 1, 1),
padding=(1, 1, 1), dilation=(1, 1, 1), transposed=False,
output_padding=(0, 0, 0), groups=1, bias=None)
assert_size_stride(buf7, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1))
buf8 = empty_strided_cuda((1, 4, 1, 1, 1), (4, 1, 1, 1, 1), torch.
float32)
buf9 = empty_strided_cuda((1, 4, 1, 1, 1), (4, 1, 4, 4, 4), torch.
float32)
buf11 = reinterpret_tensor(buf9, (1, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0)
del buf9
buf12 = empty_strided_cuda((1, 4, 4, 4, 4), (256, 64, 16, 4, 1),
torch.float32)
buf13 = reinterpret_tensor(buf12, (4, 4, 4, 4), (64, 16, 4, 1), 0)
del buf12
triton_per_fused__native_batch_norm_legit_add_1[grid(4)](buf11,
buf13, buf7, primals_6, primals_7, primals_1, buf8, 4, 64,
XBLOCK=1, num_warps=2, num_stages=1)
return (buf13, primals_2, primals_3, primals_5, primals_6, primals_7,
reinterpret_tensor(primals_1, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1),
0), buf0, reinterpret_tensor(buf4, (4,), (1,), 0),
reinterpret_tensor(buf6, (1, 4, 4, 4, 4), (256, 64, 16, 4, 1), 0),
buf7, buf8, buf11, buf14, reinterpret_tensor(buf1, (1, 4, 1, 1, 1),
(4, 1, 1, 1, 1), 0))
def Activation_layer(activation_cfg, inplace=True):
out = None
if activation_cfg == 'ReLU':
out = nn.ReLU(inplace=inplace)
else:
out = nn.LeakyReLU(negative_slope=0.01, inplace=inplace)
return out
def Norm_layer(norm_cfg, inplanes):
out = None
if norm_cfg == 'BN':
out = nn.BatchNorm3d(inplanes)
elif norm_cfg == 'SyncBN':
out = nn.SyncBatchNorm(inplanes)
elif norm_cfg == 'GN':
out = nn.GroupNorm(16, inplanes)
else:
out = nn.InstanceNorm3d(inplanes, affine=True)
return out
def conv3x3x3(in_planes, out_planes, kernel_size, stride=(1, 1, 1), padding
=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=False, weight_std=False):
"""3x3x3 convolution with padding"""
if weight_std:
return Conv3d_wd(in_planes, out_planes, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=
groups, bias=bias)
else:
return nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=
groups, bias=bias)
class Conv3d_wd(nn.Conv3d):
def __init__(self, in_channels, out_channels, kernel_size, stride=(1, 1,
1), padding=(0, 0, 0), dilation=(1, 1, 1), groups=1, bias=False):
super(Conv3d_wd, self).__init__(in_channels, out_channels,
kernel_size, stride, padding, dilation, groups, bias)
def forward(self, x):
weight = self.weight
weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True
).mean(dim=3, keepdim=True).mean(dim=4, keepdim=True)
weight = weight - weight_mean
std = torch.sqrt(torch.var(weight.view(weight.size(0), -1), dim=1) +
1e-12).view(-1, 1, 1, 1, 1)
weight = weight / std.expand_as(weight)
return F.conv3d(x, weight, self.bias, self.stride, self.padding,
self.dilation, self.groups)
class Conv3dBlock(nn.Module):
def __init__(self, in_channels, out_channels, norm_cfg, activation_cfg,
kernel_size, stride=(1, 1, 1), padding=(0, 0, 0), dilation=(1, 1, 1
), bias=False, weight_std=False):
super(Conv3dBlock, self).__init__()
self.conv = conv3x3x3(in_channels, out_channels, kernel_size=
kernel_size, stride=stride, padding=padding, dilation=dilation,
bias=bias, weight_std=weight_std)
self.norm = Norm_layer(norm_cfg, out_channels)
self.nonlin = Activation_layer(activation_cfg, inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.norm(x)
x = self.nonlin(x)
return x
class ResBlockNew(nn.Module):
def __init__(self, inplanes, planes, norm_cfg, activation_cfg,
weight_std=False):
super(ResBlockNew, self).__init__()
self.resconv1 = Conv3dBlock(inplanes, planes, norm_cfg,
activation_cfg, kernel_size=3, stride=1, padding=1, bias=False,
weight_std=weight_std)
self.resconv2 = Conv3dBlock(planes, planes, norm_cfg,
activation_cfg, kernel_size=3, stride=1, padding=1, bias=False,
weight_std=weight_std)
def forward(self, input_0):
primals_2 = self.resconv1.conv.weight
primals_3 = self.resconv1.norm.weight
primals_4 = self.resconv1.norm.bias
primals_5 = self.resconv2.conv.weight
primals_6 = self.resconv2.norm.weight
primals_7 = self.resconv2.norm.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7])
return output[0]
|
junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration
|
ResBlock
| false
| 15,777
|
[
"MIT"
] | 82
|
dfa24a47a564a000aa9b4eea95a6e83a24568359
|
https://github.com/junyuchen245/TransMorph_Transformer_for_Medical_Image_Registration/tree/dfa24a47a564a000aa9b4eea95a6e83a24568359
|
RMSE
|
import torch
import torch.nn as nn
from torch.optim import *
class RMSE(nn.Module):
def __init__(self):
super().__init__()
def forward(self, outputs, target, *args):
val_pixels = (target > 0.001).float()
err = (target * val_pixels - outputs * val_pixels) ** 2
loss = torch.sum(err.view(err.size(0), 1, -1), -1, keepdim=True)
cnt = torch.sum(val_pixels.view(val_pixels.size(0), 1, -1), -1,
keepdim=True)
return torch.sqrt(loss / cnt)
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.optim import *
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_per_fused_div_sqrt_sum_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
rnumel, XBLOCK: tl.constexpr):
xnumel = 4
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r1 = rindex
x0 = xindex
tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
tmp5 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0)
tmp1 = 0.001
tmp2 = tmp0 > tmp1
tmp3 = tmp2.to(tl.float32)
tmp4 = tmp0 * tmp3
tmp6 = tmp5 * tmp3
tmp7 = tmp4 - tmp6
tmp8 = tmp7 * tmp7
tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
tmp11 = tl.where(xmask, tmp9, 0)
tmp12 = tl.sum(tmp11, 1)[:, None]
tmp13 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
tmp15 = tl.where(xmask, tmp13, 0)
tmp16 = tl.sum(tmp15, 1)[:, None]
tmp17 = tmp12 / tmp16
tmp18 = libdevice.sqrt(tmp17)
tl.debug_barrier()
tl.store(in_out_ptr0 + x0, tmp18, xmask)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 1, 1), (1, 4, 4), torch.float32)
buf2 = reinterpret_tensor(buf0, (4, 1, 1), (1, 1, 1), 0)
del buf0
get_raw_stream(0)
triton_per_fused_div_sqrt_sum_0[grid(4)](buf2, arg0_1, arg1_1, 4,
64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class RMSENew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_0, input_1):
arg0_1 = input_0
arg1_1 = input_1
output = call([arg0_1, arg1_1])
return output[0]
|
kakaxi314/GuideNet
|
RMSE
| false
| 15,778
|
[
"MIT"
] | 142
|
9f53b4086d707e94d48a47bbac7dd87aaba9fdea
|
https://github.com/kakaxi314/GuideNet/tree/9f53b4086d707e94d48a47bbac7dd87aaba9fdea
|
mySConv
|
import torch
import torch.nn as nn
from torch.nn import Conv2d
from torch.nn import ReLU
from torch.nn import InstanceNorm2d
class mySConv(nn.Module):
def __init__(self, num_filter=128, stride=1, in_channels=128):
super(mySConv, self).__init__()
self.conv = Conv2d(out_channels=num_filter, kernel_size=3, stride=
stride, padding=1, in_channels=in_channels)
self.bn = InstanceNorm2d(num_features=num_filter)
self.relu = ReLU()
def forward(self, x):
return self.relu(self.bn(self.conv(x)))
def get_inputs():
return [torch.rand([4, 128, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn import Conv2d
from torch.nn import ReLU
from torch.nn import InstanceNorm2d
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 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_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 512
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 % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 128 * x2 + 524288 * y1), tmp0, ymask)
@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 % 128
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__native_batch_norm_legit_relu_threshold_backward_3(in_ptr0
, out_ptr0, out_ptr2, out_ptr3, out_ptr4, xnumel, rnumel, XBLOCK: tl.
constexpr, RBLOCK: tl.constexpr):
xnumel = 512
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
tmp2_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_weight = tl.zeros([XBLOCK, RBLOCK], tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (128 * r1 + 524288 * (x0 // 128) + x0 %
128), rmask & xmask, eviction_policy='evict_last', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp2_mean_next, tmp2_m2_next, tmp2_weight_next = (triton_helpers.
welford_reduce(tmp1, tmp2_mean, tmp2_m2, tmp2_weight, roffset == 0)
)
tmp2_mean = tl.where(rmask & xmask, tmp2_mean_next, tmp2_mean)
tmp2_m2 = tl.where(rmask & xmask, tmp2_m2_next, tmp2_m2)
tmp2_weight = tl.where(rmask & xmask, tmp2_weight_next, tmp2_weight)
tmp2_tmp, tmp3_tmp, tmp4_tmp = triton_helpers.welford(tmp2_mean,
tmp2_m2, tmp2_weight, 1)
tmp2 = tmp2_tmp[:, None]
tmp3 = tmp3_tmp[:, None]
tmp4_tmp[:, None]
tl.store(out_ptr0 + x0, tmp2, xmask)
tmp5 = 4096.0
tmp6 = tmp3 / tmp5
tmp7 = 1e-05
tmp8 = tmp6 + tmp7
tmp9 = libdevice.rsqrt(tmp8)
tl.store(out_ptr2 + x0, tmp9, xmask)
x2 = xindex % 128
x3 = xindex // 128
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp10 = tl.load(in_ptr0 + (x2 + 128 * r1 + 524288 * x3), rmask &
xmask, eviction_policy='evict_first', other=0.0)
tmp11 = tmp10 - tmp2
tmp12 = tmp11 * tmp9
tmp13 = tl.full([1, 1], 0, tl.int32)
tmp14 = triton_helpers.maximum(tmp13, tmp12)
tmp15 = 0.0
tmp16 = tmp14 <= tmp15
tl.store(out_ptr3 + (r1 + 4096 * x0), tmp14, rmask & xmask)
tl.store(out_ptr4 + (x2 + 128 * r1 + 524288 * x3), tmp16, rmask & xmask
)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_2, (128,), (1,))
assert_size_stride(primals_3, (4, 128, 64, 64), (524288, 4096, 64, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16384, 9)](primals_1, buf0, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 128, 64, 64), (524288, 1, 8192, 128),
torch.float32)
triton_poi_fused_1[grid(512, 4096)](primals_3, buf1, 512, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf2 = 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(buf2, (4, 128, 64, 64), (524288, 1, 8192, 128))
buf3 = buf2
del buf2
triton_poi_fused_convolution_2[grid(2097152)](buf3, primals_2,
2097152, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf4 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512), torch
.float32)
buf7 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512), torch
.float32)
buf8 = empty_strided_cuda((4, 128, 64, 64), (524288, 4096, 64, 1),
torch.float32)
buf9 = empty_strided_cuda((4, 128, 64, 64), (524288, 1, 8192, 128),
torch.bool)
triton_red_fused__native_batch_norm_legit_relu_threshold_backward_3[
grid(512)](buf3, buf4, buf7, buf8, buf9, 512, 4096, XBLOCK=8,
RBLOCK=512, num_warps=16, num_stages=1)
return buf8, buf0, buf1, buf3, reinterpret_tensor(buf7, (512,), (1,), 0
), buf9, reinterpret_tensor(buf4, (1, 512, 1, 1), (512, 1, 1, 1), 0)
class mySConvNew(nn.Module):
def __init__(self, num_filter=128, stride=1, in_channels=128):
super(mySConvNew, self).__init__()
self.conv = Conv2d(out_channels=num_filter, kernel_size=3, stride=
stride, padding=1, in_channels=in_channels)
self.bn = InstanceNorm2d(num_features=num_filter)
self.relu = ReLU()
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]
|
junhocho/ShapeMatchingGAN
|
mySConv
| false
| 15,779
|
[
"MIT"
] | 117
|
b90e9c2490bfdf62c5da9b1eb6b0cdf0618cf570
|
https://github.com/junhocho/ShapeMatchingGAN/tree/b90e9c2490bfdf62c5da9b1eb6b0cdf0618cf570
|
Scale
|
import torch
from torch import nn
from torch.nn import *
class Scale(nn.Module):
def __init__(self, scale):
super().__init__()
self.scale = scale
def forward(self, x):
return x * self.scale
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'scale': 1.0}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch import nn
from torch.nn import *
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
tl.store(out_ptr0 + x0, tmp2, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class ScaleNew(nn.Module):
def __init__(self, scale):
super().__init__()
self.scale = scale
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
kcorder/autonomous-learning-library
|
Scale
| false
| 15,780
|
[
"MIT"
] | 584
|
0266195fa47564e51a32087bc007bff6dda5e263
|
https://github.com/kcorder/autonomous-learning-library/tree/0266195fa47564e51a32087bc007bff6dda5e263
|
MultiLayeredConv1d
|
import torch
class MultiLayeredConv1d(torch.nn.Module):
"""Multi-layered conv1d for Transformer block.
This is a module of multi-leyered conv1d designed to replace positionwise feed-forward network
in Transforner block, which is introduced in `FastSpeech: Fast, Robust and Controllable Text to Speech`_.
Args:
in_chans (int): Number of input channels.
hidden_chans (int): Number of hidden channels.
kernel_size (int): Kernel size of conv1d.
dropout_rate (float): Dropout rate.
.. _`FastSpeech: Fast, Robust and Controllable Text to Speech`:
https://arxiv.org/pdf/1905.09263.pdf
"""
def __init__(self, in_chans: 'int', hidden_chans: 'int', kernel_size:
'int', dropout_rate: 'float'):
super(MultiLayeredConv1d, self).__init__()
self.w_1 = torch.nn.Conv1d(in_chans, hidden_chans, kernel_size,
stride=1, padding=(kernel_size - 1) // 2)
self.w_2 = torch.nn.Conv1d(hidden_chans, in_chans, 1, stride=1,
padding=(1 - 1) // 2)
self.dropout = torch.nn.Dropout(dropout_rate)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
"""Calculate forward propagation.
Args:
x (Tensor): Batch of input tensors (B, *, in_chans).
Returns:
Tensor: Batch of output tensors (B, *, hidden_chans)
"""
x = torch.relu(self.w_1(x.transpose(-1, 1))).transpose(-1, 1)
return self.w_2(self.dropout(x).transpose(-1, 1)).transpose(-1, 1)
def get_inputs():
return [torch.rand([4, 4])]
def get_init_inputs():
return [[], {'in_chans': 4, 'hidden_chans': 4, 'kernel_size': 4,
'dropout_rate': 0.5}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
assert_size_stride = torch._C._dynamo.guards.assert_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 = 12
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 3
tmp0 = tl.load(in_out_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x2, tmp4, xmask)
tl.store(out_ptr0 + x2, tmp6, xmask)
@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 12
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 3
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, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 4), (4, 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, 1), (4, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(reinterpret_tensor(primals_1, (1,
4, 4), (16, 4, 1), 0), primals_2, stride=(1,), padding=(1,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf0, (1, 4, 3), (12, 3, 1))
buf1 = reinterpret_tensor(buf0, (4, 3), (3, 1), 0)
del buf0
buf4 = empty_strided_cuda((4, 3), (3, 1), torch.bool)
get_raw_stream(0)
triton_poi_fused_relu_threshold_backward_0[grid(12)](buf1,
primals_3, buf4, 12, XBLOCK=16, num_warps=1, num_stages=1)
del primals_3
buf2 = extern_kernels.convolution(reinterpret_tensor(buf1, (1, 4, 3
), (0, 3, 1), 0), primals_4, stride=(1,), padding=(0,),
dilation=(1,), transposed=False, output_padding=(0,), groups=1,
bias=None)
assert_size_stride(buf2, (1, 4, 3), (12, 3, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_1[grid(12)](buf3, primals_5, 12,
XBLOCK=16, num_warps=1, num_stages=1)
del primals_5
return reinterpret_tensor(buf3, (4, 3), (3, 1), 0
), primals_2, primals_4, reinterpret_tensor(primals_1, (1, 4, 4), (
16, 4, 1), 0), reinterpret_tensor(buf1, (1, 4, 3), (12, 3, 1), 0), buf4
class MultiLayeredConv1dNew(torch.nn.Module):
"""Multi-layered conv1d for Transformer block.
This is a module of multi-leyered conv1d designed to replace positionwise feed-forward network
in Transforner block, which is introduced in `FastSpeech: Fast, Robust and Controllable Text to Speech`_.
Args:
in_chans (int): Number of input channels.
hidden_chans (int): Number of hidden channels.
kernel_size (int): Kernel size of conv1d.
dropout_rate (float): Dropout rate.
.. _`FastSpeech: Fast, Robust and Controllable Text to Speech`:
https://arxiv.org/pdf/1905.09263.pdf
"""
def __init__(self, in_chans: 'int', hidden_chans: 'int', kernel_size:
'int', dropout_rate: 'float'):
super(MultiLayeredConv1dNew, self).__init__()
self.w_1 = torch.nn.Conv1d(in_chans, hidden_chans, kernel_size,
stride=1, padding=(kernel_size - 1) // 2)
self.w_2 = torch.nn.Conv1d(hidden_chans, in_chans, 1, stride=1,
padding=(1 - 1) // 2)
self.dropout = torch.nn.Dropout(dropout_rate)
def forward(self, input_0):
primals_2 = self.w_1.weight
primals_3 = self.w_1.bias
primals_4 = self.w_2.weight
primals_5 = self.w_2.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
karan-deepsync/FastSpeech2
|
MultiLayeredConv1d
| false
| 15,781
|
[
"Apache-2.0"
] | 148
|
84ad261db4a865536b2e15dfb8346644c3192704
|
https://github.com/karan-deepsync/FastSpeech2/tree/84ad261db4a865536b2e15dfb8346644c3192704
|
mySBlock
|
import torch
import torch.nn as nn
from torch.nn import Conv2d
from torch.nn import ReLU
from torch.nn import InstanceNorm2d
class mySConv(nn.Module):
def __init__(self, num_filter=128, stride=1, in_channels=128):
super(mySConv, self).__init__()
self.conv = Conv2d(out_channels=num_filter, kernel_size=3, stride=
stride, padding=1, in_channels=in_channels)
self.bn = InstanceNorm2d(num_features=num_filter)
self.relu = ReLU()
def forward(self, x):
return self.relu(self.bn(self.conv(x)))
class mySBlock(nn.Module):
def __init__(self, num_filter=128):
super(mySBlock, self).__init__()
self.myconv = mySConv(num_filter=num_filter, stride=1, in_channels=
num_filter)
self.conv = Conv2d(out_channels=num_filter, kernel_size=3, padding=
1, in_channels=num_filter)
self.bn = InstanceNorm2d(num_features=num_filter)
self.relu = ReLU()
def forward(self, x):
return self.relu(x + self.bn(self.conv(self.myconv(x))))
def get_inputs():
return [torch.rand([4, 128, 64, 64])]
def get_init_inputs():
return [[], {}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
from torch.nn import Conv2d
from torch.nn import ReLU
from torch.nn import InstanceNorm2d
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
xnumel = 9
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y0 = yindex % 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_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
constexpr, XBLOCK: tl.constexpr):
ynumel = 512
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 % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tl.store(out_ptr0 + (y0 + 128 * x2 + 524288 * y1), tmp0, ymask)
@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 % 128
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__native_batch_norm_legit_3(in_ptr0, out_ptr0, out_ptr1,
out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 512
rnumel = 4096
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
rbase = tl.arange(0, RBLOCK)[None, :]
x0 = xindex
tmp2_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_weight = tl.zeros([XBLOCK, RBLOCK], tl.float32)
for roffset in range(0, rnumel, RBLOCK):
rindex = roffset + rbase
rmask = rindex < rnumel
r1 = rindex
tmp0 = tl.load(in_ptr0 + (128 * r1 + 524288 * (x0 // 128) + x0 %
128), rmask & xmask, eviction_policy='evict_first', other=0.0)
tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
tmp2_mean_next, tmp2_m2_next, tmp2_weight_next = (triton_helpers.
welford_reduce(tmp1, tmp2_mean, tmp2_m2, tmp2_weight, roffset == 0)
)
tmp2_mean = tl.where(rmask & xmask, tmp2_mean_next, tmp2_mean)
tmp2_m2 = tl.where(rmask & xmask, tmp2_m2_next, tmp2_m2)
tmp2_weight = tl.where(rmask & xmask, tmp2_weight_next, tmp2_weight)
tmp2_tmp, tmp3_tmp, tmp4_tmp = triton_helpers.welford(tmp2_mean,
tmp2_m2, tmp2_weight, 1)
tmp2 = tmp2_tmp[:, None]
tmp3 = tmp3_tmp[:, None]
tmp4_tmp[:, None]
tl.store(out_ptr0 + x0, tmp2, xmask)
tl.store(out_ptr1 + x0, tmp3, xmask)
tmp5 = 4096.0
tmp6 = tmp3 / tmp5
tmp7 = 1e-05
tmp8 = tmp6 + tmp7
tmp9 = libdevice.rsqrt(tmp8)
tl.store(out_ptr2 + x0, tmp9, xmask)
@triton.jit
def triton_poi_fused_relu_4(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
x0 = xindex % 128
x2 = xindex // 524288
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + (x0 + 128 * x2), None, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr2 + (x0 + 128 * x2), None, eviction_policy=
'evict_last')
tmp2 = tmp0 - tmp1
tmp4 = 4096.0
tmp5 = tmp3 / tmp4
tmp6 = 1e-05
tmp7 = tmp5 + tmp6
tmp8 = libdevice.rsqrt(tmp7)
tmp9 = tmp2 * tmp8
tmp10 = tl.full([1], 0, tl.int32)
tmp11 = triton_helpers.maximum(tmp10, tmp9)
tl.store(out_ptr0 + x3, tmp11, None)
@triton.jit
def triton_poi_fused_add_relu_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
xnumel = 128
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
tl.full([XBLOCK, YBLOCK], True, tl.int1)
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y3 = yindex
y1 = yindex // 4096
y0 = yindex % 4096
tmp0 = tl.load(in_ptr0 + (x2 + 128 * y3), xmask, eviction_policy=
'evict_last')
tmp1 = tl.load(in_ptr1 + (x2 + 128 * y3), xmask, eviction_policy=
'evict_last')
tmp2 = tl.load(in_ptr2 + (x2 + 128 * y1), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr3 + (x2 + 128 * y1), xmask, eviction_policy=
'evict_last')
tmp3 = tmp1 - tmp2
tmp5 = 4096.0
tmp6 = tmp4 / tmp5
tmp7 = 1e-05
tmp8 = tmp6 + tmp7
tmp9 = libdevice.rsqrt(tmp8)
tmp10 = tmp3 * tmp9
tmp11 = tmp0 + tmp10
tmp12 = tl.full([1, 1], 0, tl.int32)
tmp13 = triton_helpers.maximum(tmp12, tmp11)
tl.store(out_ptr0 + (y0 + 4096 * x2 + 524288 * y1), tmp13, xmask)
@triton.jit
def triton_poi_fused_threshold_backward_6(in_ptr0, out_ptr0, ynumel, xnumel,
YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 512
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 % 128
y1 = yindex // 128
tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy=
'evict_last')
tmp1 = 0.0
tmp2 = tmp0 <= tmp1
tl.store(out_ptr0 + (y0 + 128 * x2 + 524288 * y1), tmp2, ymask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_2, (128,), (1,))
assert_size_stride(primals_3, (4, 128, 64, 64), (524288, 4096, 64, 1))
assert_size_stride(primals_4, (128, 128, 3, 3), (1152, 9, 3, 1))
assert_size_stride(primals_5, (128,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16384, 9)](primals_1, buf0, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_1
buf1 = empty_strided_cuda((4, 128, 64, 64), (524288, 1, 8192, 128),
torch.float32)
triton_poi_fused_1[grid(512, 4096)](primals_3, buf1, 512, 4096,
XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
del primals_3
buf2 = empty_strided_cuda((128, 128, 3, 3), (1152, 1, 384, 128),
torch.float32)
triton_poi_fused_0[grid(16384, 9)](primals_4, buf2, 16384, 9,
XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
del primals_4
buf3 = 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(buf3, (4, 128, 64, 64), (524288, 1, 8192, 128))
buf4 = buf3
del buf3
triton_poi_fused_convolution_2[grid(2097152)](buf4, primals_2,
2097152, XBLOCK=512, num_warps=8, num_stages=1)
del primals_2
buf5 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512), torch
.float32)
buf6 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512), torch
.float32)
buf8 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512), torch
.float32)
triton_red_fused__native_batch_norm_legit_3[grid(512)](buf4, buf5,
buf6, buf8, 512, 4096, XBLOCK=1, RBLOCK=2048, num_warps=16,
num_stages=1)
buf9 = empty_strided_cuda((4, 128, 64, 64), (524288, 1, 8192, 128),
torch.float32)
triton_poi_fused_relu_4[grid(2097152)](buf4, buf5, buf6, buf9,
2097152, XBLOCK=1024, num_warps=4, num_stages=1)
buf10 = extern_kernels.convolution(buf9, buf2, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 128, 64, 64), (524288, 1, 8192, 128))
buf11 = buf10
del buf10
triton_poi_fused_convolution_2[grid(2097152)](buf11, primals_5,
2097152, XBLOCK=512, num_warps=8, num_stages=1)
del primals_5
buf12 = buf6
del buf6
buf13 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
buf15 = empty_strided_cuda((1, 512, 1, 1), (512, 1, 512, 512),
torch.float32)
triton_red_fused__native_batch_norm_legit_3[grid(512)](buf11, buf12,
buf13, buf15, 512, 4096, XBLOCK=1, RBLOCK=2048, num_warps=16,
num_stages=1)
buf16 = empty_strided_cuda((4, 128, 64, 64), (524288, 4096, 64, 1),
torch.float32)
triton_poi_fused_add_relu_5[grid(16384, 128)](buf1, buf11, buf12,
buf13, buf16, 16384, 128, XBLOCK=32, YBLOCK=32, num_warps=4,
num_stages=1)
del buf13
buf17 = empty_strided_cuda((4, 128, 64, 64), (524288, 1, 8192, 128),
torch.bool)
triton_poi_fused_threshold_backward_6[grid(512, 4096)](buf16, buf17,
512, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
return buf16, buf0, buf1, buf2, buf4, reinterpret_tensor(buf8, (512,),
(1,), 0), buf9, buf11, reinterpret_tensor(buf15, (512,), (1,), 0
), buf17, reinterpret_tensor(buf12, (1, 512, 1, 1), (512, 1, 1, 1), 0
), reinterpret_tensor(buf5, (1, 512, 1, 1), (512, 1, 1, 1), 0)
class mySConv(nn.Module):
def __init__(self, num_filter=128, stride=1, in_channels=128):
super(mySConv, self).__init__()
self.conv = Conv2d(out_channels=num_filter, kernel_size=3, stride=
stride, padding=1, in_channels=in_channels)
self.bn = InstanceNorm2d(num_features=num_filter)
self.relu = ReLU()
def forward(self, x):
return self.relu(self.bn(self.conv(x)))
class mySBlockNew(nn.Module):
def __init__(self, num_filter=128):
super(mySBlockNew, self).__init__()
self.myconv = mySConv(num_filter=num_filter, stride=1, in_channels=
num_filter)
self.conv = Conv2d(out_channels=num_filter, kernel_size=3, padding=
1, in_channels=num_filter)
self.bn = InstanceNorm2d(num_features=num_filter)
self.relu = ReLU()
def forward(self, input_0):
primals_1 = self.myconv.conv.weight
primals_2 = self.myconv.conv.bias
primals_4 = self.conv.weight
primals_5 = self.conv.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
junhocho/ShapeMatchingGAN
|
mySBlock
| false
| 15,782
|
[
"MIT"
] | 117
|
b90e9c2490bfdf62c5da9b1eb6b0cdf0618cf570
|
https://github.com/junhocho/ShapeMatchingGAN/tree/b90e9c2490bfdf62c5da9b1eb6b0cdf0618cf570
|
LayerNorm
|
import torch
class LayerNorm(torch.nn.Module):
def __init__(self, nout: 'int'):
super(LayerNorm, self).__init__()
self.layer_norm = torch.nn.LayerNorm(nout, eps=1e-12)
def forward(self, x: 'torch.Tensor') ->torch.Tensor:
x = self.layer_norm(x.transpose(1, -1))
x = x.transpose(1, -1)
return x
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'nout': 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
assert_size_stride = torch._C._dynamo.guards.assert_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 % 16
x1 = xindex // 16
x2 = xindex
tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
tmp1 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
tmp3 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
tmp5 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
tmp2 = tmp0 + tmp1
tmp4 = tmp2 + tmp3
tmp6 = tmp4 + tmp5
tmp7 = 4.0
tmp8 = tmp6 / tmp7
tmp9 = tmp0 - tmp8
tmp10 = tmp9 * tmp9
tmp11 = tmp1 - tmp8
tmp12 = tmp11 * tmp11
tmp13 = tmp10 + tmp12
tmp14 = tmp3 - tmp8
tmp15 = tmp14 * tmp14
tmp16 = tmp13 + tmp15
tmp17 = tmp5 - tmp8
tmp18 = tmp17 * tmp17
tmp19 = tmp16 + tmp18
tmp20 = tmp19 / tmp7
tmp21 = 1e-12
tmp22 = tmp20 + tmp21
tmp23 = libdevice.rsqrt(tmp22)
tl.store(out_ptr0 + x2, tmp8, xmask)
tl.store(out_ptr1 + x2, tmp23, xmask)
@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
in_ptr4, 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
x3 = xindex
y2 = yindex // 16
y4 = yindex % 16
y5 = yindex
y0 = yindex % 4
y1 = yindex // 4 % 4
tmp0 = tl.load(in_ptr0 + (y4 + 16 * x3 + 64 * y2), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y5, ymask, eviction_policy='evict_last')
tmp3 = tl.load(in_ptr2 + y5, ymask, eviction_policy='evict_last')
tmp5 = tl.load(in_ptr3 + x3, xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr4 + x3, xmask, eviction_policy='evict_last')
tmp2 = tmp0 - tmp1
tmp4 = tmp2 * tmp3
tmp6 = tmp4 * tmp5
tmp8 = tmp6 + tmp7
tl.store(out_ptr0 + (x3 + 4 * y1 + 16 * y0 + 64 * y2), tmp8, xmask & ymask)
def call(args):
primals_1, primals_2, primals_3 = args
args.clear()
assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_2, (4,), (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), (16, 1, 4, 64), torch.float32)
buf1 = empty_strided_cuda((4, 4, 4, 1), (16, 1, 4, 64), torch.float32)
get_raw_stream(0)
triton_poi_fused_native_layer_norm_0[grid(64)](primals_1, buf0,
buf1, 64, XBLOCK=64, num_warps=1, num_stages=1)
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_native_layer_norm_1[grid(64, 4)](primals_1, buf0,
buf1, primals_2, primals_3, buf2, 64, 4, XBLOCK=4, YBLOCK=32,
num_warps=4, num_stages=1)
del buf0
del buf1
del primals_2
del primals_3
return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 1, 4, 16), 0), primals_1
class LayerNormNew(torch.nn.Module):
def __init__(self, nout: 'int'):
super(LayerNormNew, self).__init__()
self.layer_norm = torch.nn.LayerNorm(nout, eps=1e-12)
def forward(self, input_0):
primals_2 = self.layer_norm.weight
primals_3 = self.layer_norm.bias
primals_1 = input_0
output = call([primals_1, primals_2, primals_3])
return output[0]
|
karan-deepsync/FastSpeech2
|
LayerNorm
| false
| 15,783
|
[
"Apache-2.0"
] | 148
|
84ad261db4a865536b2e15dfb8346644c3192704
|
https://github.com/karan-deepsync/FastSpeech2/tree/84ad261db4a865536b2e15dfb8346644c3192704
|
AlbertAttention
|
from _paritybench_helpers import _mock_config
import math
import torch
from typing import List
from typing import Tuple
from torch import nn
from typing import Set
import torch.utils.checkpoint
def find_pruneable_heads_and_indices(heads: 'List[int]', n_heads: 'int',
head_size: 'int', already_pruned_heads: 'Set[int]') ->Tuple[Set[int],
torch.LongTensor]:
"""
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
Args:
heads (:obj:`List[int]`): List of the indices of heads to prune.
n_heads (:obj:`int`): The number of heads in the model.
head_size (:obj:`int`): The size of each head.
already_pruned_heads (:obj:`Set[int]`): A set of already pruned heads.
Returns:
:obj:`Tuple[Set[int], torch.LongTensor]`: A tuple with the remaining heads and their corresponding indices.
"""
mask = torch.ones(n_heads, head_size)
heads = set(heads) - already_pruned_heads
for head in heads:
head = head - sum(1 if h < head else 0 for h in already_pruned_heads)
mask[head] = 0
mask = mask.view(-1).contiguous().eq(1)
index: 'torch.LongTensor' = torch.arange(len(mask))[mask].long()
return heads, index
def prune_linear_layer(layer: 'nn.Linear', index: 'torch.LongTensor', dim:
'int'=0) ->nn.Linear:
"""
Prune a linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`torch.nn.Linear`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to keep in the layer.
dim (:obj:`int`, `optional`, defaults to 0): The dimension on which to keep the indices.
Returns:
:obj:`torch.nn.Linear`: The pruned layer as a new layer with :obj:`requires_grad=True`.
"""
index = index
W = layer.weight.index_select(dim, index).clone().detach()
if layer.bias is not None:
if dim == 1:
b = layer.bias.clone().detach()
else:
b = layer.bias[index].clone().detach()
new_size = list(layer.weight.size())
new_size[dim] = len(index)
new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None
)
new_layer.weight.requires_grad = False
new_layer.weight.copy_(W.contiguous())
new_layer.weight.requires_grad = True
if layer.bias is not None:
new_layer.bias.requires_grad = False
new_layer.bias.copy_(b.contiguous())
new_layer.bias.requires_grad = True
return new_layer
class AlbertAttention(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads}'
)
self.num_attention_heads = config.num_attention_heads
self.hidden_size = config.hidden_size
self.attention_head_size = (config.hidden_size // config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.attention_dropout = nn.Dropout(config.attention_probs_dropout_prob
)
self.output_dropout = nn.Dropout(config.hidden_dropout_prob)
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.pruned_heads = set()
self.position_embedding_type = getattr(config,
'position_embedding_type', 'absolute')
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.
max_position_embeddings - 1, self.attention_head_size)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.
num_attention_heads, self.attention_head_size, self.pruned_heads)
self.query = prune_linear_layer(self.query, index)
self.key = prune_linear_layer(self.key, index)
self.value = prune_linear_layer(self.value, index)
self.dense = prune_linear_layer(self.dense, index, dim=1)
self.num_attention_heads = self.num_attention_heads - len(heads)
self.all_head_size = (self.attention_head_size * self.
num_attention_heads)
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, hidden_states, attention_mask=None, head_mask=None,
output_attentions=False):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1,
-2))
attention_scores = attention_scores / math.sqrt(self.
attention_head_size)
if attention_mask is not None:
attention_scores = attention_scores + attention_mask
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
seq_length = hidden_states.size()[1]
position_ids_l = torch.arange(seq_length, dtype=torch.long,
device=hidden_states.device).view(-1, 1)
position_ids_r = torch.arange(seq_length, dtype=torch.long,
device=hidden_states.device).view(1, -1)
distance = position_ids_l - position_ids_r
positional_embedding = self.distance_embedding(distance + self.
max_position_embeddings - 1)
positional_embedding = positional_embedding
if self.position_embedding_type == 'relative_key':
relative_position_scores = torch.einsum('bhld,lrd->bhlr',
query_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores
elif self.position_embedding_type == 'relative_key_query':
relative_position_scores_query = torch.einsum('bhld,lrd->bhlr',
query_layer, positional_embedding)
relative_position_scores_key = torch.einsum('bhrd,lrd->bhlr',
key_layer, positional_embedding)
attention_scores = (attention_scores +
relative_position_scores_query +
relative_position_scores_key)
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.attention_dropout(attention_probs)
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
w = self.dense.weight.t().view(self.num_attention_heads, self.
attention_head_size, self.hidden_size)
b = self.dense.bias
projected_context_layer = torch.einsum('bfnd,ndh->bfh',
context_layer, w) + b
projected_context_layer_dropout = self.output_dropout(
projected_context_layer)
layernormed_context_layer = self.LayerNorm(hidden_states +
projected_context_layer_dropout)
return (layernormed_context_layer, attention_probs
) if output_attentions else (layernormed_context_layer,)
def get_inputs():
return [torch.rand([4, 4, 4])]
def get_init_inputs():
return [[], {'config': _mock_config(hidden_size=4, num_attention_heads=
4, attention_probs_dropout_prob=0.5, hidden_dropout_prob=0.5,
layer_norm_eps=1, position_embedding_type=4)}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from typing import List
from typing import Tuple
from torch import nn
from typing import Set
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_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
tmp3 = 1.0
tmp4 = tmp2 * tmp3
tl.store(out_ptr0 + (x2 + 4 * y3), tmp4, xmask & ymask)
@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x2 = xindex
x1 = xindex // 4
tmp0 = tl.load(in_ptr0 + x2, xmask)
tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp5 = triton_helpers.maximum(tmp3, tmp4)
tmp7 = triton_helpers.maximum(tmp5, tmp6)
tmp8 = tmp0 - tmp7
tmp9 = tl_math.exp(tmp8)
tl.store(out_ptr0 + x2, tmp9, xmask)
@triton.jit
def triton_poi_fused_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr
):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 4
x2 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp25 = tl.load(in_ptr1 + x2, xmask)
tmp26 = tl.load(in_ptr1 + 4 * x1, xmask, eviction_policy='evict_last')
tmp27 = tl.load(in_ptr1 + (1 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp29 = tl.load(in_ptr1 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp31 = tl.load(in_ptr1 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
)
tmp1 = float('-inf')
tmp2 = tmp0 == tmp1
tmp3 = tmp2 == 0
tmp4 = tmp3.to(tl.int64)
tmp5 = tmp4 != 0
tmp7 = tmp6 == tmp1
tmp8 = tmp7 == 0
tmp9 = tmp8.to(tl.int64)
tmp10 = tmp9 != 0
tmp11 = tmp5 | tmp10
tmp13 = tmp12 == tmp1
tmp14 = tmp13 == 0
tmp15 = tmp14.to(tl.int64)
tmp16 = tmp15 != 0
tmp17 = tmp11 | tmp16
tmp19 = tmp18 == tmp1
tmp20 = tmp19 == 0
tmp21 = tmp20.to(tl.int64)
tmp22 = tmp21 != 0
tmp23 = tmp17 | tmp22
tmp24 = tmp23 == 0
tmp28 = tmp26 + tmp27
tmp30 = tmp28 + tmp29
tmp32 = tmp30 + tmp31
tmp33 = tmp25 / tmp32
tmp34 = 0.0
tmp35 = tl.where(tmp24, tmp34, tmp33)
tl.store(out_ptr0 + x2, tmp35, xmask)
@triton.jit
def triton_poi_fused_3(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK:
tl.constexpr, XBLOCK: tl.constexpr):
ynumel = 16
xnumel = 4
yoffset = tl.program_id(1) * YBLOCK
yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
ymask = yindex < ynumel
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
xmask = xindex < xnumel
x2 = xindex
y0 = yindex % 4
y1 = yindex // 4
y3 = yindex
tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask,
eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(out_ptr0 + (x2 + 4 * y3), tmp2, xmask & ymask)
@triton.jit
def triton_poi_fused_clone_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_native_layer_norm_5(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_6(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 = 1.0
tmp9 = tmp7 + tmp8
tmp10 = libdevice.rsqrt(tmp9)
tmp11 = tmp6 * tmp10
tmp13 = tmp11 * tmp12
tmp15 = tmp13 + tmp14
tl.store(out_ptr0 + x2, tmp15, 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, 1))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4), (4, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4,), (1,))
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_3, (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_3, (16, 4), (4, 1), 0),
reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf2)
del primals_6
buf3 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_0[grid(16, 4)](buf0, primals_2, buf3, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_2
buf4 = reinterpret_tensor(buf0, (4, 4, 1, 4), (16, 4, 4, 1), 0)
del buf0
triton_poi_fused_0[grid(16, 4)](buf1, primals_5, buf4, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_5
buf5 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32)
extern_kernels.bmm(reinterpret_tensor(buf3, (16, 4, 1), (4, 1, 0),
0), reinterpret_tensor(buf4, (16, 1, 4), (4, 0, 1), 0), out=buf5)
buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_1[grid(256)](buf5, buf6, 256, XBLOCK=128,
num_warps=4, num_stages=1)
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused_2[grid(256)](buf5, buf6, buf7, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del buf5
del buf6
buf8 = reinterpret_tensor(buf1, (4, 4, 4, 1), (16, 4, 1, 1), 0)
del buf1
triton_poi_fused_3[grid(16, 4)](buf2, primals_7, buf8, 16, 4,
XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
del primals_7
buf9 = reinterpret_tensor(buf2, (16, 4, 1), (4, 1, 1), 0)
del buf2
extern_kernels.bmm(reinterpret_tensor(buf7, (16, 4, 4), (16, 4, 1),
0), reinterpret_tensor(buf8, (16, 4, 1), (4, 1, 0), 0), out=buf9)
buf10 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 1), torch.float32)
triton_poi_fused_clone_4[grid(16, 4)](buf9, buf10, 16, 4, XBLOCK=4,
YBLOCK=16, num_warps=1, num_stages=1)
buf11 = reinterpret_tensor(buf9, (1, 16, 4), (64, 4, 1), 0)
del buf9
extern_kernels.bmm(reinterpret_tensor(buf10, (1, 16, 4), (0, 4, 1),
0), reinterpret_tensor(primals_8, (1, 4, 4), (0, 1, 4), 0), out
=buf11)
buf12 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
buf13 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32)
triton_poi_fused_add_native_layer_norm_5[grid(16)](primals_3, buf11,
primals_9, buf12, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1)
buf14 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
triton_poi_fused_add_native_layer_norm_6[grid(64)](primals_3, buf11,
primals_9, buf12, buf13, primals_10, primals_11, buf14, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del buf12
del buf13
del primals_11
return buf14, primals_3, primals_9, primals_10, buf7, 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, 4), 0
), buf11, reinterpret_tensor(buf10, (1, 4, 16), (64, 1, 4), 0
), reinterpret_tensor(primals_8, (1, 4, 4), (4, 4, 1), 0)
def find_pruneable_heads_and_indices(heads: 'List[int]', n_heads: 'int',
head_size: 'int', already_pruned_heads: 'Set[int]') ->Tuple[Set[int],
torch.LongTensor]:
"""
Finds the heads and their indices taking :obj:`already_pruned_heads` into account.
Args:
heads (:obj:`List[int]`): List of the indices of heads to prune.
n_heads (:obj:`int`): The number of heads in the model.
head_size (:obj:`int`): The size of each head.
already_pruned_heads (:obj:`Set[int]`): A set of already pruned heads.
Returns:
:obj:`Tuple[Set[int], torch.LongTensor]`: A tuple with the remaining heads and their corresponding indices.
"""
mask = torch.ones(n_heads, head_size)
heads = set(heads) - already_pruned_heads
for head in heads:
head = head - sum(1 if h < head else 0 for h in already_pruned_heads)
mask[head] = 0
mask = mask.view(-1).contiguous().eq(1)
index: 'torch.LongTensor' = torch.arange(len(mask))[mask].long()
return heads, index
def prune_linear_layer(layer: 'nn.Linear', index: 'torch.LongTensor', dim:
'int'=0) ->nn.Linear:
"""
Prune a linear layer to keep only entries in index.
Used to remove heads.
Args:
layer (:obj:`torch.nn.Linear`): The layer to prune.
index (:obj:`torch.LongTensor`): The indices to keep in the layer.
dim (:obj:`int`, `optional`, defaults to 0): The dimension on which to keep the indices.
Returns:
:obj:`torch.nn.Linear`: The pruned layer as a new layer with :obj:`requires_grad=True`.
"""
index = index
W = layer.weight.index_select(dim, index).clone().detach()
if layer.bias is not None:
if dim == 1:
b = layer.bias.clone().detach()
else:
b = layer.bias[index].clone().detach()
new_size = list(layer.weight.size())
new_size[dim] = len(index)
new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None
)
new_layer.weight.requires_grad = False
new_layer.weight.copy_(W.contiguous())
new_layer.weight.requires_grad = True
if layer.bias is not None:
new_layer.bias.requires_grad = False
new_layer.bias.copy_(b.contiguous())
new_layer.bias.requires_grad = True
return new_layer
class AlbertAttentionNew(nn.Module):
def __init__(self, config):
super().__init__()
if (config.hidden_size % config.num_attention_heads != 0 and not
hasattr(config, 'embedding_size')):
raise ValueError(
f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention heads ({config.num_attention_heads}'
)
self.num_attention_heads = config.num_attention_heads
self.hidden_size = config.hidden_size
self.attention_head_size = (config.hidden_size // config.
num_attention_heads)
self.all_head_size = (self.num_attention_heads * self.
attention_head_size)
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.attention_dropout = nn.Dropout(config.attention_probs_dropout_prob
)
self.output_dropout = nn.Dropout(config.hidden_dropout_prob)
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps)
self.pruned_heads = set()
self.position_embedding_type = getattr(config,
'position_embedding_type', 'absolute')
if (self.position_embedding_type == 'relative_key' or self.
position_embedding_type == 'relative_key_query'):
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.
max_position_embeddings - 1, self.attention_head_size)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.
attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.
num_attention_heads, self.attention_head_size, self.pruned_heads)
self.query = prune_linear_layer(self.query, index)
self.key = prune_linear_layer(self.key, index)
self.value = prune_linear_layer(self.value, index)
self.dense = prune_linear_layer(self.dense, index, dim=1)
self.num_attention_heads = self.num_attention_heads - len(heads)
self.all_head_size = (self.attention_head_size * self.
num_attention_heads)
self.pruned_heads = self.pruned_heads.union(heads)
def forward(self, input_0):
primals_1 = self.query.weight
primals_2 = self.query.bias
primals_4 = self.key.weight
primals_5 = self.key.bias
primals_6 = self.value.weight
primals_7 = self.value.bias
primals_8 = self.dense.weight
primals_9 = self.dense.bias
primals_10 = self.LayerNorm.weight
primals_11 = self.LayerNorm.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]
|
jxhe/unify-parameter-efficient-tuning
|
AlbertAttention
| false
| 15,784
|
[
"Apache-2.0"
] | 101
|
3222ce2c0079566a28043e22380eb4ab6ad14389
|
https://github.com/jxhe/unify-parameter-efficient-tuning/tree/3222ce2c0079566a28043e22380eb4ab6ad14389
|
L2Norm
|
import torch
import torch.nn as nn
import torch.nn.init
class L2Norm(nn.Module):
def __init__(self):
super(L2Norm, self).__init__()
self.eps = 1e-10
def forward(self, x):
norm = torch.sqrt(torch.sum(x * x, dim=1) + self.eps)
x = x / norm.unsqueeze(-1).expand_as(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
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
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_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
x1 = xindex // 4 % 16
x2 = xindex // 64
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + (x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp3 = tl.load(in_ptr0 + (16 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x1 + 64 * x2), xmask, eviction_policy=
'evict_last')
tmp9 = tl.load(in_ptr0 + (48 + x1 + 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 = 1e-10
tmp13 = tmp11 + tmp12
tmp14 = libdevice.sqrt(tmp13)
tmp15 = tmp0 / tmp14
tl.store(out_ptr0 + x3, tmp15, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_div_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class L2NormNew(nn.Module):
def __init__(self):
super(L2NormNew, self).__init__()
self.eps = 1e-10
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
keeeeenw/image-matching-benchmark-baselines
|
L2Norm
| false
| 15,785
|
[
"Apache-2.0"
] | 103
|
1a11bedbe3c57f477ab9de302591811115ada37a
|
https://github.com/keeeeenw/image-matching-benchmark-baselines/tree/1a11bedbe3c57f477ab9de302591811115ada37a
|
BCELoss
|
import torch
import torch.utils.data
from torch import nn
class BCELoss(nn.Module):
def __init__(self):
super(self.__class__, self).__init__()
def forward(self, input, target):
return -torch.mean(torch.sum(target * torch.log(torch.clamp(input,
min=1e-10)) + (1 - target) * torch.log(torch.clamp(1 - input,
min=1e-10)), 1))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_add_clamp_log_mean_mul_neg_rsub_sum_0(in_out_ptr0,
in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp13 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp14 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp25 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp26 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp37 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp38 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp2 = 1e-10
tmp3 = triton_helpers.maximum(tmp1, tmp2)
tmp4 = tl_math.log(tmp3)
tmp5 = tmp0 * tmp4
tmp6 = 1.0
tmp7 = tmp6 - tmp0
tmp8 = tmp6 - tmp1
tmp9 = triton_helpers.maximum(tmp8, tmp2)
tmp10 = tl_math.log(tmp9)
tmp11 = tmp7 * tmp10
tmp12 = tmp5 + tmp11
tmp15 = triton_helpers.maximum(tmp14, tmp2)
tmp16 = tl_math.log(tmp15)
tmp17 = tmp13 * tmp16
tmp18 = tmp6 - tmp13
tmp19 = tmp6 - tmp14
tmp20 = triton_helpers.maximum(tmp19, tmp2)
tmp21 = tl_math.log(tmp20)
tmp22 = tmp18 * tmp21
tmp23 = tmp17 + tmp22
tmp24 = tmp12 + tmp23
tmp27 = triton_helpers.maximum(tmp26, tmp2)
tmp28 = tl_math.log(tmp27)
tmp29 = tmp25 * tmp28
tmp30 = tmp6 - tmp25
tmp31 = tmp6 - tmp26
tmp32 = triton_helpers.maximum(tmp31, tmp2)
tmp33 = tl_math.log(tmp32)
tmp34 = tmp30 * tmp33
tmp35 = tmp29 + tmp34
tmp36 = tmp24 + tmp35
tmp39 = triton_helpers.maximum(tmp38, tmp2)
tmp40 = tl_math.log(tmp39)
tmp41 = tmp37 * tmp40
tmp42 = tmp6 - tmp37
tmp43 = tmp6 - tmp38
tmp44 = triton_helpers.maximum(tmp43, tmp2)
tmp45 = tl_math.log(tmp44)
tmp46 = tmp42 * tmp45
tmp47 = tmp41 + tmp46
tmp48 = tmp36 + tmp47
tmp49 = tl.broadcast_to(tmp48, [XBLOCK, RBLOCK])
tmp51 = tl.sum(tmp49, 1)[:, None]
tmp52 = 64.0
tmp53 = tmp51 / tmp52
tmp54 = -tmp53
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp54, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf1 = empty_strided_cuda((), (), torch.float32)
buf2 = buf1
del buf1
get_raw_stream(0)
triton_per_fused_add_clamp_log_mean_mul_neg_rsub_sum_0[grid(1)](buf2,
arg1_1, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf2,
class BCELossNew(nn.Module):
def __init__(self):
super(self.__class__, 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]
|
kejiejiang/UnsupervisedDeepLearning-Pytorch
|
BCELoss
| false
| 15,786
|
[
"MIT"
] | 87
|
6ea7b7151ae62bf0130b56cc023f2be068aa87f0
|
https://github.com/kejiejiang/UnsupervisedDeepLearning-Pytorch/tree/6ea7b7151ae62bf0130b56cc023f2be068aa87f0
|
stage_block
|
import torch
import torch.nn as nn
import torch.utils.data
class dilation_layer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, padding=
'same_padding', dilation=1):
super(dilation_layer, self).__init__()
if padding == 'same_padding':
padding = int((kernel_size - 1) / 2 * dilation)
self.Dconv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, padding=padding,
dilation=dilation)
self.Drelu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.Dconv(x)
x = self.Drelu(x)
return x
class stage_block(nn.Module):
"""This class makes sure the paf and heatmap branch out in every stage"""
def __init__(self, in_channels, out_channels):
super(stage_block, self).__init__()
self.Dconv_1 = dilation_layer(in_channels, out_channels=64)
self.Dconv_2 = dilation_layer(in_channels=64, out_channels=64)
self.Dconv_3 = dilation_layer(in_channels=64, out_channels=64,
dilation=2)
self.Dconv_4 = dilation_layer(in_channels=64, out_channels=32,
dilation=4)
self.Dconv_5 = dilation_layer(in_channels=32, out_channels=32,
dilation=8)
self.Mconv_6 = nn.Conv2d(in_channels=256, out_channels=128,
kernel_size=1, padding=0)
self.Mrelu_6 = nn.ReLU(inplace=True)
self.paf = nn.Conv2d(in_channels=128, out_channels=14, kernel_size=
1, padding=0)
self.heatmap = nn.Conv2d(in_channels=128, out_channels=9,
kernel_size=1, padding=0)
def forward(self, x):
x_1 = self.Dconv_1(x)
x_2 = self.Dconv_2(x_1)
x_3 = self.Dconv_3(x_2)
x_4 = self.Dconv_4(x_3)
x_5 = self.Dconv_5(x_4)
x_cat = torch.cat([x_1, x_2, x_3, x_4, x_5], 1)
x_out = self.Mconv_6(x_cat)
x_out = self.Mrelu_6(x_out)
paf = self.paf(x_out)
heatmap = self.heatmap(x_out)
return paf, heatmap
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_convolution_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 // 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 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, None)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 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_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x1 = xindex // 16 % 256
x0 = xindex % 16
x2 = xindex // 4096
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 64, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 1024 * x2), tmp4, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 128, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (x0 + 16 * (-64 + x1) + 1024 * x2), tmp9,
other=0.0)
tmp11 = tmp0 >= tmp7
tmp12 = tl.full([1], 192, tl.int64)
tmp13 = tmp0 < tmp12
tmp14 = tmp11 & tmp13
tmp15 = tl.load(in_ptr2 + (x0 + 16 * (-128 + x1) + 1024 * x2), tmp14,
other=0.0)
tmp16 = tmp0 >= tmp12
tmp17 = tl.full([1], 224, tl.int64)
tmp18 = tmp0 < tmp17
tmp19 = tmp16 & tmp18
tmp20 = tl.load(in_ptr3 + (x0 + 16 * (-192 + x1) + 512 * x2), tmp19,
other=0.0)
tmp21 = tmp0 >= tmp17
tl.full([1], 256, tl.int64)
tmp24 = tl.load(in_ptr4 + (x0 + 16 * (-224 + x1) + 512 * x2), tmp21,
other=0.0)
tmp25 = tl.load(in_ptr5 + (-224 + x1), tmp21, eviction_policy=
'evict_last', other=0.0)
tmp26 = tmp24 + tmp25
tmp27 = tl.full([1], 0, tl.int32)
tmp28 = triton_helpers.maximum(tmp27, tmp26)
tmp29 = tl.full(tmp28.shape, 0.0, tmp28.dtype)
tmp30 = tl.where(tmp21, tmp28, tmp29)
tmp31 = tl.where(tmp19, tmp20, tmp30)
tmp32 = tl.where(tmp14, tmp15, tmp31)
tmp33 = tl.where(tmp9, tmp10, tmp32)
tmp34 = tl.where(tmp4, tmp5, tmp33)
tl.store(out_ptr0 + x3, tmp34, 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 // 16 % 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_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 896
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 14
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 576
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 9
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_6(in_ptr0, in_ptr1,
out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 16 % 32
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) = args
args.clear()
assert_size_stride(primals_1, (64, 4, 3, 3), (36, 9, 3, 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, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_5, (64,), (1,))
assert_size_stride(primals_6, (64, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_7, (64,), (1,))
assert_size_stride(primals_8, (32, 64, 3, 3), (576, 9, 3, 1))
assert_size_stride(primals_9, (32,), (1,))
assert_size_stride(primals_10, (32, 32, 3, 3), (288, 9, 3, 1))
assert_size_stride(primals_11, (32,), (1,))
assert_size_stride(primals_12, (128, 256, 1, 1), (256, 1, 1, 1))
assert_size_stride(primals_13, (128,), (1,))
assert_size_stride(primals_14, (14, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_15, (14,), (1,))
assert_size_stride(primals_16, (9, 128, 1, 1), (128, 1, 1, 1))
assert_size_stride(primals_17, (9,), (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, 4, 4), (1024, 16, 4, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_relu_0[grid(4096)](buf1, primals_2,
4096, XBLOCK=256, 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, 4, 4), (1024, 16, 4, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_relu_0[grid(4096)](buf3, primals_5,
4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_5
buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1),
padding=(2, 2), dilation=(2, 2), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf4, (4, 64, 4, 4), (1024, 16, 4, 1))
buf5 = buf4
del buf4
triton_poi_fused_convolution_relu_0[grid(4096)](buf5, primals_7,
4096, XBLOCK=256, num_warps=4, num_stages=1)
del primals_7
buf6 = extern_kernels.convolution(buf5, primals_8, stride=(1, 1),
padding=(4, 4), dilation=(4, 4), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf6, (4, 32, 4, 4), (512, 16, 4, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_relu_1[grid(2048)](buf7, primals_9,
2048, XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf8 = extern_kernels.convolution(buf7, primals_10, stride=(1, 1),
padding=(8, 8), dilation=(8, 8), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf8, (4, 32, 4, 4), (512, 16, 4, 1))
buf9 = empty_strided_cuda((4, 256, 4, 4), (4096, 16, 4, 1), torch.
float32)
triton_poi_fused_cat_2[grid(16384)](buf1, buf3, buf5, buf7, buf8,
primals_11, buf9, 16384, XBLOCK=256, num_warps=4, num_stages=1)
buf10 = extern_kernels.convolution(buf9, primals_12, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf10, (4, 128, 4, 4), (2048, 16, 4, 1))
buf11 = buf10
del buf10
triton_poi_fused_convolution_relu_3[grid(8192)](buf11, primals_13,
8192, XBLOCK=128, num_warps=4, num_stages=1)
del primals_13
buf12 = extern_kernels.convolution(buf11, primals_14, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf12, (4, 14, 4, 4), (224, 16, 4, 1))
buf13 = buf12
del buf12
triton_poi_fused_convolution_4[grid(896)](buf13, primals_15, 896,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_15
buf14 = extern_kernels.convolution(buf11, primals_16, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf14, (4, 9, 4, 4), (144, 16, 4, 1))
buf15 = buf14
del buf14
triton_poi_fused_convolution_5[grid(576)](buf15, primals_17, 576,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_17
buf16 = empty_strided_cuda((4, 32, 4, 4), (512, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_6[grid(2048)](buf8
, primals_11, buf16, 2048, XBLOCK=128, num_warps=4, num_stages=1)
del buf8
del primals_11
return (buf13, buf15, primals_1, primals_3, primals_4, primals_6,
primals_8, primals_10, primals_12, primals_14, primals_16, buf1,
buf3, buf5, buf7, buf9, buf11, buf16)
class dilation_layer(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, padding=
'same_padding', dilation=1):
super(dilation_layer, self).__init__()
if padding == 'same_padding':
padding = int((kernel_size - 1) / 2 * dilation)
self.Dconv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, padding=padding,
dilation=dilation)
self.Drelu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.Dconv(x)
x = self.Drelu(x)
return x
class stage_blockNew(nn.Module):
"""This class makes sure the paf and heatmap branch out in every stage"""
def __init__(self, in_channels, out_channels):
super(stage_blockNew, self).__init__()
self.Dconv_1 = dilation_layer(in_channels, out_channels=64)
self.Dconv_2 = dilation_layer(in_channels=64, out_channels=64)
self.Dconv_3 = dilation_layer(in_channels=64, out_channels=64,
dilation=2)
self.Dconv_4 = dilation_layer(in_channels=64, out_channels=32,
dilation=4)
self.Dconv_5 = dilation_layer(in_channels=32, out_channels=32,
dilation=8)
self.Mconv_6 = nn.Conv2d(in_channels=256, out_channels=128,
kernel_size=1, padding=0)
self.Mrelu_6 = nn.ReLU(inplace=True)
self.paf = nn.Conv2d(in_channels=128, out_channels=14, kernel_size=
1, padding=0)
self.heatmap = nn.Conv2d(in_channels=128, out_channels=9,
kernel_size=1, padding=0)
def forward(self, input_0):
primals_1 = self.Dconv_1.Dconv.weight
primals_2 = self.Dconv_1.Dconv.bias
primals_4 = self.Dconv_2.Dconv.weight
primals_5 = self.Dconv_2.Dconv.bias
primals_6 = self.Dconv_3.Dconv.weight
primals_7 = self.Dconv_3.Dconv.bias
primals_8 = self.Dconv_4.Dconv.weight
primals_9 = self.Dconv_4.Dconv.bias
primals_10 = self.Dconv_5.Dconv.weight
primals_11 = self.Dconv_5.Dconv.bias
primals_12 = self.Mconv_6.weight
primals_13 = self.Mconv_6.bias
primals_14 = self.paf.weight
primals_15 = self.paf.bias
primals_16 = self.heatmap.weight
primals_17 = self.heatmap.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], output[1]
|
kacel33/ActionAI_PC
|
stage_block
| false
| 15,787
|
[
"MIT"
] | 1,311
|
a0528f49ea61cc07d7c1e9a3cd6846e5f50cfae7
|
https://github.com/kacel33/ActionAI_PC/tree/a0528f49ea61cc07d7c1e9a3cd6846e5f50cfae7
|
MSELoss
|
import torch
import torch.utils.data
from torch import nn
class MSELoss(nn.Module):
def __init__(self):
super(self.__class__, self).__init__()
def forward(self, input, target):
return torch.mean(torch.sum((input - target) ** 2, 1))
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.utils.data
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_per_fused_mean_pow_sub_sum_0(in_out_ptr0, in_ptr0, in_ptr1,
xnumel, rnumel, XBLOCK: tl.constexpr):
RBLOCK: tl.constexpr = 64
xoffset = tl.program_id(0) * XBLOCK
xoffset + tl.arange(0, XBLOCK)[:, None]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
rindex = tl.arange(0, RBLOCK)[None, :]
tl.full([XBLOCK, RBLOCK], True, tl.int1)
r0 = rindex % 16
r1 = rindex // 16
tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
tmp4 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
tmp5 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
tmp9 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
tmp10 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
tmp14 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
tmp15 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
tmp2 = tmp0 - tmp1
tmp3 = tmp2 * tmp2
tmp6 = tmp4 - tmp5
tmp7 = tmp6 * tmp6
tmp8 = tmp3 + tmp7
tmp11 = tmp9 - tmp10
tmp12 = tmp11 * tmp11
tmp13 = tmp8 + tmp12
tmp16 = tmp14 - tmp15
tmp17 = tmp16 * tmp16
tmp18 = tmp13 + tmp17
tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
tmp21 = tl.sum(tmp19, 1)[:, None]
tmp22 = 64.0
tmp23 = tmp21 / tmp22
tl.debug_barrier()
tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp23, None)
def call(args):
arg0_1, arg1_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((), (), torch.float32)
buf1 = buf0
del buf0
get_raw_stream(0)
triton_per_fused_mean_pow_sub_sum_0[grid(1)](buf1, arg0_1, arg1_1,
1, 64, XBLOCK=1, num_warps=2, num_stages=1)
del arg0_1
del arg1_1
return buf1,
class MSELossNew(nn.Module):
def __init__(self):
super(self.__class__, 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]
|
kejiejiang/UnsupervisedDeepLearning-Pytorch
|
MSELoss
| false
| 15,788
|
[
"MIT"
] | 87
|
6ea7b7151ae62bf0130b56cc023f2be068aa87f0
|
https://github.com/kejiejiang/UnsupervisedDeepLearning-Pytorch/tree/6ea7b7151ae62bf0130b56cc023f2be068aa87f0
|
StageBlock
|
import torch
import torch.nn as nn
import torch.utils.data
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1):
super(ConvBlock, self).__init__()
self.Mconv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=
padding)
self.MPrelu = nn.PReLU(num_parameters=out_channels)
def forward(self, x):
x = self.Mconv(x)
x = self.MPrelu(x)
return x
class StageBlock(nn.Module):
""" L1/L2 StageBlock Template """
def __init__(self, in_channels, inner_channels, innerout_channels,
out_channels):
super(StageBlock, self).__init__()
self.Mconv1_0 = ConvBlock(in_channels, inner_channels)
self.Mconv1_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv1_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv2_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv2_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv2_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv3_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv3_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv3_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv4_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv4_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv4_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv5_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv5_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv5_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv6 = ConvBlock(inner_channels * 3, innerout_channels,
kernel_size=1, stride=1, padding=0)
self.Mconv7 = nn.Conv2d(in_channels=innerout_channels, out_channels
=out_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x):
out1_1 = self.Mconv1_0(x)
out2_1 = self.Mconv1_1(out1_1)
out3_1 = self.Mconv1_2(out2_1)
x_cat_1 = torch.cat([out1_1, out2_1, out3_1], 1)
out1_2 = self.Mconv2_0(x_cat_1)
out2_2 = self.Mconv2_1(out1_2)
out3_2 = self.Mconv2_2(out2_2)
x_cat_2 = torch.cat([out1_2, out2_2, out3_2], 1)
out1_3 = self.Mconv3_0(x_cat_2)
out2_3 = self.Mconv3_1(out1_3)
out3_3 = self.Mconv3_2(out2_3)
x_cat_3 = torch.cat([out1_3, out2_3, out3_3], 1)
out1_4 = self.Mconv4_0(x_cat_3)
out2_4 = self.Mconv4_1(out1_4)
out3_4 = self.Mconv4_2(out2_4)
x_cat_4 = torch.cat([out1_4, out2_4, out3_4], 1)
out1_5 = self.Mconv5_0(x_cat_4)
out2_5 = self.Mconv5_1(out1_5)
out3_5 = self.Mconv5_2(out2_5)
x_cat_5 = torch.cat([out1_5, out2_5, out3_5], 1)
out_6 = self.Mconv6(x_cat_5)
stage_output = self.Mconv7(out_6)
return stage_output
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_channels': 4, 'inner_channels': 4, 'innerout_channels':
4, 'out_channels': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils.data
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused__prelu_kernel_convolution_0(in_out_ptr0, in_ptr0,
in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
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')
tmp5 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = 0.0
tmp4 = tmp2 > tmp3
tmp6 = tmp5 * tmp2
tmp7 = tl.where(tmp4, tmp2, tmp6)
tl.store(in_out_ptr0 + x3, tmp2, xmask)
tl.store(out_ptr0 + x3, tmp7, 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)
@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
xnumel, XBLOCK: tl.constexpr):
xnumel = 768
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 12
x0 = xindex % 16
x2 = xindex // 192
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tmp7 = tl.full([1], 8, tl.int64)
tmp8 = tmp0 < tmp7
tmp9 = tmp6 & tmp8
tmp10 = tl.load(in_ptr1 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp9 & xmask,
other=0.0)
tmp11 = tmp0 >= tmp7
tl.full([1], 12, tl.int64)
tmp14 = tl.load(in_ptr2 + (x0 + 16 * (-8 + x1) + 64 * x2), tmp11 &
xmask, other=0.0)
tmp15 = 0.0
tmp16 = tmp14 > tmp15
tmp17 = tl.load(in_ptr3 + (-8 + x1), tmp11 & xmask, eviction_policy=
'evict_last', other=0.0)
tmp18 = tmp17 * tmp14
tmp19 = tl.where(tmp16, tmp14, tmp18)
tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype)
tmp21 = tl.where(tmp11, tmp19, tmp20)
tmp22 = tl.where(tmp9, tmp10, tmp21)
tmp23 = tl.where(tmp4, tmp5, tmp22)
tl.store(out_ptr0 + x3, tmp23, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
primals_13, primals_14, primals_15, primals_16, primals_17,
primals_18, primals_19, primals_20, primals_21, primals_22,
primals_23, primals_24, primals_25, primals_26, primals_27,
primals_28, primals_29, primals_30, primals_31, primals_32,
primals_33, primals_34, primals_35, primals_36, primals_37,
primals_38, primals_39, primals_40, primals_41, primals_42,
primals_43, primals_44, primals_45, primals_46, primals_47,
primals_48, primals_49, primals_50, primals_51) = args
args.clear()
assert_size_stride(primals_1, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4,), (1,))
assert_size_stride(primals_8, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_9, (4,), (1,))
assert_size_stride(primals_10, (4,), (1,))
assert_size_stride(primals_11, (4, 12, 3, 3), (108, 9, 3, 1))
assert_size_stride(primals_12, (4,), (1,))
assert_size_stride(primals_13, (4,), (1,))
assert_size_stride(primals_14, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_15, (4,), (1,))
assert_size_stride(primals_16, (4,), (1,))
assert_size_stride(primals_17, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_18, (4,), (1,))
assert_size_stride(primals_19, (4,), (1,))
assert_size_stride(primals_20, (4, 12, 3, 3), (108, 9, 3, 1))
assert_size_stride(primals_21, (4,), (1,))
assert_size_stride(primals_22, (4,), (1,))
assert_size_stride(primals_23, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_24, (4,), (1,))
assert_size_stride(primals_25, (4,), (1,))
assert_size_stride(primals_26, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_27, (4,), (1,))
assert_size_stride(primals_28, (4,), (1,))
assert_size_stride(primals_29, (4, 12, 3, 3), (108, 9, 3, 1))
assert_size_stride(primals_30, (4,), (1,))
assert_size_stride(primals_31, (4,), (1,))
assert_size_stride(primals_32, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_33, (4,), (1,))
assert_size_stride(primals_34, (4,), (1,))
assert_size_stride(primals_35, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_36, (4,), (1,))
assert_size_stride(primals_37, (4,), (1,))
assert_size_stride(primals_38, (4, 12, 3, 3), (108, 9, 3, 1))
assert_size_stride(primals_39, (4,), (1,))
assert_size_stride(primals_40, (4,), (1,))
assert_size_stride(primals_41, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_42, (4,), (1,))
assert_size_stride(primals_43, (4,), (1,))
assert_size_stride(primals_44, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_45, (4,), (1,))
assert_size_stride(primals_46, (4,), (1,))
assert_size_stride(primals_47, (4, 12, 1, 1), (12, 1, 1, 1))
assert_size_stride(primals_48, (4,), (1,))
assert_size_stride(primals_49, (4,), (1,))
assert_size_stride(primals_50, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_51, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
buf1 = buf0
del buf0
buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf1,
primals_2, primals_4, buf2, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_2
buf3 = extern_kernels.convolution(buf2, primals_5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf4,
primals_6, primals_7, buf5, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_6
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, 4, 4, 4), (64, 16, 4, 1))
buf7 = buf6
del buf6
triton_poi_fused_convolution_1[grid(256)](buf7, primals_9, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_9
buf8 = empty_strided_cuda((4, 12, 4, 4), (192, 16, 4, 1), torch.float32
)
triton_poi_fused_cat_2[grid(768)](buf2, buf5, buf7, primals_10,
buf8, 768, XBLOCK=256, num_warps=4, num_stages=1)
buf9 = extern_kernels.convolution(buf8, primals_11, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf9, (4, 4, 4, 4), (64, 16, 4, 1))
buf10 = buf9
del buf9
buf11 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf10,
primals_12, primals_13, buf11, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_12
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, 4, 4, 4), (64, 16, 4, 1))
buf13 = buf12
del buf12
buf14 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf13,
primals_15, primals_16, buf14, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_15
buf15 = extern_kernels.convolution(buf14, primals_17, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf15, (4, 4, 4, 4), (64, 16, 4, 1))
buf16 = buf15
del buf15
triton_poi_fused_convolution_1[grid(256)](buf16, primals_18, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_18
buf17 = empty_strided_cuda((4, 12, 4, 4), (192, 16, 4, 1), torch.
float32)
triton_poi_fused_cat_2[grid(768)](buf11, buf14, buf16, primals_19,
buf17, 768, XBLOCK=256, num_warps=4, num_stages=1)
buf18 = extern_kernels.convolution(buf17, primals_20, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf18, (4, 4, 4, 4), (64, 16, 4, 1))
buf19 = buf18
del buf18
buf20 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf19,
primals_21, primals_22, buf20, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_21
buf21 = extern_kernels.convolution(buf20, primals_23, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf21, (4, 4, 4, 4), (64, 16, 4, 1))
buf22 = buf21
del buf21
buf23 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf22,
primals_24, primals_25, buf23, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_24
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, 4, 4, 4), (64, 16, 4, 1))
buf25 = buf24
del buf24
triton_poi_fused_convolution_1[grid(256)](buf25, primals_27, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_27
buf26 = empty_strided_cuda((4, 12, 4, 4), (192, 16, 4, 1), torch.
float32)
triton_poi_fused_cat_2[grid(768)](buf20, buf23, buf25, primals_28,
buf26, 768, XBLOCK=256, num_warps=4, num_stages=1)
buf27 = extern_kernels.convolution(buf26, primals_29, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf27, (4, 4, 4, 4), (64, 16, 4, 1))
buf28 = buf27
del buf27
buf29 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf28,
primals_30, primals_31, buf29, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_30
buf30 = extern_kernels.convolution(buf29, primals_32, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf30, (4, 4, 4, 4), (64, 16, 4, 1))
buf31 = buf30
del buf30
buf32 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf31,
primals_33, primals_34, buf32, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_33
buf33 = extern_kernels.convolution(buf32, primals_35, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf33, (4, 4, 4, 4), (64, 16, 4, 1))
buf34 = buf33
del buf33
triton_poi_fused_convolution_1[grid(256)](buf34, primals_36, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_36
buf35 = empty_strided_cuda((4, 12, 4, 4), (192, 16, 4, 1), torch.
float32)
triton_poi_fused_cat_2[grid(768)](buf29, buf32, buf34, primals_37,
buf35, 768, XBLOCK=256, num_warps=4, num_stages=1)
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, 4, 4, 4), (64, 16, 4, 1))
buf37 = buf36
del buf36
buf38 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf37,
primals_39, primals_40, buf38, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_39
buf39 = extern_kernels.convolution(buf38, primals_41, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf39, (4, 4, 4, 4), (64, 16, 4, 1))
buf40 = buf39
del buf39
buf41 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf40,
primals_42, primals_43, buf41, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_42
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, 4, 4, 4), (64, 16, 4, 1))
buf43 = buf42
del buf42
triton_poi_fused_convolution_1[grid(256)](buf43, primals_45, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_45
buf44 = empty_strided_cuda((4, 12, 4, 4), (192, 16, 4, 1), torch.
float32)
triton_poi_fused_cat_2[grid(768)](buf38, buf41, buf43, primals_46,
buf44, 768, XBLOCK=256, num_warps=4, num_stages=1)
buf45 = extern_kernels.convolution(buf44, primals_47, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf45, (4, 4, 4, 4), (64, 16, 4, 1))
buf46 = buf45
del buf45
buf47 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
triton_poi_fused__prelu_kernel_convolution_0[grid(256)](buf46,
primals_48, primals_49, buf47, 256, XBLOCK=256, num_warps=4,
num_stages=1)
del primals_48
buf48 = extern_kernels.convolution(buf47, primals_50, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf48, (4, 4, 4, 4), (64, 16, 4, 1))
buf49 = buf48
del buf48
triton_poi_fused_convolution_1[grid(256)](buf49, primals_51, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_51
return (buf49, primals_1, primals_3, primals_4, primals_5, primals_7,
primals_8, primals_10, primals_11, primals_13, primals_14,
primals_16, primals_17, primals_19, primals_20, primals_22,
primals_23, primals_25, primals_26, primals_28, primals_29,
primals_31, primals_32, primals_34, primals_35, primals_37,
primals_38, primals_40, primals_41, primals_43, primals_44,
primals_46, primals_47, primals_49, primals_50, buf1, buf2, buf4,
buf5, buf7, buf8, buf10, buf11, buf13, buf14, buf16, buf17, buf19,
buf20, buf22, buf23, buf25, buf26, buf28, buf29, buf31, buf32,
buf34, buf35, buf37, buf38, buf40, buf41, buf43, buf44, buf46, buf47)
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=1):
super(ConvBlock, self).__init__()
self.Mconv = nn.Conv2d(in_channels=in_channels, out_channels=
out_channels, kernel_size=kernel_size, stride=stride, padding=
padding)
self.MPrelu = nn.PReLU(num_parameters=out_channels)
def forward(self, x):
x = self.Mconv(x)
x = self.MPrelu(x)
return x
class StageBlockNew(nn.Module):
""" L1/L2 StageBlock Template """
def __init__(self, in_channels, inner_channels, innerout_channels,
out_channels):
super(StageBlockNew, self).__init__()
self.Mconv1_0 = ConvBlock(in_channels, inner_channels)
self.Mconv1_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv1_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv2_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv2_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv2_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv3_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv3_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv3_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv4_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv4_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv4_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv5_0 = ConvBlock(inner_channels * 3, inner_channels)
self.Mconv5_1 = ConvBlock(inner_channels, inner_channels)
self.Mconv5_2 = ConvBlock(inner_channels, inner_channels)
self.Mconv6 = ConvBlock(inner_channels * 3, innerout_channels,
kernel_size=1, stride=1, padding=0)
self.Mconv7 = nn.Conv2d(in_channels=innerout_channels, out_channels
=out_channels, kernel_size=1, stride=1, padding=0)
def forward(self, input_0):
primals_1 = self.Mconv1_0.Mconv.weight
primals_2 = self.Mconv1_0.Mconv.bias
primals_4 = self.Mconv1_0.MPrelu.weight
primals_5 = self.Mconv1_1.Mconv.weight
primals_6 = self.Mconv1_1.Mconv.bias
primals_7 = self.Mconv1_1.MPrelu.weight
primals_8 = self.Mconv1_2.Mconv.weight
primals_9 = self.Mconv1_2.Mconv.bias
primals_10 = self.Mconv1_2.MPrelu.weight
primals_11 = self.Mconv2_0.Mconv.weight
primals_12 = self.Mconv2_0.Mconv.bias
primals_13 = self.Mconv2_0.MPrelu.weight
primals_14 = self.Mconv2_1.Mconv.weight
primals_15 = self.Mconv2_1.Mconv.bias
primals_16 = self.Mconv2_1.MPrelu.weight
primals_17 = self.Mconv2_2.Mconv.weight
primals_18 = self.Mconv2_2.Mconv.bias
primals_19 = self.Mconv2_2.MPrelu.weight
primals_20 = self.Mconv3_0.Mconv.weight
primals_21 = self.Mconv3_0.Mconv.bias
primals_22 = self.Mconv3_0.MPrelu.weight
primals_23 = self.Mconv3_1.Mconv.weight
primals_24 = self.Mconv3_1.Mconv.bias
primals_25 = self.Mconv3_1.MPrelu.weight
primals_26 = self.Mconv3_2.Mconv.weight
primals_27 = self.Mconv3_2.Mconv.bias
primals_28 = self.Mconv3_2.MPrelu.weight
primals_29 = self.Mconv4_0.Mconv.weight
primals_30 = self.Mconv4_0.Mconv.bias
primals_31 = self.Mconv4_0.MPrelu.weight
primals_32 = self.Mconv4_1.Mconv.weight
primals_33 = self.Mconv4_1.Mconv.bias
primals_34 = self.Mconv4_1.MPrelu.weight
primals_35 = self.Mconv4_2.Mconv.weight
primals_36 = self.Mconv4_2.Mconv.bias
primals_37 = self.Mconv4_2.MPrelu.weight
primals_38 = self.Mconv5_0.Mconv.weight
primals_39 = self.Mconv5_0.Mconv.bias
primals_40 = self.Mconv5_0.MPrelu.weight
primals_41 = self.Mconv5_1.Mconv.weight
primals_42 = self.Mconv5_1.Mconv.bias
primals_43 = self.Mconv5_1.MPrelu.weight
primals_44 = self.Mconv5_2.Mconv.weight
primals_45 = self.Mconv5_2.Mconv.bias
primals_46 = self.Mconv5_2.MPrelu.weight
primals_47 = self.Mconv6.Mconv.weight
primals_48 = self.Mconv6.Mconv.bias
primals_49 = self.Mconv6.MPrelu.weight
primals_50 = self.Mconv7.weight
primals_51 = self.Mconv7.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])
return output[0]
|
kacel33/ActionAI_PC
|
StageBlock
| false
| 15,789
|
[
"MIT"
] | 1,311
|
a0528f49ea61cc07d7c1e9a3cd6846e5f50cfae7
|
https://github.com/kacel33/ActionAI_PC/tree/a0528f49ea61cc07d7c1e9a3cd6846e5f50cfae7
|
SeparableConv
|
import torch
import torch.nn as nn
import torch.utils
import torch.nn.parallel
class SeparableConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, bias):
super(SeparableConv, self).__init__()
padding = (kernel_size - 1) // 2
self.depthwise = nn.Conv2d(in_planes, in_planes, kernel_size=
kernel_size, padding=padding, groups=in_planes, bias=bias)
self.pointwise = nn.Conv2d(in_planes, out_planes, kernel_size=1,
bias=bias)
def forward(self, x):
out = self.depthwise(x)
out = self.pointwise(out)
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'in_planes': 4, 'out_planes': 4, 'kernel_size': 4, 'bias': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
import torch.nn as nn
import torch.utils
import torch.nn.parallel
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
@triton.jit
def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
.constexpr):
xnumel = 144
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 9 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tl.store(in_out_ptr0 + x3, tmp2, xmask)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 4, 4), (16, 16, 4, 1))
assert_size_stride(primals_2, (4,), (1,))
assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(primals_4, (4, 4, 1, 1), (4, 1, 1, 1))
assert_size_stride(primals_5, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1,
1), padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=4, bias=None)
assert_size_stride(buf0, (4, 4, 3, 3), (36, 9, 3, 1))
buf1 = buf0
del buf0
get_raw_stream(0)
triton_poi_fused_convolution_0[grid(144)](buf1, primals_2, 144,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_2
buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf2, (4, 4, 3, 3), (36, 9, 3, 1))
buf3 = buf2
del buf2
triton_poi_fused_convolution_0[grid(144)](buf3, primals_5, 144,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_5
return buf3, primals_1, primals_3, primals_4, buf1
class SeparableConvNew(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, bias):
super(SeparableConvNew, self).__init__()
padding = (kernel_size - 1) // 2
self.depthwise = nn.Conv2d(in_planes, in_planes, kernel_size=
kernel_size, padding=padding, groups=in_planes, bias=bias)
self.pointwise = nn.Conv2d(in_planes, out_planes, kernel_size=1,
bias=bias)
def forward(self, input_0):
primals_1 = self.depthwise.weight
primals_2 = self.depthwise.bias
primals_4 = self.pointwise.weight
primals_5 = self.pointwise.bias
primals_3 = input_0
output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
return output[0]
|
kcyu2014/eval-nas
|
SeparableConv
| false
| 15,790
|
[
"MIT"
] | 47
|
385376a3ef96336b54ee7e696af1d02b97aa5c32
|
https://github.com/kcyu2014/eval-nas/tree/385376a3ef96336b54ee7e696af1d02b97aa5c32
|
ConstractiveLoss
|
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class ConstractiveLoss(nn.Module):
def __init__(self, margin=2.0, dist_flag='l2'):
super(ConstractiveLoss, self).__init__()
self.margin = margin
self.dist_flag = dist_flag
def various_distance(self, out_vec_t0, out_vec_t1):
if self.dist_flag == 'l2':
distance = F.pairwise_distance(out_vec_t0, out_vec_t1, p=2)
if self.dist_flag == 'l1':
distance = F.pairwise_distance(out_vec_t0, out_vec_t1, p=1)
if self.dist_flag == 'cos':
similarity = F.cosine_similarity(out_vec_t0, out_vec_t1)
distance = 1 - 2 * similarity / np.pi
return distance
def forward(self, out_vec_t0, out_vec_t1, label):
distance = self.various_distance(out_vec_t0, out_vec_t1)
constractive_loss = torch.sum((1 - label) * torch.pow(distance, 2) +
label * torch.pow(torch.clamp(self.margin - distance, min=0.0), 2))
return constractive_loss
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand(
[4, 4, 4, 4])]
def get_init_inputs():
return [[], {}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_add_norm_sub_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 64
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x0 = xindex
tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last')
tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
tmp12 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp13 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp18 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp19 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
)
tmp2 = tmp0 - tmp1
tmp3 = 1e-06
tmp4 = tmp2 + tmp3
tmp5 = tmp4 * tmp4
tmp8 = tmp6 - tmp7
tmp9 = tmp8 + tmp3
tmp10 = tmp9 * tmp9
tmp11 = tmp5 + tmp10
tmp14 = tmp12 - tmp13
tmp15 = tmp14 + tmp3
tmp16 = tmp15 * tmp15
tmp17 = tmp11 + tmp16
tmp20 = tmp18 - tmp19
tmp21 = tmp20 + tmp3
tmp22 = tmp21 * tmp21
tmp23 = tmp17 + tmp22
tmp24 = libdevice.sqrt(tmp23)
tl.store(out_ptr0 + x0, tmp24, xmask)
@triton.jit
def triton_per_fused_add_clamp_mul_pow_rsub_sum_1(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)
r2 = rindex
r0 = rindex % 64
tmp0 = tl.load(in_ptr0 + r2, None)
tmp3 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last')
tmp1 = 1.0
tmp2 = tmp1 - tmp0
tmp4 = tmp3 * tmp3
tmp5 = tmp2 * tmp4
tmp6 = 2.0
tmp7 = tmp6 - tmp3
tmp8 = 0.0
tmp9 = triton_helpers.maximum(tmp7, tmp8)
tmp10 = tmp9 * tmp9
tmp11 = tmp0 * tmp10
tmp12 = tmp5 + tmp11
tmp13 = tl.broadcast_to(tmp12, [RBLOCK])
tmp15 = triton_helpers.promote_to_tensor(tl.sum(tmp13, 0))
tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp15, None)
def call(args):
arg0_1, arg1_1, arg2_1 = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_add_norm_sub_0[grid(64)](arg1_1, arg0_1, buf0, 64,
XBLOCK=64, num_warps=1, num_stages=1)
del arg0_1
del arg1_1
buf1 = empty_strided_cuda((), (), torch.float32)
triton_per_fused_add_clamp_mul_pow_rsub_sum_1[grid(1)](arg2_1, buf0,
buf1, 1, 256, num_warps=2, num_stages=1)
del arg2_1
del buf0
return buf1,
class ConstractiveLossNew(nn.Module):
def __init__(self, margin=2.0, dist_flag='l2'):
super(ConstractiveLossNew, self).__init__()
self.margin = margin
self.dist_flag = dist_flag
def various_distance(self, out_vec_t0, out_vec_t1):
if self.dist_flag == 'l2':
distance = F.pairwise_distance(out_vec_t0, out_vec_t1, p=2)
if self.dist_flag == 'l1':
distance = F.pairwise_distance(out_vec_t0, out_vec_t1, p=1)
if self.dist_flag == 'cos':
similarity = F.cosine_similarity(out_vec_t0, out_vec_t1)
distance = 1 - 2 * similarity / np.pi
return distance
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]
|
kensakurada/SceneChangeDet
|
ConstractiveLoss
| false
| 15,791
|
[
"MIT"
] | 199
|
0530e0162863fec0c5296188526f0d27e0109814
|
https://github.com/kensakurada/SceneChangeDet/tree/0530e0162863fec0c5296188526f0d27e0109814
|
l1normalization
|
import torch
import torch.nn as nn
class l1normalization(nn.Module):
def __init__(self, scale):
super(l1normalization, self).__init__()
self.scale = scale
def forward(self, x, dim=1):
return self.scale * x * x.pow(1).sum(dim).clamp(min=1e-12).rsqrt(
).expand_as(x)
def get_inputs():
return [torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'scale': 1.0}]
|
import torch
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x0 = xindex % 16
x1 = xindex // 16 % 4
tmp0 = tl.load(in_ptr0 + x3, xmask)
tmp3 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp4 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp8 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask, eviction_policy=
'evict_last')
tmp1 = 1.0
tmp2 = tmp0 * tmp1
tmp5 = tmp3 + tmp4
tmp7 = tmp5 + tmp6
tmp9 = tmp7 + tmp8
tmp10 = 1e-12
tmp11 = triton_helpers.maximum(tmp9, tmp10)
tmp12 = libdevice.rsqrt(tmp11)
tmp13 = tmp2 * tmp12
tl.store(out_ptr0 + x3, tmp13, xmask)
def call(args):
arg0_1, = args
args.clear()
assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
num_warps=4, num_stages=1)
del arg0_1
return buf0,
class l1normalizationNew(nn.Module):
def __init__(self, scale):
super(l1normalizationNew, self).__init__()
self.scale = scale
def forward(self, input_0):
arg0_1 = input_0
output = call([arg0_1])
return output[0]
|
kensakurada/SceneChangeDet
|
l1normalization
| false
| 15,792
|
[
"MIT"
] | 199
|
0530e0162863fec0c5296188526f0d27e0109814
|
https://github.com/kensakurada/SceneChangeDet/tree/0530e0162863fec0c5296188526f0d27e0109814
|
QueryModule
|
import torch
from torch import nn
from torch.nn import functional as F
class QueryModule(nn.Module):
"""
A neural module that takes as input a feature map and an attention and produces a feature
map as output.
Extended Summary
----------------
A :class:`QueryModule` takes a feature map and an attention mask as input. It attends to the
feature map via an elementwise multiplication with the attention mask, then processes this
attended feature map via a series of convolutions to extract relevant information.
For example, a :class:`QueryModule` tasked with determining the color of objects would output a
feature map encoding what color the attended object is. A module intended to count would output
a feature map encoding the number of attended objects in the scene.
Parameters
----------
dim: int
The number of channels of each convolutional filter.
"""
def __init__(self, dim: 'int'):
super().__init__()
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
torch.nn.init.kaiming_normal_(self.conv1.weight)
torch.nn.init.kaiming_normal_(self.conv2.weight)
self.dim = dim
def forward(self, feats, attn):
attended_feats = torch.mul(feats, attn.repeat(1, self.dim, 1, 1))
out = F.relu(self.conv1(attended_feats))
out = F.relu(self.conv2(out))
return out
def get_inputs():
return [torch.rand([4, 4, 64, 64]), torch.rand([4, 1, 64, 64])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch 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_mul_repeat_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x0 = xindex % 4096
x2 = xindex // 16384
tmp0 = tl.load(in_ptr0 + x3, None)
tmp1 = tl.load(in_ptr1 + (x0 + 4096 * x2), None, eviction_policy=
'evict_last')
tmp2 = tmp0 * tmp1
tl.store(out_ptr0 + x3, tmp2, None)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 4
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.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_2(in_out_ptr0,
in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
tl.full([XBLOCK], True, tl.int1)
x3 = xindex
x1 = xindex // 4096 % 4
tmp0 = tl.load(in_out_ptr0 + x3, None)
tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.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)
def call(args):
primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
args.clear()
assert_size_stride(primals_1, (4, 1, 64, 64), (4096, 4096, 64, 1))
assert_size_stride(primals_2, (4, 4, 64, 64), (16384, 4096, 64, 1))
assert_size_stride(primals_3, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.float32)
get_raw_stream(0)
triton_poi_fused_mul_repeat_0[grid(65536)](primals_2, primals_1,
buf0, 65536, XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = extern_kernels.convolution(buf0, primals_3, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 64, 64), (16384, 4096, 64, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_relu_1[grid(65536)](buf2, primals_4,
65536, XBLOCK=512, num_warps=4, num_stages=1)
del primals_4
buf3 = extern_kernels.convolution(buf2, primals_5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 64, 64), (16384, 4096, 64, 1))
buf4 = buf3
del buf3
buf5 = empty_strided_cuda((4, 4, 64, 64), (16384, 4096, 64, 1),
torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_2[grid(65536)](
buf4, primals_6, buf5, 65536, XBLOCK=512, num_warps=4, num_stages=1
)
del primals_6
return buf4, primals_3, primals_5, buf0, buf2, buf5
class QueryModuleNew(nn.Module):
"""
A neural module that takes as input a feature map and an attention and produces a feature
map as output.
Extended Summary
----------------
A :class:`QueryModule` takes a feature map and an attention mask as input. It attends to the
feature map via an elementwise multiplication with the attention mask, then processes this
attended feature map via a series of convolutions to extract relevant information.
For example, a :class:`QueryModule` tasked with determining the color of objects would output a
feature map encoding what color the attended object is. A module intended to count would output
a feature map encoding the number of attended objects in the scene.
Parameters
----------
dim: int
The number of channels of each convolutional filter.
"""
def __init__(self, dim: 'int'):
super().__init__()
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
torch.nn.init.kaiming_normal_(self.conv1.weight)
torch.nn.init.kaiming_normal_(self.conv2.weight)
self.dim = dim
def forward(self, input_0, input_1):
primals_3 = self.conv1.weight
primals_4 = self.conv1.bias
primals_5 = self.conv2.weight
primals_6 = self.conv2.bias
primals_2 = input_0
primals_1 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6])
return output[0]
|
kdexd/probnmn-clevr
|
QueryModule
| false
| 15,793
|
[
"MIT"
] | 69
|
9c1b2286cf30e9fb045370153c9242a39760e02e
|
https://github.com/kdexd/probnmn-clevr/tree/9c1b2286cf30e9fb045370153c9242a39760e02e
|
ComparisonModule
|
import torch
from torch import nn
from torch.nn import functional as F
class ComparisonModule(nn.Module):
"""
A neural module that takes as input two feature maps and produces a feature map as output.
Extended Summary
----------------
A :class:`ComparisonModule` takes two feature maps as input and concatenates these. It then
processes the concatenated features and produces a feature map encoding whether the two input
feature maps encode the same property.
This block is useful in making integer comparisons, for example to answer the question, "Are
there more red things than small spheres?" It can also be used to determine whether some
relationship holds of two objects (e.g. they are the same shape, size, color, or material).
Parameters
----------
dim: int
The number of channels of each convolutional filter.
"""
def __init__(self, dim: 'int'):
super().__init__()
self.projection = nn.Conv2d(2 * dim, dim, kernel_size=1, padding=0)
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
torch.nn.init.kaiming_normal_(self.conv1.weight)
torch.nn.init.kaiming_normal_(self.conv2.weight)
def forward(self, in1, in2):
out = torch.cat([in1, in2], 1)
out = F.relu(self.projection(out))
out = F.relu(self.conv1(out))
out = F.relu(self.conv2(out))
return out
def get_inputs():
return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]
def get_init_inputs():
return [[], {'dim': 4}]
|
import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch import nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
@triton.jit
def triton_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
constexpr):
xnumel = 512
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x1 = xindex // 16 % 8
x0 = xindex % 16
x2 = xindex // 128
x3 = xindex
tmp0 = x1
tl.full([1], 0, tl.int64)
tmp3 = tl.full([1], 4, tl.int64)
tmp4 = tmp0 < tmp3
tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0)
tmp6 = tmp0 >= tmp3
tl.full([1], 8, tl.int64)
tmp9 = tl.load(in_ptr1 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp6 & xmask,
other=0.0)
tmp10 = tl.where(tmp4, tmp5, tmp9)
tl.store(out_ptr0 + x3, tmp10, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
XBLOCK: tl.constexpr):
xnumel = 256
xoffset = tl.program_id(0) * XBLOCK
xindex = xoffset + tl.arange(0, XBLOCK)[:]
xmask = xindex < xnumel
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tl.store(in_out_ptr0 + x3, tmp4, xmask)
@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_2(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
x3 = xindex
x1 = xindex // 16 % 4
tmp0 = tl.load(in_out_ptr0 + x3, xmask)
tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
tmp2 = tmp0 + tmp1
tmp3 = tl.full([1], 0, tl.int32)
tmp4 = triton_helpers.maximum(tmp3, tmp2)
tmp5 = 0.0
tmp6 = tmp4 <= tmp5
tl.store(in_out_ptr0 + x3, tmp4, xmask)
tl.store(out_ptr0 + x3, tmp6, xmask)
def call(args):
(primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
primals_7, primals_8) = 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, 8, 1, 1), (8, 1, 1, 1))
assert_size_stride(primals_4, (4,), (1,))
assert_size_stride(primals_5, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_6, (4,), (1,))
assert_size_stride(primals_7, (4, 4, 3, 3), (36, 9, 3, 1))
assert_size_stride(primals_8, (4,), (1,))
with torch.cuda._DeviceGuard(0):
torch.cuda.set_device(0)
buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32)
get_raw_stream(0)
triton_poi_fused_cat_0[grid(512)](primals_1, primals_2, buf0, 512,
XBLOCK=256, num_warps=4, num_stages=1)
del primals_1
del primals_2
buf1 = extern_kernels.convolution(buf0, primals_3, stride=(1, 1),
padding=(0, 0), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1))
buf2 = buf1
del buf1
triton_poi_fused_convolution_relu_1[grid(256)](buf2, primals_4, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_4
buf3 = extern_kernels.convolution(buf2, primals_5, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1))
buf4 = buf3
del buf3
triton_poi_fused_convolution_relu_1[grid(256)](buf4, primals_6, 256,
XBLOCK=128, num_warps=4, num_stages=1)
del primals_6
buf5 = extern_kernels.convolution(buf4, primals_7, stride=(1, 1),
padding=(1, 1), dilation=(1, 1), transposed=False,
output_padding=(0, 0), groups=1, bias=None)
assert_size_stride(buf5, (4, 4, 4, 4), (64, 16, 4, 1))
buf6 = buf5
del buf5
buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
triton_poi_fused_convolution_relu_threshold_backward_2[grid(256)](buf6,
primals_8, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1)
del primals_8
return buf6, primals_3, primals_5, primals_7, buf0, buf2, buf4, buf7
class ComparisonModuleNew(nn.Module):
"""
A neural module that takes as input two feature maps and produces a feature map as output.
Extended Summary
----------------
A :class:`ComparisonModule` takes two feature maps as input and concatenates these. It then
processes the concatenated features and produces a feature map encoding whether the two input
feature maps encode the same property.
This block is useful in making integer comparisons, for example to answer the question, "Are
there more red things than small spheres?" It can also be used to determine whether some
relationship holds of two objects (e.g. they are the same shape, size, color, or material).
Parameters
----------
dim: int
The number of channels of each convolutional filter.
"""
def __init__(self, dim: 'int'):
super().__init__()
self.projection = nn.Conv2d(2 * dim, dim, kernel_size=1, padding=0)
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
torch.nn.init.kaiming_normal_(self.conv1.weight)
torch.nn.init.kaiming_normal_(self.conv2.weight)
def forward(self, input_0, input_1):
primals_3 = self.projection.weight
primals_4 = self.projection.bias
primals_5 = self.conv1.weight
primals_6 = self.conv1.bias
primals_7 = self.conv2.weight
primals_8 = self.conv2.bias
primals_1 = input_0
primals_2 = input_1
output = call([primals_1, primals_2, primals_3, primals_4,
primals_5, primals_6, primals_7, primals_8])
return output[0]
|
kdexd/probnmn-clevr
|
ComparisonModule
| false
| 15,794
|
[
"MIT"
] | 69
|
9c1b2286cf30e9fb045370153c9242a39760e02e
|
https://github.com/kdexd/probnmn-clevr/tree/9c1b2286cf30e9fb045370153c9242a39760e02e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.